pax_global_header00006660000000000000000000000064137643647320014531gustar00rootroot0000000000000052 comment=47f862c9f5c23e1aa09fb8659b4b19028397197b OCSInventory-Server-2.8.1/000077500000000000000000000000001376436473200153475ustar00rootroot00000000000000OCSInventory-Server-2.8.1/.github/000077500000000000000000000000001376436473200167075ustar00rootroot00000000000000OCSInventory-Server-2.8.1/.github/Contributing.md000066400000000000000000000123101376436473200216750ustar00rootroot00000000000000

Banner

OCS Inventory

Some Links:
Ask question | Installation | Website

# OCS Inventory Contributing Guidelines ## Pull Request Process 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Add your changes: `git add folder/file1.php` 4. Commit your changes: `git commit -m 'Add some feature'` 5. Push to the branch: `git push origin my-new-feature` 6. Submit a pull request ! ## Pull Request Informations When contributing, please open an issue before or contact the team using mail. This will prevent all the duplicate of work. Also, check if your contribution is not already in the roadmap or affiliated to an issue. If you are contributing on a small scale (translation, a few line modification), you don't need open an issue or contact the team but you will need to explain what you've done in the Pull Request comment and provide as accurate commit messages as possible. Cf. Commits Messages Name Informations If you need to discuss about a big change or need some help of our team during the development of your contribution, we can use other communication method like Telegram, IRC, Skype. ## Commits Messages Name Informations Try to create as accurate as possible commit messages. This will help us to speed up the review process and to reduce the misunderstanding (which can lead to a Pull Request to be rejected) There is no commit messages convention but here are some examples : 1. Create as short as possible commit name 2. One commit for one modification 3. Always leave the second commit line blank If it seems difficult to summarize what your commit does, it may be because it includes several logical changes or bug fixes, and are better split up into several commits using `git add -p`. ## Code of Conduct ### Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ### Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ### Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ### Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at `contact@ocsinventory-ng.org` . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ OCSInventory-Server-2.8.1/.github/ISSUE_TEMPLATE.md000066400000000000000000000005441376436473200214170ustar00rootroot00000000000000*It's hard to solve a problem when important details are missing, that why we added this template, to help you and us.* ### General informations Operating system : ### Server informations Perl version : Mysql / Mariadb / Percona version : ### OCS Inventory informations Ocs server version : ### Problem's description *Describe your problem here* OCSInventory-Server-2.8.1/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000007451376436473200225160ustar00rootroot00000000000000## Important notes Please, don't mistake OCSInventory-server with OCSInventory-ocsreports : * OCSInventory-server : Communication server that manage the inventory * OCSInventory-ocsreports : Web interface of OCS Inventory ## General informations : Operating system : ## Server informations : Perl version : Mysql / Mariadb / Percona version : ## Status : **READY/IN DEVELOPMENT/HOLD** ## Description : A few sentences describing the overall goals of the pull request's commits. OCSInventory-Server-2.8.1/.gitignore000066400000000000000000000000741376436473200173400ustar00rootroot00000000000000/nbproject/private/ # add ocsreports directory ocsreports/ OCSInventory-Server-2.8.1/.travis.yml000066400000000000000000000003411376436473200174560ustar00rootroot00000000000000language: perl perl: - "5.30" - "5.28" - "5.26" - "5.20" before_install: - cpanm --quiet --installdeps --notest . script: cd Apache && perl Makefile.PL && make install branches: only: - masterOCSInventory-Server-2.8.1/Apache/000077500000000000000000000000001376436473200165305ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Changes000066400000000000000000000406701376436473200200320ustar00rootroot00000000000000Revision history for Apache::Ocsinventory 2.2 RC * Add plugins web service which is used by the plugin engine to install plugin ( Use SOAP::Lite ) * Add compatibility with Apache 2.4 and more : https://github.com/OCSInventory-NG/OCSInventory-Server/commit/861dcb17f826d9580f0f5f0937bd1ae7376e6602 2.2beta1 * Add and requests tags in SOAP engine to be able to exclude tags or ids during SOAP requests * Add new 'batteries' inventory section to get various batteries data * New OCS_OPT_SNMP_PRINT_HTTPS_ERROR configuration option to enable or disable error message display about agent https communication in logfile * Fix bug in SOAP engine while retrieving data from type tables 2.1.2 2.1.1 * Fix Bug #1315004 about MySQL replication broken using MySQL 5.6 * Fix Bug #1311852 and Bug #1296633 about CHECKSUM updated for all computers * Fix a mistake for OCS_PLUGINS_PERL_DIR and OCS_PLUGINS_CONF_DIR options in ocsinventory-server.conf 2.1 * Add new fields for printers table in Map.pm * Fix Bug #1214436 about removing already registered hosts and add Mac support in ipdiscover-util.pl * Add a new table for SNMP virtual machines data in Map.pm * Fix Bug #1248582 about custom field names not decoded in SOAP ACCOUNTINFO * Fix Bug #1191791 about CHECKSUM value not updated when NOTIFY mode send new network changes * New plugins system to be able to add new entries in Map.pm and more... 2.1rc1 * Add availibility to specify a post command for a package deployment * SOAP engine is now able to get SNMP devices inventory * Add new 'sims' inventory section to get various SIM card data from phone devices * Add availibility to schedule a package deployment * Remove OCS_OPT_SUPPORT configuration option and XML tag in PROLOG * Add availibility to reforce a package deployment * Add availability to specify custom MIBS for SNMP scans * Add availability to specify a custom network address for SNMP scans * New OCS_OPT_DOWNLOAD_EXECUTION_TIMEOUT configuration option to prevent package commands to run indefinitely * setup.sh script can now detect Suse/OpenSuse distributions * Add new 'cpus' inventory section to get various CPU data * Add a new field in hardware section to get the computer architecture * Add new fields for snmp_loadbalancer table in Map.pm * Fix Bug #1085020 about ERR_ALREADY_IN_HISTORY message that should be success * Prevent bugs in NOTIFY mode with older XML behaviour 2.0.5 * Create "logs" and "scripts" directories for administration console in setup.sh 2.0.4 2.0.3 * Fix Bug #881406 about security issue due to snmp_com.txt file which is no longer used * Do not take care of comment lines when getting external useragents file content * Fix various bugs in NOTIFY mode 2.0.2 * Add availibilty to allow external useragents using a text file 2.0.1 * Remove 'Satisfy any' Apache directive in ocsinventory-server.conf * Fix RPM packages names in setup.sh * Fix Bug #800418 about subnet, gateway and IP DHCP informations disappearance from database * Increase php_value post_max_size and php_value upload_max_filesize values to 101 Mo and 100 Mo in ocsinventory-reports.conf * Change php_value to php_flag for magic_quotes_gpc setting in ocsinventory-reports.conf * Add new useragents for iOS and Android OCS agents in Useragent.pm 2.0 * New OCS_OPT_SUPPORT configuration option for OCS Inventory support activation * Add a new XML tag in PROLOG * Add a new module to manage OCS support: Support.pm * Add a XML tag in NOTIFY request to update IPDHCP field in database 2.0 rc4 * Add a warning in setup.sh about what has to be done if the OS has newsyslog installed (BSD systems) * Fix Bug #744022 about logrotate configuration in setup.sh even if the OS has not logrotate installed * Add availability to specify mysql socket in ipdiscover-util.pl * Fix UTF8 problem while comparing accountinfo strings after inventory step 2.0 rc3 * Use OCS_OPT_DBI_MYSQL_SOCKET in SOAP engine if needed * Ipdiscover now uses useragent instead of OSNAME for automatic election * Fix Bug #721278 about hardware_osname cache table. This table is now feeded by engine * Verify that HARDWARE_ID are not groups when computing groups caches * Disable MySQL strict mode by default * Fix Bug #726522 about OCS_OPT_DBI_MYSQL_SOCKET option in ocsinventory-server.conf * Don't process the sections that are use for capacities special inventory in SOAP engine (but thats the way its meant to be) * Fix a bug in Download.pm: ERR_ALREADY_IN_HISTORY message was never added in devices table * Fix SQL syntax error and add a capacities tables exclusion in Duplicate.pm 2.0 rc2 * Add a new variable $Apache::Ocsinventory::BUILD_VERSION in Ocsinventory.pm * Fix Bug #694760 about utf8 strings broken 2.0 rc1 * New OCS server module : Snmp.pm . It is use for SNMP integration in OCS Inventory NG. This module comes with Snmp/Data.pm and Snmp/Inventory.pm * Add Useragent.pm to control agents and their versions to solve versions incompatibilty problems between OCS agents and OCS server * Add a new parameter for tables in Map.pm: mandatory. This parameter force database feeding even if inventory section is not in XML * Control if inventory section is in XML before writing it in database to avoid bugs. * Add COMMENTS and VERSION fields in snmp_softwares table * Add new fields in softwares table: GUID, LANGUAGE, LASTDATE and BITSWIDTH * Debug and enhance Data.pm to use the availability to explode database structure using type tables * Add new module Datafiler.pm. This module add availibity to filter data from HARDWARE section (data filtered won't be stored in database) * setup.sh can now install missing perl modules for you using yum or apt-get (Philippe Beaumont) * Add new fileds "DEVICEPORT" and "DEVICETYPE" in snmp_networks table in Map.pm * Add a new field "SYSTEM" for snmp_blades, snmp_firewalls and snmp_loadbalancer tables in Map.pm * Add new tables for SNMP computers data in Map.pm * Add a new table "snmp_switchinfos" in Map.pm * snmp_switchs table is "multi" now in Map.pm * Add the copy of the snmp_com.txt file in setup.sh to set default SNMP "public" community if this file does not exists * Fix various mistakes and missing fields for snmp tables in Map.pm * Add the new Apache configuration for SNMP communities reference file (snmp_com.txt) in setup.sh and ocsinventory-reports.conf * Enhance DB backend by reducing the SQL request number as possible in SNMP inventory * Enhance errors management for SNMP inventory * New OCS_OPT_SNMP_INVENTORY_DIFF config option to enable or disable the SNMP inventory sections update regarding to snmp_laststate table * Add a CHECKSUM for SNMP devices. It is compute using mask values from SNMP inventory sections from Map.pm . * New snmp_laststate table to store md5 hashes for SNMP inventory sections (this table is used for SNMP inventory sections update in database) * SNMP inventory sections are updated in database only if changed since last inventory * Snmp.pm send the snmp_com.txt file URI to the agent * New table snmp_accountinfo * Feel the SNMP_ID filed in snmp_accountinfo when a new SNMP device coming * Feel the TAG field in the snmp_accountinfo while inventory for SNMP devices * Add STATUS and ERRORSTATE fields for snmp_printers table * Map.pm: snmp_networksconnected and snmp_switchs are now auto => 0 due to the special treatments associated to this tables * Don't take care of identified network devices for SNMP scans in Snmp.pm. This devices will be scanned using SNMP too * Add the MAC address in the PROLOG response in Snmp.pm * Use of _get_snmp_parser_ForceArray subroutine to get sections for the 'ForceArray' in Snmp.pm * Add LASTDATE field in the snmp table to store the last inventory date for a SNMP device * Enhance SNMP implementation by getting SNMP communities informations directly from the snmp_communities table * Enable the SNMP activation/deactivation using custom parameters on computer on groups * Map.pm: new table parameter -> capacities * Map.pm: add new tables for SNMP * Data.pm : use the new "capacities" Map.pm parameter to don't take care of tables that have this parameter when feeding %SECTIONS and @SECTIONS * Config.pm : add a new configuration option for activate/desactivate SNMP feature * ocsinventory-server.conf : add Snmp.pm in Capacities list and add a new configuration option for activate/desactivate SNMP feature * Correct Bug #563791 about GW and SUBNET update in NOTIFY * Correct Bug #563791 about GW and SUBNET update in NOTIFY * Correct a misprint about the use of 'OCS_OPT_UNICODE_SUPPORT' in Data.pm (from sisfb_tech) * Useragent.pm: allow the future 4062 Windows agent and some code cleaning by using a hash reference for %CURRENT_CONTEXT * Add the Windows rearch agent to allow in Useragent.pm * ASSETTAG is in BIOS, not HARDWARE 1.3.3 * Force XML::Simple to use XML::Parser instead of XML::SAX to fix disastrous performance issues in Redhat distribution due to the perl-XML-SAX package problems. * Correct bug about automatic IPDISCOVER election 1.3 * Unix right: add the exec flag * Quote HARDWARE/TYPE * Save SOFTWARE/FROM (Stéphane Urbanovski) * SQL quote for all the hardware fields * SQL syntax fix. Duplicate 'WHERE' (axil_76) * Decrease OCS_OPT_GROUPS_CACHE_* from one day to 10 minutes * Fix: Computer with ASSETTAG are not inventoried * Save HARDWARE/UUID * Avoid err 500 if ACCOUNTINFO is not found for a given inventory * Added printers.DESCRIPTION * Added OCS_OPT_ACCEPT_TAG_UPDATE_FROM_CLIENT from trunk * DTD updates 1.3 beta2 * fix setup.sh for Debian * minor fixes * add binutils/create-release-tarball.sh 1.3 beta1 * Added virtual device detection for a network iface * Added description field to printers section * Use of hardware.UUID and hardware.ASSETTAG in duplicates detection * Duplicates mgmt: Now removing current device from dynamic groups and keep the static groups membership * The SOAP service is now able to share data with engine in +w mode by the use of ::System::_lock() * Deleting computers using SOAP service http://sourceforge.net/tracker/?func=detail&aid=2776298&group_id=58373&atid=487495 * itmgmt_comments support in duplicates * Download: Added ERR_ALREADY_IN_HISTORY status code (package affected but already in history) * Added source IP in inventory https://sourceforge.net/tracker/?func=detail&aid=2807594&group_id=58373&atid=487495 * Added DRIVES/CREATEDATE support https://sourceforge.net/tracker/?func=detail&atid=487495&aid=2275640&group_id=58373 * Added ASSETTAG support https://sourceforge.net/tracker/index.php?func=detail&aid=2804146&group_id=58373&atid=487495 * Added DNS device informations https://sourceforge.net/tracker/?func=detail&aid=1566957&group_id=58373&atid=487495 * Fixed .ocs files generation on windows server https://sourceforge.net/tracker/index.php?func=detail&aid=2817320&group_id=58373&atid=487492 * Mobile devices support https://sourceforge.net/tracker/index.php?func=detail&aid=2810746&group_id=58373&atid=487495 * Fixed the "bad software import bug" https://sourceforge.net/tracker/index.php?func=detail&aid=2129983&group_id=58373&atid=487492 * DB schema changes support through "type=>1" field meta information in Map.pm * Unicode support https://sourceforge.net/tracker/index.php?func=detail&aid=2796796&group_id=58373&atid=487495 Thanks to Andrek * Added DEFAULTGATEWAY support * Added inventory of virtualization (Philippe Libat) * Fixed a bug in SOAP Engine https://sourceforge.net/tracker/?func=detail&atid=487492&aid=2787130&group_id=58373 1.02 final * Handling the trailing '/' in deploy feature and calling _end in more standard way (Ocsinventory.pm) * Fix a typo (logging) in System.pm (OCS_OPT_LOGPATH) Thx to Remi Collet * Fix: call to _accountinfo() in Inventory.pm whereas Update::AccountInfos not in the scope 1.02 RC2 * Fix the problem of feeding cache when write_diff is OFF * Fix the duplicate error in packages history (download) 1.02 RC1 * As the dictionary and "all softs" are inventory cache dependent = INVENTORY_CACHE_REVALIDATE default => 7 * Fixed the DEVICEID checking * Important fix in "on the fly deletion" in inventory cache * Added fallback values for '??' (unix agents prior than 0.8) * Added OCS_OPT_INVENTORY_CACHE_KEEP setting * Inventory_cache deletion is handled "on the fly" * Inventory cache clean now retry on fault * Inventory cache clean is now off by default * IPDISCOVER: Do not evaluate if mode is local * Added LOCAL_FL to CURRENT_CONTEXT * The default Ip(hardware.IPADDR) is now based on REMOTE_ADDR (or HTTP_X_FORWARDED_FOR) * Added IS_TRUSTED test if INVENTORY_SESSION_ONLY * Inventory_cache is now computed on row level * Moved user agent update in prolog stage * Added old_deviceid log * Added "fallback" field's attribute to Map.pm * Added OCS_OPT_COMPRESS_TRY_OTHERS setting * Notify: Added IP address update event handling * Added Notify.pm capacity * Fix a bug in DATA_MAP: accountinfos is a "multi" section * Added log when using compression different than raw ZLIB * Added -path parameter to ipdiscover-util.pl (changes in GUI for FHS support) * Added OCS_OPT_INVENTORY_SESSION_ONLY: An inventory is accepted only if it is required by server * Added session (prolog=>post_inventory) Options: SESSION_VALIDITY_TIME, SESSION_CLEAN_TIME * Added error 523 * Added OCS_OPT_* parameters checking to server starting * Bug fix in inventory cache revalidate (lock fault) * Added disable caches computation (group and inventory) feature (REVALIDATE* set to 0) * Removed inventory cache checking for a section that has not changed since last inventory * Added OCS_OPT_OPTIONS_NOT_OVERLOADED (configure engine to take its settings from file only) * Higher server's verbosity * Bug fix: Do not handle in Duplicates the "auto => 0" sections * Bug fix: Replacement of a "one shot" computer generates an error (QUALITY is NULL) * Bug fix: do not close logfile if LOGLEVEL is off * Added ocsinventory-log.pl sample and associated README * A few improvements and fixes on web service * Added groups.REVALIDATE_FROM field : groups.CREATE_TIME is now the real groups computation date * Added a minimal system to load external methods in web service (OCS_OPT_WEB_SERVICE_PRIV_MODS_CONF) * Added ipdiscover_delete_type_V1() to web service * Added ipdiscover_create_type_V1() to web service * Added ipdiscover_untag_V1() to web service * Added ipdiscover_remove_V1() to web service * Added ipdiscover_tag_V1() to web service * Added get_ipdiscover_device() to web service * Added OCS_OPT_WEB_SERVICE_RESULTS_LIMIT setting * Added XML::Entities dependency on SOAP service (as SOAP::Lite may not decode CDATA) * Web service upgrade ( bug fixes, and many improvements) * New configuration system using Apache::Ocsinventory::Server::System::Config * Groups are now computed using DB Slae if available * Engine extensions : "Option" renamed to "Capacity" * Changed module structure * Code improvement for Inventory.pm * Added model serial as auto duplicate criteria * Added INVENTORY_WRITE_DIFF for lower load on DB backends and more afficient sql query cache * Added Slave DB backend support (for read: soap engine...etc) * PROLOG_FREQ specific parameter handling (computer, mass processing and group levels) * DOWNLOAD* specific parameters handling (computer, mass processing and group levels) * IPDISCOVER specific parameter handling (computer, mass processing and group levels) * Computer's groups support (dynamic and static) * blacklists of MAC and SERIAL are now handled from database * Multiple ocs servers support (Backends) * Trusted computers support (filter exceptions) * GZIP compression support * No compression support * inventory cache handling improved OCSInventory-Server-2.8.1/Apache/INSTALL000066400000000000000000000046261376436473200175710ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Communication Server Perl Module Setup # # Copyleft 2006 Pascal DANEK # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ This module handles communication between OCS Inventory NG agents and server. It acts as an Apache extension and require following PERL Modules. - 'DBI' => 1.40 or higher - 'Apache::DBI' => 0.93 or higher - 'DBD::mysql' => 2.9004 or higher - 'Compress::Zlib' => 1.33 or higher - 'XML::Simple' => 2.12 or higher - 'Net::IP' => 1.21 or higher To setup it, just follow traditional PERL Module installation procedure. - perl Makefile.PL - make - make install This will install OCS Inventory NG Communication Server PERL Module into standard PERL includes directory. Next, you have to to configure Apache web server to load Communication Server at startup. You can use provided etc/ocsinventory/ocsinventory-server.conf file as sample. Apache must have module mod_perl enabled. As configuration differs from mod_perl 1.999_21 or previous AND mod_perl 1.999_22 or higher, you must specify which release of mod_perl your Apache is using. On Linux computers, you can find which release of mod_perl is installed by running the following command: - On RPM enabled OS, rpm -q mod_perl - On DPKG enabled OS, dpkg -l libapache*-mod-perl* You must set the value of PERL constant OCS_MODPERL_VERSION to 1 if mod_perl 1.999_21 or previous is used by Apache, or to 2 if mod_perl 1.999_22 and higher is used by Apache. Update constants OCS_DB_HOST and OCS_DB_PORT to specify where is MySQL database server. Generally, set localhost and 3306 if MySQL is on the same computer. Update constant OCS_LOGPATH to specify where Communication Server must write logs, if they are enabled. Remember to allow web server to write in this directory ! File etc/logrotate.d/ocsinventory-server is a sample to enable rotation of Communication Server logs. Directory binutils contains useful perl scripts to batch import locally generated inventory results (.ocs files), to analyse Communication Server logs... Refer to README in directory. Enjoy ;-) OCSInventory-Server-2.8.1/Apache/LICENSE000066400000000000000000000431031376436473200175360ustar00rootroot00000000000000 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. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively 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 program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, 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. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. OCSInventory-Server-2.8.1/Apache/MANIFEST000066400000000000000000000033151376436473200176630ustar00rootroot00000000000000Changes INSTALL LICENSE MANIFEST This list of files Makefile.PL Ocsinventory.pm Ocsinventory/Interface.pm Ocsinventory/Interface/Config.pm Ocsinventory/Interface/Database.pm Ocsinventory/Interface/Extensions.pm Ocsinventory/Interface/History.pm Ocsinventory/Interface/Internals.pm Ocsinventory/Interface/Inventory.pm Ocsinventory/Interface/Ipdiscover.pm Ocsinventory/Interface/Snmp.pm Ocsinventory/Interface/Updates.pm Ocsinventory/Map.pm Ocsinventory/Plugins.pm Ocsinventory/Plugins/Modules.pm Ocsinventory/Server/Capacities/Datafilter.pm Ocsinventory/Server/Capacities/Download.pm Ocsinventory/Server/Capacities/Download/Inventory.pm Ocsinventory/Server/Capacities/Example.pm Ocsinventory/Server/Capacities/Filter.pm Ocsinventory/Server/Capacities/Ipdiscover.pm Ocsinventory/Server/Capacities/Notify.pm Ocsinventory/Server/Capacities/Registry.pm Ocsinventory/Server/Capacities/Snmp.pm Ocsinventory/Server/Capacities/Snmp/Data.pm Ocsinventory/Server/Capacities/Snmp/Inventory.pm Ocsinventory/Server/Capacities/Update.pm Ocsinventory/Server/Communication.pm Ocsinventory/Server/Communication/Session.pm Ocsinventory/Server/Constants.pm Ocsinventory/Server/Duplicate.pm Ocsinventory/Server/Groups.pm Ocsinventory/Server/Inventory.pm Ocsinventory/Server/Inventory/Cache.pm Ocsinventory/Server/Inventory/Capacities.pm Ocsinventory/Server/Inventory/Data.pm Ocsinventory/Server/Inventory/Export.pm Ocsinventory/Server/Inventory/Filter.pm Ocsinventory/Server/Inventory/Update.pm Ocsinventory/Server/Inventory/Update/AccountInfos.pm Ocsinventory/Server/Inventory/Update/Hardware.pm Ocsinventory/Server/Modperl1.pm Ocsinventory/Server/Modperl2.pm Ocsinventory/Server/System.pm Ocsinventory/Server/System/Config.pm Ocsinventory/Server/Useragent.pm OCSInventory-Server-2.8.1/Apache/Makefile.PL000066400000000000000000000032031376436473200205000ustar00rootroot00000000000000#------------------------------------------------------- # # $Id: Makefile.PL,v 1.6 2008-02-27 21:26:27 dliroulet Exp $ # #------------------------------------------------------- ################################################################################ # # OCS Inventory NG Communication Server Perl Module Setup # # Copyleft 2006 Pascal DANEK # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Apache::Ocsinventory', 'VERSION_FROM' => 'Ocsinventory.pm', 'PREREQ_PM' => { 'DBI' => 1.40, # no DBI can never be any fun. 'Apache::DBI' => 0.93, # no Apache::DBI can never be any fun. 'Compress::Zlib' => 1.33, # no Compress:Zlib can never be any fun. 'DBD::mysql' => 2.9004, # no DBD::mysql can never be any fun. 'XML::Simple' => 2.12, # no XML::Simple can never be any fun. 'Net::IP' => 1.21, # no Net::IP can never be any fun. }, # 'EXE_FILES' => ['binutils/ocsinventory-injector.pl'], # 'INSTALLSCRIPT' => "/usr/bin", # 'INSTALLSITESCRIPT' => "/usr/bin", ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (AUTHOR => 'Pascal DANEK ') : ()), ); # EOF OCSInventory-Server-2.8.1/Apache/Ocsinventory.pm000066400000000000000000000253411376436473200215750ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); }else{ if(!defined($ENV{'OCS_MODPERL_VERSION'})){ die("OCS_MODPERL_VERSION not defined. Abort\n"); }else{ die("OCS_MODPERL_VERSION set to, a bad parameter. Must be '1' or '2'. Abort\n"); } } } $Apache::Ocsinventory::VERSION = '2.8.1'; $Apache::Ocsinventory::BUILD_VERSION = '780'; $XML::Simple::PREFERRED_PARSER = 'XML::Parser'; # Ocs modules use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::System qw /:server _modules_get_request_handler /; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Inventory; use Apache::Ocsinventory::Server::Groups; use Apache::Ocsinventory::Server::Useragent; # To compress the tx and read the rx use Compress::Zlib; use Encode; # Globale structure our %CURRENT_CONTEXT; our @XMLParseOptForceArray;# Obsolete, for 1.01 modules only my %XML_PARSER_OPT; our @TRUSTED_IP; sub handler{ my $d; my $status; my $r; my $data; my $raw_data; my $inflated; my $query; my $dbMode; # current context # Will be used to handle all globales %CURRENT_CONTEXT = ( 'APACHE_OBJECT' => undef, 'RAW_DATA' => undef, #'DBI_HANDLE' => undef, # DBI_SL_HANDLE => undef 'DEVICEID' => undef, 'DATABASE_ID' => undef, 'DATA' => undef, 'XML_ENTRY' => undef, 'XML_INVENTORY' => undef, 'LOCK_FL' => 0, 'EXIST_FL' => 0, 'MEMBER_OF' => undef, 'DEFLATE_SUB' => \&Compress::Zlib::compress, 'IS_TRUSTED' => 0, 'DETAILS' => undef, 'PARAMS' => undef, 'PARAMS_G' => undef, 'MEMBER_OF' => undef, 'IPADDRESS' => $ENV{'HTTP_X_FORWARDED_FOR'}?$ENV{'HTTP_X_FORWARDED_FOR'}:$ENV{'REMOTE_ADDR'}, 'USER_AGENT' => undef, 'LOCAL_FL' => undef ); # No buffer for STDOUT select(STDOUT); $|=1; # Get the data and the apache object $r=shift; $CURRENT_CONTEXT{'APACHE_OBJECT'} = $r; $CURRENT_CONTEXT{'USER_AGENT'} = &_get_http_header('User-agent', $r); @TRUSTED_IP = $r->dir_config->get('OCS_OPT_TRUSTED_IP'); #Connect to database $dbMode = 'write'; if($Apache::Ocsinventory::CURRENT_CONTEXT{'USER_AGENT'} =~ /local/i){ $CURRENT_CONTEXT{'LOCAL_FL'}=1; $dbMode = 'local'; } if(!($CURRENT_CONTEXT{'DBI_HANDLE'} = &_database_connect( $dbMode ))){ &_log(505,'handler','Database connection'); return &_end(APACHE_SERVER_ERROR); } if(!($CURRENT_CONTEXT{'DBI_SL_HANDLE'} = &_database_connect( 'read' ))){ &_log(505,'handler','Database Slave connection'); return &_end(APACHE_SERVER_ERROR); } #Retrieve server options if(&_get_sys_options()){ &_log(503,'handler', 'System options'); return &_end(APACHE_SERVER_ERROR); } # First, we determine the http method # The get method will be only available for the bootstrap to manage the deploy, and maybe, sometime to give files which will be stored in the database if($r->method() eq 'GET'){ # To manage the first contact with the bootstrap # The uri must be '/ocsinventory/deploy/[filename]' if($r->uri()=~/deploy\/([^\/]+)\/?$/){ if($ENV{'OCS_OPT_DEPLOY'}){ return &_end(&_send_file('deploy',$1)); }else{ return &_end(APACHE_FORBIDDEN); } }elsif($r->uri()=~/update\/(.+)\/(.+)\/(\d+)\/?/){ # We use the GET method for the update to use the proxies # The URL is built like that : [OCSFSERVER]/ocsinventory/[os]/[name]/[version] if($ENV{'OCS_OPT_UPDATE'}){ return &_end(&_send_file('update',$1,$2,$3)); }else{ return &_end(APACHE_FORBIDDEN); } }else{ # If the url is invalid return &_end(APACHE_BAD_REQUEST); } # Here is the post method management }elsif($r->method eq 'POST'){ # Get the data if( !read(STDIN, $data, $ENV{'CONTENT_LENGTH'}) ){ &_log(512,'handler','Reading request') if $ENV{'OCS_OPT_LOGLEVEL'}; return &_end(APACHE_SERVER_ERROR); } # Copying buffer because inflate() modify it $raw_data = $data; $CURRENT_CONTEXT{'RAW_DATA'} = \$raw_data; # Debug level for Apache::DBI (apache/error.log) # $Apache::DBI::DEBUG=2; # Read the request # Possibilities : # prolog : The agent wants to know if he have to send an inventory (and with which options) # update : The agent wants to know if there is a newer version available # inventory : It is an inventory # system : Request to know the server's time response (and if it's alive) not yet implemented # file : Download files when upgrading (For the moment, only when upgrading) ################################################## # # Inflate the data unless($d = Compress::Zlib::inflateInit()){ &_log(506,'handler','Compress stage') if $ENV{'OCS_OPT_LOGLEVEL'}; return &_end(APACHE_BAD_REQUEST); } ($inflated, $status) = $d->inflate($data); unless( $status == Z_OK or $status == Z_STREAM_END){ if( $ENV{OCS_OPT_COMPRESS_TRY_OTHERS} ){ &_inflate(\$raw_data, \$inflated); } else{ undef $inflated; } if(!$inflated){ &_log(506,'handler','Compress stage'); return &_end(APACHE_SERVER_ERROR); } } # Unicode support - The XML may not use UTF8 if($ENV{'OCS_OPT_UNICODE_SUPPORT'}) { if($inflated =~ /^.+encoding="([\w+\-]+)/) { my $enc = $1; $inflated =~ s/$enc/UTF-8/; Encode::from_to($inflated, "$enc", "utf8"); } } $CURRENT_CONTEXT{'DATA'} = \$inflated; ########################## # Parse the XML request # Retrieving xml parsing options if needed &_get_xml_parser_opt( \%XML_PARSER_OPT ) unless %XML_PARSER_OPT; eval { $query = XML::Simple::XMLin( $inflated, %XML_PARSER_OPT ); } or do { unless($query = XML::Simple::XMLin( encode('utf8',$inflated), %XML_PARSER_OPT )){ &_log(507,'handler','Xml stage'); return &_end(APACHE_BAD_REQUEST); } }; $query = verif_xml($query); $CURRENT_CONTEXT{'XML_ENTRY'} = $query; # Get the request type my $request=$query->{QUERY}; $CURRENT_CONTEXT{'DEVICEID'} = $query->{DEVICEID} or $CURRENT_CONTEXT{'DEVICEID'} = $query->{CONTENT}->{DEVICEID}; unless($request eq 'UPDATE'){ if(&_check_deviceid($Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'})){ &_log(502,'inventory','Bad deviceid') if $ENV{'OCS_OPT_LOGLEVEL'}; return &_end(APACHE_BAD_REQUEST); } } # Must be filled unless($request){ &_log(500,'handler','Request not defined'); return &_end(APACHE_BAD_REQUEST); } # Init global structure my $err = &_init(); return &_end($err) if $err; # The three above are hardcoded if($request eq 'PROLOG'){ my $ret = &_prolog(); return(&_end($ret)); }elsif($request eq 'INVENTORY'){ my $ret = &_inventory_handler(); return(&_end($ret)) }elsif($request eq 'SYSTEM'){ my $ret = &_system_handler(); return(&_end($ret)); }else{ # Other request are handled by options my $handler = &_modules_get_request_handler($request); if($handler == 0){ &_log(500,'handler', 'No handler'); return APACHE_BAD_REQUEST; }else{ my $ret = &{$handler}(\%CURRENT_CONTEXT); return(&_end($ret)); } } }else{ return APACHE_FORBIDDEN } } sub _init{ my $request; # Retrieve Device if exists $request = $CURRENT_CONTEXT{'DBI_HANDLE'}->prepare(' SELECT DEVICEID,ID,UNIX_TIMESTAMP(LASTCOME) AS LCOME,UNIX_TIMESTAMP(LASTDATE) AS LDATE,QUALITY,FIDELITY FROM hardware WHERE DEVICEID=?' ); unless($request->execute($CURRENT_CONTEXT{'DEVICEID'})){ return(APACHE_SERVER_ERROR); } for my $ipreg (@TRUSTED_IP){ if($CURRENT_CONTEXT{'IPADDRESS'}=~/^$ipreg$/){ &_log(310,'handler','trusted_computer') if $ENV{'OCS_OPT_LOGLEVEL'}; $CURRENT_CONTEXT{'IS_TRUSTED'} = 1; } } if($request->rows){ my $row = $request->fetchrow_hashref; $CURRENT_CONTEXT{'EXIST_FL'} = 1; $CURRENT_CONTEXT{'DATABASE_ID'} = $row->{'ID'}; $CURRENT_CONTEXT{'DETAILS'} = { 'LCOME' => $row->{'LCOME'}, 'LDATE' => $row->{'LDATE'}, 'QUALITY' => $row->{'QUALITY'}, 'FIDELITY' => $row->{'FIDELITY'}, }; # Computing groups list if($ENV{'OCS_OPT_ENABLE_GROUPS'}){ $CURRENT_CONTEXT{'MEMBER_OF'} = [ &_get_groups() ]; } else{ $CURRENT_CONTEXT{'MEMBER_OF'} = []; } $CURRENT_CONTEXT{'PARAMS'} = { &_get_spec_params() }; $CURRENT_CONTEXT{'PARAMS_G'} = { &_get_spec_params_g() }; }else{ $CURRENT_CONTEXT{'EXIST_FL'} = 0; $CURRENT_CONTEXT{'MEMBER_OF'} = []; } $request->finish; return; } # XML string verification sub verif_xml{ my ($query) = @_; my $key; my $exp; my $exp2; for(%{$query->{CONTENT}}){ if(ref($_) ne 'ARRAY'){ $key = $_; if(ref($query->{CONTENT}->{$key}) eq 'ARRAY'){ for(@{$query->{CONTENT}->{$key}}){ for(%{$_}){ $exp = $_; $exp2 = $exp =~ s/ //gr; if($exp2 =~ m/=\(/ && $exp2 =~ m/\)/){ $_ = 1; } } } } if(ref($query->{CONTENT}->{$key}) eq 'HASH'){ for(%{$query->{CONTENT}->{$key}}){ $exp = $_; $exp2 = $exp =~ s/ //gr; if($exp2 =~ m/=\(/ && $exp2 =~ m/\)/){ $_ = 1; } } } } } return $query; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/000077500000000000000000000000001376436473200212325ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface.pm000066400000000000000000000146651376436473200235040ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface; use Apache::Ocsinventory::Interface::Internals; use Apache::Ocsinventory::Interface::Database; require Apache::Ocsinventory::Interface::Ipdiscover; require Apache::Ocsinventory::Interface::Inventory; require Apache::Ocsinventory::Interface::Config; require Apache::Ocsinventory::Interface::History; require Apache::Ocsinventory::Interface::Extensions; require Apache::Ocsinventory::Interface::Updates; require Apache::Ocsinventory::Interface::Snmp; use strict; $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT} = 100 if !defined $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; eval{ if( $ENV{OCS_OPT_WEB_SERVICE_PRIV_MODS_CONF} ){ require $ENV{OCS_OPT_WEB_SERVICE_PRIV_MODS_CONF} or die($!); } }; if($@){ print STDERR "ocsinventory-server: $@\n"; print STDERR "ocsinventory-server: Can't load $ENV{OCS_OPT_WEB_SERVICE_PRIV_MODS_CONF} - Web service Private extensions will be unavailable\n"; }; # ===== ACCESSOR TO COMPUTER'S DATA ===== sub get_computers_V1{ my $class = shift; # Xml request my $request = shift; return Apache::Ocsinventory::Interface::Inventory::get_computers( $request ); } sub delete_computers_by_id_V1{ my $class = shift ; my @ids = @_ ; return Apache::Ocsinventory::Interface::Updates::delete_computers_by_id( \@ids ); } # ===== CONFIGURATION METHODS ===== # Read a general config parameter # If a value is provided, set it to given parameters # If only a tvalue is given, set ivalue to NULL sub ocs_config_V1{ my $class = shift; my ($key, $value) = @_; return send_error('BAD_KEY') unless $key =~ /^[_\w]+$/; if( defined( $key ) and defined( $value ) ){ $key = decode_xml( $key ); $value = decode_xml( $value ); Apache::Ocsinventory::Interface::Config::ocs_config_write( $key, $value, undef ) if defined($value); } return Apache::Ocsinventory::Interface::Config::ocs_config_read( $key, 1 ); } sub ocs_config_V2{ my $class = shift; my ($key, $ivalue, $tvalue) = @_; return send_error('BAD_KEY') unless $key =~ /^[_\w]+$/; if( defined( $key ) and ( defined( $ivalue) or defined( $tvalue) ) ){ $key = decode_xml( $key ); $ivalue = decode_xml( $ivalue ) if defined $ivalue; $tvalue = decode_xml( $tvalue ) if defined $tvalue; my ($error, $result ) = Apache::Ocsinventory::Interface::Config::ocs_config_write( $key, $ivalue, $tvalue ); return $result if $error; } return Apache::Ocsinventory::Interface::Config::ocs_config_read( $key, 0 ); } # ===== SOFTWARE DICTIONARY ===== # Get a software dictionary word sub get_dico_soft_element_V1{ my( $class, $word ) = @_; $word = decode_xml( $word ); return Apache::Ocsinventory::Interface::Inventory::get_dico_soft_extracted( $word ); } # ===== CHECKSUM UPDATE ===== sub reset_checksum_V1 { my $class = shift; my $checksum = shift; return send_error('BAD_CHECKSUM') unless $checksum =~ /^\d+$/; for(@_){ return send_error('BAD_ID') unless $_ =~ /^\d+$/; } return Apache::Ocsinventory::Interface::Internals::reset_checksum( $checksum, \@_ ); } # ===== EVENTS TRACKING ===== # Get computer's history sub get_history_V1{ my( $class, $offset ) = @_; return send_error('BAD_OFFSET') unless $offset =~ /^\d+$/; return Apache::Ocsinventory::Interface::History::get_history_events( $offset ); } # Clear computer's history sub clear_history_V1{ my( $class, $offset ) = @_; return send_error('BAD_OFFSET') unless $offset =~ /^\d+$/; return Apache::Ocsinventory::Interface::History::clear_history_events( $offset ); } # ===== IPDISCOVER METHODS ===== sub get_ipdiscover_devices_V1{ my $class = shift; my ( $date, $offset, $nInv ) = @_; $nInv = 0 if !defined $nInv; return send_error('BAD_DATE') unless $date =~ /^\d{4}-\d{2}-\d{2}(\s\d\d(:\d\d){2})?$/; return send_error('BAD_OFFSET') unless $offset =~ /^\d+$/; return send_error('BAD_THIRD_PARAMETER') unless $nInv =~ /^(?:0|1)$/; return Apache::Ocsinventory::Interface::Ipdiscover::get_ipdiscover_devices( $date, $offset, $nInv ); } sub ipdiscover_tag_V1 { my $class = shift; my ( $device, $description, $type, $user ) = @_; $description = decode_xml( $description ); $type = decode_xml( $type ); $user = decode_xml( $user ); return send_error('BAD_MAC') unless $device =~ /^\w\w(.\w\w){5}$/; return Apache::Ocsinventory::Interface::Ipdiscover::ipdiscover_tag( $device, $description, $type, $user ); } sub ipdiscover_untag_V1{ my $class = shift; my $device = shift; return send_error('BAD_MAC') unless $device =~ /^\w\w(.\w\w){5}$/; return Apache::Ocsinventory::Interface::Ipdiscover::ipdiscover_untag( $device ); } sub ipdiscover_remove_V1{ my $class = shift; my $device = shift; return send_error('BAD_MAC') unless $device =~ /^\w\w(.\w\w){5}$/; return Apache::Ocsinventory::Interface::Ipdiscover::ipdiscover_remove( $device ); } sub ipdiscover_create_type_V1{ my $class = shift; my $type = shift; $type = decode_xml( $type ); return Apache::Ocsinventory::Interface::Ipdiscover::ipdiscover_add_type( $type ); } sub ipdiscover_delete_type_V1{ my $class = shift; my $type = shift; $type = decode_xml( $type ); return Apache::Ocsinventory::Interface::Ipdiscover::ipdiscover_del_type( $type ); } # ===== ACCESSOR TO SNMP DATA ===== sub get_snmp_V1{ my $class = shift; # Xml request my $request = shift; return Apache::Ocsinventory::Interface::Snmp::get_snmp( $request ); } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/000077500000000000000000000000001376436473200231325ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/AssetCategory.pm000066400000000000000000000057471376436473200262620ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::AssetCategory; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use strict; use warnings; use DBI qw(:sql_types); require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / set_asset_category /; sub set_asset_category{ my @cats = get_asset_category(); my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $hardware = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}->{CONTENT}->{HARDWARE}; foreach my $cat (@cats) { my @args = split(/,/, $cat->{SQL_ARGS}); my @part_query = split(/\?/, $cat->{SQL_QUERY}); my $query; my $execution; for (my $i = 0; $i < scalar @part_query; $i++){ if ($args[$i]) { $query .= $part_query[$i] . $args[$i]; } else { $query .= $part_query[$i]; } } $execution = $dbh->prepare($query); $execution->execute(); while (my $row = $execution->fetchrow_hashref()){ if ($row->{hardwareNAME} eq $hardware->{NAME}) { $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}->{CONTENT}->{HARDWARE}->{CATEGORY_ID} = $cat->{ID}; } } } return 1; } sub get_asset_category{ my $sth; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $sql; my @cats; $sql = "SELECT ID, SQL_QUERY, SQL_ARGS FROM assets_categories"; my $result = $dbh->prepare($sql); $result->execute; while( my $row = $result->fetchrow_hashref() ){ my $sql_query = $row->{SQL_QUERY}; $sql_query =~ s/%s/?/g; push @cats, { 'ID' => $row->{ID}, 'SQL_QUERY' => $sql_query, 'SQL_ARGS' => $row->{SQL_ARGS} } } return @cats; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Config.pm000066400000000000000000000062361376436473200247040ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Config; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use Apache::Ocsinventory::Server::System::Config; use XML::Simple; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / /; sub ocs_config_is_supported{ my $setting = shift; return grep { $_ eq $setting } Apache::Ocsinventory::Server::System::Config::get_settings(); } # Return a config value sub ocs_config_read{ my ($key, $legacy) = @_; unless( ocs_config_is_supported( $key ) ){ return send_error( 'KEY_NOT_SUPPORTED' ); } my $sth = get_sth('SELECT IVALUE,TVALUE FROM config WHERE NAME=?', $key); unless($sth->rows){ $sth->finish(); return undef; } my ($i,$t) = $sth->fetchrow_array(); $sth->finish(); if( $legacy ){ return $i; } else{ return XMLout ( { 'IVALUE' =>[$i], 'TVALUE' =>[$t] }, RootName => 'RESULT' ); } } sub ocs_config_is_valid { my ($key, $ivalue, $tvalue ) = @_; my $testedValue; if( $CONFIG{$key}->{type} eq 'IVALUE' ){ $testedValue = $ivalue; } elsif( $CONFIG{$key}->{type} eq 'TVALUE' ){ $testedValue = $tvalue; } else{ return 0; } return $testedValue =~ $CONFIG{$key}->{filter}; } # Set a config value in "config" table # If ocs GUI is not used, # you have to change parameters in ocsinventory.conf sub ocs_config_write{ my( $key, $ivalue, $tvalue ) = @_; if( ocs_config_is_supported( $key ) ){ if( !ocs_config_is_valid( $key, $ivalue, $tvalue ) ){ return (1, send_error( 'VALUE_NOT_VALID' )); } my $sth = get_sth("SELECT * FROM config WHERE NAME=?", $key); if( !$sth->rows ){ do_sql("INSERT INTO config(NAME) VALUES(?)", $key); } $sth->finish(); do_sql("UPDATE config SET IVALUE=? WHERE NAME=?", $ivalue, $key ) if defined $ivalue; do_sql("UPDATE config SET TVALUE=? WHERE NAME=?", $tvalue, $key ) if defined $tvalue; } else{ return ( 1, send_error( 'KEY_NOT_SUPPORTED' ) ); } 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Database.pm000066400000000000000000000130411376436473200251730ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Database; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / database_connect get_sth get_dbh_write get_dbh_read do_sql get_hardware_table_pk get_snmp_table_pk get_type_name untaint_dbstring untaint_dbstring_lst /; # Database connection sub database_connect{ my $dbHost; my $dbName; my $dbPort; my $dbUser; my $dbPwd; my %params; my $mode = shift; my $env_mode_prefix = 'OCS_DB'; if( $mode eq 'read' && $ENV{'OCS_DB_SL_HOST'} ){ $dbHost = $ENV{'OCS_DB_SL_HOST'}; $dbName = $ENV{'OCS_DB_SL_NAME'}||'ocsweb'; $dbPort = $ENV{'OCS_DB_SL_PORT'}||'3306'; $dbUser = $ENV{'OCS_DB_SL_USER'}; $dbPwd = $Apache::Ocsinventory::SOAP::apache_req->dir_config('OCS_DB_SL_PWD'); $env_mode_prefix .= '_SL'; } else{ $dbHost = $ENV{'OCS_DB_HOST'}; $dbName = $ENV{'OCS_DB_NAME'}||'ocsweb'; $dbPort = $ENV{'OCS_DB_PORT'}||'3306'; $dbUser = $ENV{'OCS_DB_USER'}; $dbPwd = $Apache::Ocsinventory::SOAP::apache_req->dir_config('OCS_DB_PWD'); } # Optionnaly a mysql socket different than the client's built in $params{'mysql_socket'} = $ENV{'OCS_OPT_DBI_MYSQL_SOCKET'} if $ENV{'OCS_OPT_DBI_MYSQL_SOCKET'}; my $mysql_ssl_mode = ''; if( defined($ENV{$env_mode_prefix.'_SSL_ENABLED'}) and $ENV{$env_mode_prefix.'_SSL_ENABLED'} == 1 ) { if( defined($ENV{$env_mode_prefix.'_SSL_MODE'}) and $ENV{$env_mode_prefix.'_SSL_MODE'} eq 'SSL_MODE_PREFERRED' ) { $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_optional=1'; } elsif( defined($ENV{$env_mode_prefix.'_SSL_MODE'}) and $ENV{$env_mode_prefix.'_SSL_MODE'} eq 'SSL_MODE_REQUIRED' ) { $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_verify_server_cert=0'; } elsif( defined($ENV{$env_mode_prefix.'_SSL_MODE'}) and $ENV{$env_mode_prefix.'_SSL_MODE'} eq 'SSL_MODE_STRICT' ) { $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_verify_server_cert=1'; } else { # SSL Is enabled but mode hasn't been provided. Let's put PREFERRED mode by default $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_optional=1'; } if( defined( $ENV{$env_mode_prefix.'_SSL_CLIENT_KEY'} ) and defined( $ENV{$env_mode_prefix.'_SSL_CLIENT_CERT'} ) and defined( $ENV{$env_mode_prefix.'_SSL_CA_CERT'} ) ) { $mysql_ssl_mode .= ';mysql_ssl_client_key='.$ENV{$env_mode_prefix.'_SSL_CLIENT_KEY'}.';mysql_ssl_client_cert='.$ENV{$env_mode_prefix.'_SSL_CLIENT_CERT'}.';mysql_ssl_ca_file='.$ENV{$env_mode_prefix.'_SSL_CA_CERT'}; } } # Connection... my $dbh = DBI->connect( "DBI:mysql:database=$dbName;host=$dbHost;port=$dbPort".$mysql_ssl_mode, $dbUser, $dbPwd, \%params); unless($dbh) { die DBI->errstr; } $dbh->do("SET NAMES 'utf8'") if($dbh && $ENV{'OCS_OPT_UNICODE_SUPPORT'}); $dbh->do("SET sql_mode='NO_ENGINE_SUBSTITUTION'"); return $dbh; } # Process the sql requests (prepare) sub get_sth { my ($sql, @values) = @_; my $dbh = database_connect( get_db_mode( $sql ) ); my $request = $dbh->prepare( $sql ); $request->execute( @values ) or die("==Bad request==\nSQL:$sql\nDATAS:".join "> <", @values, "\n"); return $request; } # Return dbi handles for particular use sub get_dbh_write { return database_connect('write') ; } sub get_dbh_read { return database_connect('read') ; } # Process the sql requests (do) sub do_sql { my ($sql, @values) = @_; my $dbh = database_connect( get_db_mode($sql) ); return $dbh->do( $sql, {}, @values ); } # Return the id field of an inventory section sub get_hardware_table_pk{ my $section = shift; return ($section eq 'hardware')?'ID':'HARDWARE_ID'; } sub get_snmp_table_pk{ my $section = shift; return ($section eq 'snmp')?'ID':'SNMP_ID'; } sub get_type_name{ my ($section, $field, $value) = @_ ; my $table_name = 'type_'.lc $section.'_'.lc $field ; my $name ; my $existsSql = "SELECT NAME FROM $table_name WHERE ID=?" ; my $existsReq = get_sth($existsSql, $value) ; my $row = $existsReq->fetchrow_hashref() ; $name = $row->{NAME} ; $existsReq->finish ; return $name ; } sub untaint_dbstring{ my $string = shift; $string =~ s/"/\\"/g; $string =~ s/'/\\'/g; return $string; } sub untaint_dbstring_lst{ my @list = @_; my @quoted; for (@list){ push @quoted, untaint_dbstring($_); } return @quoted; } sub get_db_mode { my $sql = shift; if( $sql =~ /select|show/i ){ return 'read'; } else{ return 'write'; } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Extensions.pm000066400000000000000000000024211376436473200256260ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Extensions; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / /; 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/History.pm000066400000000000000000000050121376436473200251270ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::History; use Apache::Ocsinventory::Interface::Database; use XML::Simple; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / get_history_events clear_history_events /; sub get_history_events { my $offset = shift; my @tmp; $offset = $offset * $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; my $sth = get_sth( "SELECT DATE,DELETED,EQUIVALENT FROM deleted_equiv ORDER BY DATE,DELETED LIMIT $offset, $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}" ); while( my $row = $sth->fetchrow_hashref() ){ push @tmp, { 'DELETED' => [ $row->{'DELETED'} ], 'DATE' => [ $row->{'DATE'} ], 'EQUIVALENT' => [ $row->{'EQUIVALENT'} ] } } $sth->finish(); return XML::Simple::XMLout( {'EVENT' => \@tmp} , RootName => 'EVENTS' ); } sub clear_history_events { my $offset = shift; my $ok = 0; my $sth = get_sth( "SELECT * FROM deleted_equiv ORDER BY DATE,DELETED LIMIT 0,$offset" ); while( my $row = $sth->fetchrow_hashref() ) { if( defined $row->{'EQUIVALENT'} ){ do_sql('DELETE FROM deleted_equiv WHERE DELETED=? AND DATE=? AND EQUIVALENT=?', $row->{'DELETED'}, $row->{'DATE'}, $row->{'EQUIVALENT'}) or die; } else{ do_sql('DELETE FROM deleted_equiv WHERE DELETED=? AND DATE=? AND EQUIVALENT IS NULL', $row->{'DELETED'}, $row->{'DATE'}) or die; } $ok++; } return $ok; } OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Internals.pm000066400000000000000000000161171376436473200254350ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Internals; use strict; require Exporter; # If SOAP lite doesn't decode xml entities eval { require XML::Entities; }; if($@){ print STDERR "[".localtime()."] OCSINVENTORY: (SOAP): Cannot find XML::Entities\n"; } use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Interface::Database; use XML::Simple; our @ISA = qw /Exporter/; our @EXPORT = qw / build_xml_standard_section decode_xml encode_xml search_engine send_error get_custom_field_name_map get_custom_fields_values_map /; sub decode_xml{ my $data = shift; unless( $data =~ /^ \&engine_first, ); &{ $search_engines{ (lc $engine) } }( @_ ); } sub engine_first { my ($request, $ids, $begin, $main_table, $accountinfo_table, $deviceid_column, $pk, $sort_by, $sort_dir) = @_; my $parsed_request = XML::Simple::XMLin( $request, ForceArray => ['ID', 'EXCLUDE_ID', 'TAG', 'EXCLUDE_TAG', 'USERID'], SuppressEmpty => 1 ) or die; my ($id, $name, $userid, $checksum, $tag); # Database ids criteria die("BAD_REQUEST") if ( $parsed_request->{ID} and $parsed_request->{EXCLUDE_ID} ); if( $parsed_request->{ID} ){ if( my @ids = untaint_int_lst( @{ $parsed_request->{ID} } )){ $id .= ' AND'; $id .= ' '.$main_table.'.ID IN('.join(',', @ids ).')'; } } if( $parsed_request->{EXCLUDE_ID} ){ if( my @exclude_ids = untaint_int_lst( @{ $parsed_request->{EXCLUDE_ID} } )){ $id .= ' AND'; $id .= ' '.$main_table.'.ID NOT IN('.join(',', @exclude_ids ).')'; } } # Tag criteria die("BAD_REQUEST") if ( $parsed_request->{TAG} and $parsed_request->{EXCLUDE_TAG} ); if( $parsed_request->{TAG} ){ if( my @tags = untaint_dbstring_lst( @{ $parsed_request->{TAG} } )){ $tag .= ' AND'; $tag .= ' '.$accountinfo_table.'.TAG IN("'.join('","', @tags ).'")'; } } if( $parsed_request->{EXCLUDE_TAG} ){ if( my @exclude_tags = untaint_dbstring_lst( @{ $parsed_request->{EXCLUDE_TAG} } )){ $tag .= ' AND'; $tag .= ' '.$accountinfo_table.'.TAG NOT IN("'.join('","', @exclude_tags ).'")'; } } # Checksum criteria (only positive "&" will match if( $parsed_request->{CHECKSUM} ){ die("BAD_CHECKSUM") if !untaint_int( $parsed_request->{CHECKSUM} ); $checksum = ' AND ('.$parsed_request->{CHECKSUM}.' & '.$main_table.'.CHECKSUM)'; } # Associated user criteria if( $parsed_request->{USERID} && $main_table =~ /^hardware$/){ if( my @users_id = untaint_dbstring_lst( @{ $parsed_request->{USERID} } ) ){ $userid .= ' AND'; $userid .= ' '.$main_table.'.USERID IN("'.join('","', @users_id ).'")'; } } # Generate sql string my $search_string = "SELECT DISTINCT $main_table.ID FROM $main_table,$accountinfo_table WHERE $main_table.$deviceid_column NOT LIKE '\\_%' AND $main_table.ID=$accountinfo_table.$pk $id $name $userid $checksum $tag ORDER BY hardware.$sort_by $sort_dir limit $begin,$ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}"; # Play it my $sth = get_sth($search_string); # Get ids while( my $row = $sth->fetchrow_hashref() ){ push @{$ids}, $row->{ID}; } # Destroy request object $sth->finish(); } # Build a database mapped inventory section sub build_xml_standard_section{ my ($id, $main_table, $xml_ref, $section) = @_; my %element; my @tmp; my %get_table_pk_functions = ( 'hardware' => \&get_hardware_table_pk, 'snmp' => \&get_snmp_table_pk ); # Request database my $deviceid = &{ $get_table_pk_functions{ $main_table } }($section); my $sth = get_sth("SELECT * FROM $section WHERE $deviceid=?", $id); # Build data structure... while ( my $row = $sth->fetchrow_hashref() ){ for( keys(%{$DATA_MAP{ $section }->{fields}}) ){ next if $DATA_MAP{ $section }->{fields}->{$_}->{noSql}; # New DB schema support if( $DATA_MAP{ $section }->{fields}->{$_}->{type} ){ my $field = $_; $field =~ s/_ID//g; #We delete the _ID pattern to be in concordance with table name $row->{ $_ } = get_type_name($section, $field, $row->{ $_ }); $element{$field} = [ $row->{ $_ } ]; } else { $element{$_} = [ $row->{ $_ } ]; } } push @tmp, { %element }; %element = (); } $section =~ s/$section/\U$&/g; $xml_ref->{$section}=[ @tmp ]; @tmp = (); $sth->finish; } sub reset_checksum { my( $checksum, $ref ) = @_; my $where = join(',', @$ref); return do_sql("UPDATE hardware SET CHECKSUM=? WHERE ID IN ($where)", $checksum); } sub send_error{ my $error = shift; return XMLout ( { 'ERROR' => [ $error ] }, RootName => 'RESULT' ); } sub untaint_int_lst{ my @list = @_; my @cleared; for (@list){ push @cleared, $_ if untaint_int($_); } return @cleared; } sub untaint_int{ my $int = shift; return $int =~ /^\d+$/; } # Helper for resolving custom field names in ACCOUNTINFO sub get_custom_field_name_map { my $account_type = shift; my $name_map = {}; # Request database my $sth = get_sth('SELECT ID, NAME FROM accountinfo_config WHERE NAME_ACCOUNTINFO IS NULL AND ACCOUNT_TYPE=?', $account_type); # Build data structure... my $rows = $sth->fetchall_arrayref(); foreach my $row ( @$rows ) { $name_map->{ "fields_" . $row->[0] } = $row->[1]; } $sth->finish; return $name_map; } # Helper for resolving textual values of custom fields # of type CHECKBOX, RADIOBUTTON, SELECT sub get_custom_fields_values_map { my $account_value = shift; my $values_map = {}; # Request database my $sth = get_sth('SELECT NAME, IVALUE, TVALUE FROM config WHERE NAME LIKE ?', $account_value."_%_%"); my $rows = $sth->fetchall_arrayref(); my $regexp = $account_value."_(.*)_[0-9]+"; foreach my $row ( @$rows ) { if ($row->[0] =~ /^$regexp$/) { $values_map->{ $1 }->{ $row->[1] } = $row->[2]; } } $sth->finish; return $values_map; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Inventory.pm000066400000000000000000000160511376436473200254700ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Inventory; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / /; sub get_computers { my $request = decode_xml( shift ); my %build_functions = ( 'INVENTORY' => \&build_computers_xml_inventory, 'META' => \&build_computers_xml_meta ); # Specific values for this inventory my $main_table = "hardware"; my $accountinfo_table = "accountinfo"; my $deviceid_column = "DEVICEID"; my $pk = "HARDWARE_ID"; # Returned values my @result; # Remove backslash from xml $request =~ s/\\$// ; # First xml parsing my $parsed_request; eval { $parsed_request = XML::Simple::XMLin( $request ); } or do { return "You've malformed XML please check your SOAP Request"; }; # Max number of responses sent back to client my $max_responses = $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; my @ids; # Generate boundaries my $begin; if( defined $parsed_request->{'OFFSET'} ){ return send_error('BAD_OFFSET') unless $parsed_request->{'OFFSET'} =~ /^\d+$/; $begin = $parsed_request->{'OFFSET'}*$ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; } elsif( defined $parsed_request->{'BEGIN'}){ return send_error('BAD_BEGIN_VALUE') unless $parsed_request->{'BEGIN'} =~ /^\d+$/; $begin = $parsed_request->{'BEGIN'}; } else{ $begin = 0; } my $sort_by = "ID"; if( defined $parsed_request->{'SORT_BY'} and ($parsed_request->{'SORT_BY'} =~ m/(LASTCOME|LASTDATE)/)) { $sort_by = $parsed_request->{'SORT_BY'}; } my $sort_dir = "ASC"; if( defined $parsed_request->{'SORT_DIR'} and ($parsed_request->{'SORT_DIR'} eq "DESC")) { $sort_dir = "DESC"; } # Call search_engine sub search_engine($parsed_request->{ENGINE}, $request, \@ids, $begin, $main_table, $accountinfo_table, $deviceid_column, $pk, $sort_by, $sort_dir); # Type of requested data (meta datas, inventories, special features.. my $type=$parsed_request->{'ASKING_FOR'}||'INVENTORY'; $type =~ s/^(.+)$/\U$1/; # Generate xml responses for(@ids){ push @result, &{ $build_functions{ $type } }($_, $main_table, $parsed_request->{CHECKSUM}, $parsed_request->{WANTED});#Wanted=>special sections bitmap } # Send return "\n", @result, "\n"; } # Build whole inventory (sections specified using checksum) sub build_computers_xml_inventory { my ($computer, $main_table, $checksum, $wanted) = @_; my %xml; my %special_sections = ( accountinfo => 1, dico_soft => 2 ); # Whole inventory by default $checksum = CHECKSUM_MAX_VALUE unless $checksum=~/\d+/; # Build each section using ...standard_section for( keys(%DATA_MAP) ){ #Don't process the sections that are use for capacities special inventory next if $DATA_MAP{$_}->{capacities}; if( ($checksum & $DATA_MAP{$_}->{mask} ) ){ &build_xml_standard_section($computer, $main_table, \%xml, $_) or die; } } # Accountinfos for( keys( %special_sections ) ){ &build_computers_xml_special_section($computer, \%xml, $_) if $special_sections{$_} & $wanted; } # Return the xml response to interface return XML::Simple::XMLout( \%xml, 'RootName' => 'COMPUTER' ) or die; } # Build metadata of a computer sub build_computers_xml_meta { my $id = shift; my %xml; # For mapped fields my @mapped_fields = qw / NAME TAG DEVICEID LASTDATE LASTCOME CHECKSUM DATABASEID/; # For others my @other_fields = qw //; my $sql_str = qq/ SELECT hardware.DEVICEID AS DEVICEID, hardware.LASTDATE AS LASTDATE, hardware.LASTCOME AS LASTCOME, hardware.checksum AS CHECKSUM, hardware.ID AS DATABASEID, hardware.NAME AS NAME, accountinfo.TAG AS TAG FROM hardware,accountinfo WHERE accountinfo.HARDWARE_ID=hardware.ID AND ID=? /; my $sth = get_sth( $sql_str, $id); while( my $row = $sth->fetchrow_hashref ){ for( @mapped_fields ){ $xml{ $_ }=[$row->{ $_ }]; } } $sth->finish; return XML::Simple::XMLout( \%xml, 'RootName' => 'COMPUTER' ) or die; } # For non-standard sections sub build_computers_xml_special_section { my ($id, $xml_ref, $section) = @_; # Accountinfos retrieving if($section eq 'accountinfo'){ my $custom_field_names = get_custom_field_name_map('COMPUTERS'); my $custom_fields_values = get_custom_fields_values_map('ACCOUNT_VALUE'); my %element; my @tmp; # Request database my $sth = get_sth('SELECT * FROM accountinfo WHERE HARDWARE_ID=?', $id); # Build data structure... my $row = $sth->fetchrow_hashref(); foreach my $akey ( keys( %$row ) ) { next if $akey eq get_hardware_table_pk('accountinfo'); my $field_name = (exists $custom_field_names->{ $akey }) ? $custom_field_names->{ $akey } : $akey; if (! exists $custom_fields_values->{ $field_name }) { push @tmp, ( { Name => $field_name, content => $row->{ $akey } } ); } else { foreach my $codepoint ( split( /&&&/, $row->{ $akey } ) ) { push @tmp, ( { Name => $field_name, content => $custom_fields_values->{ $field_name }->{ $codepoint } } ); } } } $xml_ref->{'ACCOUNTINFO'}{'ENTRY'} = [ @tmp ]; $sth->finish; } elsif($section eq 'dico_soft'){ my @tmp; my $sth = get_sth('SELECT DISTINCT dico_soft.FORMATTED AS FORMAT FROM softwares,dico_soft WHERE HARDWARE_ID=? AND EXTRACTED=NAME', $id); while( my $row = $sth->fetchrow_hashref() ){ push @tmp, $row->{FORMAT}; } $xml_ref->{'DICO_SOFT'}{WORD} = [ @tmp ]; $sth->finish; } } # Return software name alias sub get_dico_soft_extracted{ my $extracted = shift; my $sth = get_sth('SELECT DISTINCT FORMATTED FROM dico_soft WHERE EXTRACTED=?', $extracted); unless($sth->rows){ $sth->finish(); return undef; } my ($formatted) = $sth->fetchrow_array; $sth->finish(); return $formatted; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Ipdiscover.pm000066400000000000000000000067721376436473200256130ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Ipdiscover; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use XML::Simple; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / get_ipdiscover_devices ipdiscover_tag ipdiscover_untag ipdiscover_remove ipdiscover_add_type ipdiscover_del_type /; sub get_ipdiscover_devices{ my ($date, $offset, $nInv ) = @_; $offset = $offset*$ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; my $sth; if( !$nInv ){ $sth = get_sth("SELECT * FROM netmap WHERE DATE>? ORDER BY DATE LIMIT $offset, $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}", $date); } else{ $sth = get_sth(" SELECT * FROM netmap nm LEFT JOIN networks nw ON nm.MAC=nw.MACADDR LEFT JOIN network_devices nd ON nd.MACADDR=nm.MAC WHERE nd.MACADDR IS NULL AND nw.MACADDR IS NULL AND DATE>? ORDER BY nm.DATE LIMIT $offset, $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}", $date); } my @result; while( my $row = $sth->fetchrow_hashref() ){ push @result, &build_xml( $row->{MAC}, $row->{IP}, $row->{MASK}, $row->{DATE}, $row->{NAME} ); } return XMLout( { IFACE => \@result }, rootName => 'RESULT' ); } sub ipdiscover_tag { my ( $device, $description, $type, $user ) = @_; return send_error('BAD_TYPE') if do_sql('SELECT * FROM devicetype WHERE NAME=?', $type) == 0E0; return send_error('BAD_USER') if do_sql('SELECT * FROM operators WHERE ID=?', $user) == 0E0; return do_sql('INSERT INTO network_devices(DESCRIPTION,TYPE,MACADDR,USER) VALUES(?,?,?,?)', ($description, $type, $device, $user ) ); } sub ipdiscover_untag{ my $device = shift; return do_sql('DELETE FROM network_devices WHERE MACADDR=?', $device); } sub ipdiscover_remove{ my $device = shift; return do_sql('DELETE FROM network_devices WHERE MACADDR=?', $device); } sub ipdiscover_add_type{ my $type = shift; return 0 if do_sql( 'SELECT * FROM devicetype WHERE NAME=?', $type )!=0E0; return do_sql( 'INSERT INTO devicetype(NAME) VALUES(?)', $type ); } sub ipdiscover_del_type{ my $type = shift; return do_sql( 'DELETE FROM devicetype WHERE NAME=?', $type ); } sub build_xml{ my ( $mac, $ip, $mask, $date, $name ) = @_; return { MAC => [ $mac ], IP => [ $ip ], MASK => [ $mask ], DATE => [ $date ], NAME => [ $name ] }; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Saas.pm000066400000000000000000000056461376436473200243720ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Saas; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use strict; use warnings; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _get_saas set_saas /; sub set_saas{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my @saas_exp = get_saas(); my $saas_en = 0; my $sql; $sql = $dbh->prepare("SELECT ivalue FROM config WHERE config.name='INVENTORY_SAAS_ENABLED'"); $sql->execute; while (my $row = $sql->fetchrow_hashref()){ $saas_en = $row->{ivalue}; } if ($saas_en == 1) { foreach my $saas (@{$Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}->{CONTENT}->{SAAS}}){ my $entry = $saas->{ENTRY}; foreach my $exp (@saas_exp) { my $dnsExp = $exp->{DNS_EXP}; $dnsExp =~ s/\?/\./g; $dnsExp =~ s/\*/\.\*/g; if ($entry =~ /$dnsExp/ || $dnsExp =~ /$entry/ ) { $dbh->do("INSERT INTO saas (SAAS_EXP_ID, HARDWARE_ID, ENTRY, DATA, TTL) VALUES (?,?,?,?,?)", {}, $exp->{ID}, $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}, $entry, $saas->{DATA}, $saas->{TTL}); } } } } return 1; } sub get_saas{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $sql; my @saas_exp; my $result; $sql = "SELECT s.ID, s.NAME, s.DNS_EXP FROM saas_exp s"; $result = $dbh->prepare($sql); $result->execute; while( my $row = $result->fetchrow_hashref() ){ push @saas_exp, { 'ID' => $row->{ID}, 'NAME' => $row->{NAME}, 'DNS_EXP' => $row->{DNS_EXP} } } return @saas_exp; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Snmp.pm000066400000000000000000000143151376436473200244110ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Snmp; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / /; sub get_snmp { my $request = decode_xml( shift ); my %build_functions = ( 'SNMP_INVENTORY' => \&build_snmp_xml_inventory, 'SNMP_META' => \&build_snmp_xml_meta ); # Specific values for this inventory my $main_table = "snmp"; my $accountinfo_table = "snmp_accountinfo"; my $deviceid_column = "SNMPDEVICEID"; my $key_column ="SNMP_ID"; # Returned values my @result; # First xml parsing my $parsed_request = XML::Simple::XMLin( $request ) or die($!); # Max number of responses sent back to client my $max_responses = $ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; my @ids; # Generate boundaries my $begin; if( defined $parsed_request->{'OFFSET'} ){ return send_error('BAD_OFFSET') unless $parsed_request->{'OFFSET'} =~ /^\d+$/; $begin = $parsed_request->{'OFFSET'}*$ENV{OCS_OPT_WEB_SERVICE_RESULTS_LIMIT}; } elsif( defined $parsed_request->{'BEGIN'}){ return send_error('BAD_BEGIN_VALUE') unless $parsed_request->{'BEGIN'} =~ /^\d+$/; $begin = $parsed_request->{'BEGIN'}; } else{ $begin = 0; } my $sort_by = "ID"; if( defined $parsed_request->{'SORT_BY'} and ($parsed_request->{'SORT_BY'} =~ m/(LASTCOME|LASTDATE)/)) { $sort_by = $parsed_request->{'SORT_BY'}; } my $sort_dir = "ASC"; if( defined $parsed_request->{'SORT_DIR'} and ($parsed_request->{'SORT_DIR'} eq "DESC")) { $sort_dir = "DESC"; } # Call search_engine stub search_engine($parsed_request->{ENGINE}, $request, \@ids, $begin, $main_table, $accountinfo_table, $deviceid_column, $key_column, $sort_by, $sort_dir); # Type of requested data (meta datas, inventories, special features.. my $type=$parsed_request->{'ASKING_FOR'}||'SNMP_INVENTORY'; $type =~ s/^(.+)$/\U$1/; # Generate xml responses for(@ids){ push @result, &{ $build_functions{ $type } }($_, $main_table, $parsed_request->{CHECKSUM}, $parsed_request->{WANTED});#Wanted=>special sections bitmap } # Send return "\n", @result, "\n"; } # Build whole inventory (sections specified using checksum) sub build_snmp_xml_inventory { my ($device, $main_table, $checksum, $wanted) = @_; my %xml; my %special_sections = ( snmp_accountinfo => 1, ); # Whole inventory by default $checksum = CHECKSUM_MAX_VALUE unless $checksum=~/\d+/; # Build each section using ...standard_section for( keys(%DATA_MAP) ){ #Process the sections that are use for capacities special inventory if ($DATA_MAP{$_}->{capacities}) { if( ($checksum & $DATA_MAP{$_}->{mask} ) ){ &build_xml_standard_section($device, $main_table, \%xml, $_) or die; } } } # Accountinfos for( keys( %special_sections ) ){ &build_snmp_xml_special_section($device, \%xml, $_) if $special_sections{$_} & $wanted; } # Return the xml response to interface return XML::Simple::XMLout( \%xml, 'RootName' => 'SNMP_DEVICE' ) or die; } # Build metadata of a snmp device sub build_snmp_xml_meta { my $id = shift; my %xml; # For mapped fields my @mapped_fields = qw / NAME TAG SNMPDEVICEID LASTDATE LASTCOME CHECKSUM DATABASEID/; # For others my @other_fields = qw //; my $sql_str = qq/ SELECT snmp.SNMPDEVICEID AS SNMPDEVICEID, snmp.LASTDATE AS LASTDATE, snmp.checksum AS CHECKSUM, snmp.ID AS DATABASEID, snmp.NAME AS NAME, snmp_accountinfo.TAG AS TAG FROM snmp,snmp_accountinfo WHERE snmp_accountinfo.SNMP_ID=snmp.ID AND ID=? /; my $sth = get_sth( $sql_str, $id); while( my $row = $sth->fetchrow_hashref ){ for( @mapped_fields ){ $xml{ $_ }=[$row->{ $_ }]; } } $sth->finish; return XML::Simple::XMLout( \%xml, 'RootName' => 'DEVICE' ) or die; } # For non-standard sections sub build_snmp_xml_special_section { my ($id, $xml_ref, $section) = @_; # Accountinfos retrieving if($section eq 'snmp_accountinfo'){ my $custom_field_names = get_custom_field_name_map('SNMP'); my $custom_fields_values = get_custom_fields_values_map('ACCOUNT_SNMP_VALUE'); my %element; my @tmp; # Request database my $sth = get_sth('SELECT * FROM snmp_accountinfo WHERE SNMP_ID=?', $id); # Build data structure... my $row = $sth->fetchrow_hashref(); foreach my $akey ( keys( %$row ) ) { next if $akey eq get_snmp_table_pk('snmp_accountinfo'); my $field_name = (exists $custom_field_names->{ $akey }) ? $custom_field_names->{ $akey } : $akey; if (! exists $custom_fields_values->{ $field_name }) { push @tmp, ( { Name => $field_name, content => $row->{ $akey } } ); } else { foreach my $codepoint ( split( /&&&/, $row->{ $akey } ) ) { push @tmp, ( { Name => $field_name, content => $custom_fields_values->{ $field_name }->{ $codepoint } } ); } } } $xml_ref->{'ACCOUNTINFO'}{'ENTRY'} = [ @tmp ]; $sth->finish; } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/SoftwareCategory.pm000066400000000000000000000150771376436473200267720ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::SoftwareCategory; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use strict; use warnings; use Switch; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _get_category_software _compare _regex set_category /; { no strict 'refs'; # When called like __PACKAGE__->$op( ... ), __PACKAGE__ is $_[0] *{'bigger'} = sub { return $_[1] >= $_[2]; }; *{'less'} = sub { return $_[1] <= $_[2]; }; *{'equal'} = sub { return $_[1] == $_[2]; }; } sub get_category_software{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $sql; my @cats; my $result; $sql = "SELECT c.ID, c.CATEGORY_NAME, c.OS, s.SOFTWARE_EXP, s.SIGN_VERSION, s.VERSION, s.PUBLISHER FROM software_categories c, software_category_exp s WHERE s.CATEGORY_ID = c.ID"; $result = $dbh->prepare($sql); $result->execute; while( my $row = $result->fetchrow_hashref() ){ push @cats, { 'ID' => $row->{ID}, 'CATEGORY_NAME' => $row->{CATEGORY_NAME}, 'OS' => $row->{OS}, 'SOFTWARE_EXP' => $row->{SOFTWARE_EXP}, 'SIGN_VERSION' => $row->{SIGN_VERSION}, 'VERSION' => $row->{VERSION}, 'PUBLISHER' => $row->{PUBLISHER} } } return @cats; } sub compare{ my ($sign,$version,$publisher,$v,$p) = @_; if ( (defined $publisher) && ($publisher ne '')) { if ( (__PACKAGE__->$sign($v, $version)) && ($publisher eq $p) ) { return 2; } else { return undef; } } else { if ( __PACKAGE__->$sign($v, $version) ) { return 2; } else { return undef; } } } sub regex{ my ($regex) = @_; if(($regex !~ m/\?/) && ($regex !~ m/\*/)){ $regex = "\^".$regex."\$"; } if((substr( $regex, -1) eq '*') && (substr( $regex, 0, 1) eq '*')){ $regex = $regex =~ s/\*//gr; } if((substr( $regex, 0, 1 ) eq '*') && (substr( $regex, -1) ne '*')){ $regex = $regex =~ s/\*//gr; $regex = $regex."\$"; } if((substr( $regex, -1) eq '*') && (substr( $regex, 0, 1) ne '*')){ $regex = $regex =~ s/\*//gr; $regex = "\^".$regex; } if(($regex =~ m/\?/)){ $regex = $regex =~ s/\?/./gr; } return $regex; } sub set_category{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my @cats = get_category_software(); my $soft_cat; my $default_cat; my $sql = $dbh->prepare("SELECT ivalue FROM config WHERE config.name='DEFAULT_CATEGORY'"); $sql->execute; while (my $row = $sql->fetchrow_hashref()){ $default_cat = $row->{ivalue}; } foreach my $soft (@{$Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}->{CONTENT}->{SOFTWARES}}){ foreach my $cat (@cats){ my $regex = $cat->{SOFTWARE_EXP}; my $sign = $cat->{SIGN_VERSION}; my $version = $cat->{VERSION}; my $publisher = $cat->{PUBLISHER}; my $os = $cat->{OS}; my $softName = $soft->{NAME}; my $response; my $minV; my $majV; $regex = regex($regex); if(( $os eq 'ALL' ) || ( $Apache::Ocsinventory::CURRENT_CONTEXT{'USER_AGENT'} =~ m/$os/ )){ if (defined $softName) { if ($softName =~ $regex) { if( ( defined $sign ) && ( $sign ne '' )){ switch ($sign) { case "EQUAL" { $minV = $version =~ s/\.//gr; $majV = $soft->{VERSION} =~ s/\.//gr; $response = compare('equal',$minV,$publisher,$majV,$soft->{PUBLISHER}); if( defined $response) { $soft_cat = $cat->{ID}; } } case "LESS" { $minV = $version =~ s/\.//gr; $majV = $soft->{VERSION} =~ s/\.//gr; $response = compare('less',$minV,$publisher,$majV,$soft->{PUBLISHER}); if( defined $response) { $soft_cat = $cat->{ID}; } } case "MORE" { $minV = $version =~ s/\.//gr; $majV = $soft->{VERSION} =~ s/\.//gr; $response = compare('bigger',$minV,$publisher,$majV,$soft->{PUBLISHER}); if( defined $response) { $soft_cat = $cat->{ID}; } } } } if ( (defined $publisher) && ( $publisher ne '' ) && ( $sign eq '' ) ) { my $softPublisher = $soft->{PUBLISHER}; if ( (defined $softPublisher) && ($publisher eq $softPublisher) ) { $soft_cat = $cat->{ID}; } } if( ($publisher eq '') && ($sign eq '')) { $soft_cat = $cat->{ID}; } } } } } if (!defined $soft_cat) { $soft_cat = $default_cat; } $soft->{CATEGORY} = $soft_cat; $soft_cat = undef; } return 1; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Interface/Updates.pm000066400000000000000000000037771376436473200251130ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Interface::Updates; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Interface::Database; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw //; sub delete_computers_by_id { my $computerIds = shift ; my $dbh = &get_dbh_write ; for my $hardwareId (@{$computerIds}){ # We lock the computer to avoid race condition next if &_lock($hardwareId, $dbh) ; for my $section ( keys %DATA_MAP ){ my $hardwareIdField = get_hardware_table_pk($section) ; # delOnReplace is used here even if the section is not "auto" # "auto" is only useful for the import phases next if !$DATA_MAP{ $section }->{delOnReplace} ; do_sql("DELETE FROM $section WHERE $hardwareIdField=$hardwareId") ; } &_unlock($hardwareId, $dbh) ; } return 'OK' ; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Map.pm000066400000000000000000000500741376436473200223130ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Map; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / %DATA_MAP /; # Field's attributes : cache, filter, noXml, noSql, fallback, type our %DATA_MAP= ( hardware => { mask => 1, multi => 0, auto => 0, delOnReplace => 1, sortBy => 'NAME', writeDiff => 0, cache => 1, fields => { ID => { noXml => 1 }, NAME => {}, WORKGROUP => {}, USERDOMAIN => {}, OSNAME => { cache=>1 }, OSVERSION => {}, OSCOMMENTS => {}, PROCESSORT => {}, PROCESSORS => {}, PROCESSORN => {}, MEMORY => {}, SWAP => {}, DEFAULTGATEWAY => {}, IPADDR => {}, DNS => {}, USERID => { filter => 1 }, TYPE => {}, DESCRIPTION => {}, WINCOMPANY => {}, WINOWNER => {}, WINPRODID => {}, WINPRODKEY => {}, LASTDATE => {}, LASTCOME => {}, CHECKSUM => {}, QUALITY => {}, FIDELITY => {}, SSTATE => { noXml => 1 }, USERAGENT => { noXml => 1 }, IPSRC => {}, ARCH => {}, CATEGORY_ID => {} }, }, accountinfo => { mask => 0, multi => 1, auto => 0, delOnReplace => 1, sortBy => 'TAG', writeDiff => 0, cache => 0, fields => { TAG => {} } }, bios => { mask => 2, multi => 0, auto => 1, delOnReplace => 1, sortBy => 'SSN', writeDiff => 0, cache => 0, fields => { MMANUFACTURER => {}, MMODEL => {}, MSN => {}, SMANUFACTURER => {}, SMODEL => {}, SSN => {}, BMANUFACTURER => {}, BVERSION => {}, BDATE => {}, TYPE => {}, ASSETTAG => {}, } }, memories => { mask => 4, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'CAPTION', writeDiff => 1, cache => 0, fields => { CAPACITY => {}, SPEED => {}, CAPTION => {}, DESCRIPTION => {}, NUMSLOTS => { fallback=>0 }, TYPE => {}, PURPOSE => {}, SERIALNUMBER => {} } }, slots => { mask => 8, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, DESCRIPTION => {}, DESIGNATION => {}, PURPOSE => {}, STATUS => {}, PSHARE => { fallback=>0 } } }, registry => { mask => 16, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 1, fields => { NAME => { cache => 1 }, REGVALUE => { cache => 1 } } }, controllers => { mask => 32, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { MANUFACTURER => {}, NAME => {}, CAPTION => {}, DESCRIPTION => {}, VERSION => {}, TYPE => {} } }, monitors => { mask => 64, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'CAPTION', writeDiff => 1, cache => 0, fields => { MANUFACTURER => {}, CAPTION => {}, DESCRIPTION => {}, TYPE => {}, SERIAL => {} } }, ports => { mask => 128, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, CAPTION => {}, DESCRIPTION => {}, TYPE => {} } }, storages => { mask => 256, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { MANUFACTURER => {}, NAME => {}, MODEL => {}, DESCRIPTION => {}, TYPE => {}, DISKSIZE => { fallback=>0 }, SERIALNUMBER => {}, FIRMWARE => {} } }, drives => { mask => 512, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'VOLUMN', writeDiff => 1, cache => 0, fields => { LETTER => {}, TYPE => {}, FILESYSTEM => {}, TOTAL => { fallback=>0 }, FREE => { fallback=>0 }, VOLUMN => {}, NUMFILES => { fallback=>0}, CREATEDATE => {} } }, inputs => { mask => 1024, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'CAPTION', writeDiff => 1, cache => 0, fields => { TYPE => {}, MANUFACTURER => {}, CAPTION => {}, DESCRIPTION => {}, INTERFACE => {}, POINTTYPE => {} } }, modems => { mask => 2048, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, MODEL => {}, DESCRIPTION => {}, TYPE => {} } }, networks => { mask => 4096, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'IPADDRESS', writeDiff => 1, cache => 0, fields => { IPADDRESS => {}, IPMASK => {}, IPSUBNET => {}, DESCRIPTION => {}, TYPE => {}, TYPEMIB => {}, SPEED => {}, MTU => {}, MACADDR => { fallback => '00:00:00:00:00:00' }, STATUS => {}, IPGATEWAY => {}, IPDHCP => {}, VIRTUALDEV => {} } }, printers => { mask => 8192, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, DRIVER => {}, PORT => {}, DESCRIPTION => {}, SERVERNAME => {}, SHARENAME => {}, RESOLUTION => {}, COMMENT => {}, SHARED => {}, NETWORK => {} } }, sounds => { mask => 16384, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, MANUFACTURER => {}, DESCRIPTION => {} } }, videos => { mask => 32768, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, CHIPSET => {}, MEMORY => {}, RESOLUTION => {} } }, virtualmachines => { mask => 131072, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { NAME => {}, MEMORY => {}, UUID => {}, STATUS => {}, SUBSYSTEM => {}, VMTYPE => {}, VCPU => {} } }, cpus => { mask => 262144, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'SERIALNUMBER', writeDiff => 1, cache => 0, fields => { MANUFACTURER => {}, TYPE => {}, SERIALNUMBER => {}, SPEED => {}, CORES => {}, L2CACHESIZE => {}, CPUARCH => {}, DATA_WIDTH => {}, CURRENT_ADDRESS_WIDTH => {}, LOGICAL_CPUS => {}, VOLTAGE => {}, CURRENT_SPEED => {}, SOCKET => {} } }, sim => { mask => 524288, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'SERIALNUMBER', writeDiff => 1, cache => 0, fields => { OPERATOR => {}, OPNAME => {}, COUNTRY => {}, SERIALNUMBER => {}, DEVICEID => {}, PHONENUMBER => {} } }, batteries => { mask => 1048576, multi => 0, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, fields => { LOCATION => {}, MANUFACTURER => {}, MANUFACTUREDATE => {}, SERIALNUMBER => {}, NAME => {}, CHEMISTRY => {}, DESIGNCAPACITY => {}, DESIGNVOLTAGE => {}, SBDSVERSION => {}, MAXERROR => {}, OEMSPECIFIC => {} } }, usbdevices => { mask => 2097152, multi => 0, auto => 1, delOnReplace => 1, sortBy => 'DESCRIPTION', writeDiff => 1, cache => 0, fields => { DESCRIPTION => {}, INTERFACE => {}, MANUFACTURER => {}, SERIAL => {}, TYPE => {} } }, repository => { mask => 0, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 0, cache => 0, fields => { BASEURL => {}, EXCLUDE => {}, EXCLUDED => {}, EXPIRE => {}, FILENAME => {}, MIRRORS => {}, NAME => {}, PKGS => {}, REVISION => {}, SIZE => {}, TAG => {}, UPDATED => {} } }, javainfo => { mask => 0, multi => 0, auto => 1, delOnReplace => 1, sortBy => 'JAVANAME', writeDiff => 0, cache => 0, fields => { JAVANAME => { fallback=>'noname' }, JAVAPATHLEVEL => { fallback=>0 }, JAVACOUNTRY => {}, JAVACLASSPATH => {}, JAVAHOME => {} } }, journallog => { mask => 0, multi => 1, auto => 1, delOnReplace => 0, sortBy => '', writeDiff => 0, cache => 0, fields => { JOURNALLOG => {}, LISTENERNAME => { fallback=>'noname' }, DATE => {}, STATUS => { fallback=>0 }, ERRORCODE => {} } }, itmgmt_comments => { mask => 0, multi => 1, auto => 0, delOnReplace => 0, sortBy => 'DATE_INSERT', writeDiff => 0, cache => 0, fields => { COMMENTS => {}, USER_INSERT => {}, DATE_INSERT => {}, ACTION => {}, VISIBLE => {} } }, devices => { mask => 0, multi => 1, auto => 0, delOnReplace => 1, sortBy => 'NAME', writeDiff => 0, cache => 0, fields => { NAME => {}, IVALUE => {}, TVALUE => {}, COMMENTS => {} } }, download_history => { mask => 0, multi => 1, auto => 0, delOnReplace => 1, sortBy => 'PKD_ID', writeDiff => 0, cache => 0, fields => { PKG_ID => {}, PKG_NAME => {} } }, groups_cache => { mask => 0, multi => 1, auto => 0, delOnReplace => 1, sortBy => 'GROUP_ID', writeDiff => 0, cache => 0, fields => { GROUP_ID => {}, STATIC => {} } }, snmp => { mask => 1, multi => 0, auto => 0, delOnReplace => 1, sortBy => 'IPADDRESS', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { ID => { noXml => 1 }, IPADDR => {}, MACADDR => {}, SNMPDEVICEID => {}, NAME => {}, DESCRIPTION => {}, CONTACT => {}, LOCATION => {}, UPTIME => {}, DOMAIN => {}, TYPE => {}, LASTDATE => {}, CHECKSUM => {} } }, snmp_printers => { mask => 2, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {}, SERIALNUMBER => {}, COUNTER => {}, STATUS => {}, ERRORSTATE => {} } }, snmp_switchs => { mask => 4, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { MANUFACTURER => {}, REFERENCE => {}, TYPE => {}, SOFTVERSION => {}, FIRMVERSION => {}, SERIALNUMBER => {}, REVISION => {}, DESCRIPTION => {} } }, snmp_firewalls => { mask => 8, multi => 0, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { SERIALNUMBER => {}, SYSTEM => {} } }, snmp_blades => { mask => 16, multi => 0, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { SERIALNUMBER => {}, SYSTEM => {} } }, snmp_loadbalancers => { mask => 32, multi => 0, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { SERIALNUMBER => {}, SYSTEM => {}, TYPE => {}, MANUFACTURER => {} } }, snmp_trays => { mask => 64, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {}, DESCRIPTION => {}, LEVEL => {}, MAXCAPACITY => {} } }, snmp_cartridges => { mask => 128, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'DESCRIPTION', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { DESCRIPTION => {}, TYPE => {}, LEVEL => {}, MAXCAPACITY => {}, COLOR => {} } }, snmp_networks => { mask => 256, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { DESCRIPTION => {}, MACADDR => {}, DEVICEMACADDR => {}, SLOT => {}, STATUS => {}, SPEED => {}, TYPE => {}, DEVICEADDRESS => {}, DEVICENAME => {}, DEVICEPORT => {}, DEVICETYPE => {}, TYPEMIB => {}, IPADDR => {}, IPMASK => {}, IPGATEWAY => {}, IPSUBNET => {}, IPDHCP => {}, DRIVER => {}, VIRTUALDEV => {} } }, snmp_storages => { mask => 512, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { DESCRIPTION => {}, MANUFACTURER => {}, NAME => {}, MODEL => {}, DISKSIZE => {}, TYPE => {}, SERIALNUMBER => {}, FIRMWARE => {} } }, snmp_drives => { mask => 1024, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { LETTER => {}, TYPE => {}, FILESYSTEM => {}, TOTAL => {}, FREE => {}, NUMFILES => {}, VOLUMN => {}, LABEL => {}, SERIAL => {} } }, snmp_powersupplies => { mask => 2048, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { MANUFACTURER => {}, REFERENCE => {}, TYPE => {}, SERIALNUMBER => {}, DESCRIPTION => {}, REVISION => {} } }, snmp_fans => { mask => 4096, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { DESCRIPTION => {}, REFERENCE => {}, REVISION => {}, SERIALNUMBER => {}, MANUFACTURER => {}, TYPE => {} } }, snmp_cards => { mask => 8192, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { DESCRIPTION => {}, REFERENCE => {}, FIRMWARE => {}, SOFTWARE => {}, REVISION => {}, SERIALNUMBER => {}, MANUFACTURER => {}, TYPE => {} } }, snmp_switchinfos => { mask => 16384, multi => 0, auto => 1, delOnReplace => 1, sortBy => 'TYPE', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { TYPE => {} } }, snmp_computers => { mask => 32768, multi => 0, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { SYSTEM => {} } }, snmp_softwares => { mask => 65536, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {}, INSTALLDATE => {}, COMMENTS => {}, VERSION => {} } }, snmp_memories => { mask => 131072, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { CAPACITY => {} } }, snmp_cpus => { mask => 262144, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { SPEED => {}, TYPE => {}, MANUFACTURER => {} } }, snmp_inputs => { mask => 524288, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { DESCRIPTION => {}, TYPE => {} } }, snmp_ports => { mask => 1048576, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {}, TYPE => {} } }, snmp_sounds => { mask => 2097152, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {} } }, snmp_videos => { mask => 4194304, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {} } }, snmp_modems => { mask => 8388608, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {} } }, snmp_localprinters => { mask => 16777216, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { NAME => {} } }, snmp_virtualmachines => { mask => 33554432, multi => 1, auto => 1, delOnReplace => 1, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { CONFIG_FILE => {}, CPU => {}, MEMORY => {}, NAME => {}, OS => {}, POWER => {}, UUID => {} } }, snmp_accountinfo => { mask => 0, multi => 1, auto => 0, delOnReplace => 1, sortBy => 'TAG', writeDiff => 0, cache => 0, fields => { TAG => {} } }, snmp_laststate => { mask => 0, multi => 0, auto => 0, delOnReplace => 0, sortBy => '', writeDiff => 1, cache => 0, capacities => 'snmp', fields => { COMMON => {}, PRINTERS => {}, TRAYS => {}, CARTRIDGES => {}, NETWORKS => {}, SWITCHS => {}, BLADES => {}, STORAGES => {}, DRIVES => {}, POWERSUPPLIES => {}, FANS => {}, LOADBALANCERS => {}, CARDS => {}, FIREWALLS => {}, SWITCHINFOS => {}, COMPUTERS => {}, SOFTWARES => {}, MEMORIES => {}, CPUS => {}, INPUTS => {}, PORTS => {}, SOUNDS => {}, VIDEOS => {}, MODEMS => {}, LOCALPRINTERS => {}, VIRTUALMACHINES => {} } }, unixusers => { mask => 0, multi => 1, auto => 1, delOnReplace => 1, sortBy => 'NAME_USERS', writeDiff => 0, cache => 0, fields => { ID_USERS => {}, GID_USERS => {}, HOME_USERS => {}, LOGIN_USERS => {}, NAME_USERS => {}, GROUP_USERS => {}, SHELL_USERS => {}, ID_GROUP => {}, MEMBER_GROUP => {}, NAME_GROUP => {} } }, ); 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Plugins.pm000066400000000000000000000033431376436473200232140ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Plugins; use strict; BEGIN { push @INC, $ENV{OCS_PLUGINS_PERL_DIR}; } #Loading plugins modules if($ENV{'OCS_MODPERL_VERSION'} == 1){ Apache->httpd_conf("Include $ENV{OCS_PLUGINS_CONF_DIR}"); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ use Apache2::ServerUtil(); Apache2::ServerUtil->server->add_config(["Include $ENV{OCS_PLUGINS_CONF_DIR}"]); }else{ if(!defined($ENV{'OCS_MODPERL_VERSION'})){ die("OCS_MODPERL_VERSION not defined. Abort\n"); }else{ die("OCS_MODPERL_VERSION set to, a bad parameter. Must be '1' or '2'. Abort\n"); } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Plugins/000077500000000000000000000000001376436473200226535ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Plugins/Modules.pm000066400000000000000000000103411376436473200246200ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Plugins::Modules; use SOAP::Lite; use strict; use LWP::Simple; use Archive::Zip; use File::Copy; use File::Path; use DBI; sub InstallPlugins { my $pluginName = $_[1]; # Download the created archive from the ocsreports which contain the communication server code (.conf and map.pm) my $url = "http://$ENV{OCS_DB_HOST}/ocsreports/upload/$pluginName.zip"; my $file = "$ENV{OCS_PLUGINS_CONF_DIR}/$pluginName.zip"; our $result; our $perm = 1; #Up case plugin directory in OCS server for match with actual template our $pluginNameUc = ucfirst($pluginName); if (-e "$ENV{OCS_PLUGINS_CONF_DIR}/$pluginName.conf") { $result = "Err_01"; } elsif(-e "$ENV{OCS_PLUGINS_PERL_DIR}/Apache/Ocsinventory/Plugins/$pluginNameUc"){ $result = "Err_05"; } else { my $status = getstore($url, $file); # If download succes, unzip, create dir, move files. if (is_success($status)) { # Check for write perm in plugins dir if(!(-w "$ENV{OCS_PLUGINS_CONF_DIR}")) { $result = "Err_03"; $perm = 0; } # Check for write perm in perl dir if(!(-w "$ENV{OCS_PLUGINS_PERL_DIR}/Apache/Ocsinventory/Plugins")) { $result = "Err_04"; $perm = 0; } if($perm){ my $pluginsdir = "$ENV{OCS_PLUGINS_CONF_DIR}"; my $zipname = $file; my $destinationDirectory = $pluginsdir; my $zip = Archive::Zip->new($zipname); my $member; foreach my $member ($zip->members) { next if $member->isDirectory; (my $extractName = $member->fileName) =~ s{.*/}{}; $member->extractToFileNamed("$destinationDirectory/$extractName"); } my $dirtocreate = "$ENV{OCS_PLUGINS_PERL_DIR}/Apache/Ocsinventory/Plugins/$pluginNameUc"; mkdir $dirtocreate; unlink $file; move("$pluginsdir/Map.pm","$ENV{OCS_PLUGINS_PERL_DIR}/Apache/Ocsinventory/Plugins/$pluginNameUc/Map.pm"); $result = "Install_OK"; } }else{ $result = "Err_02"; } } return( SOAP::Data->name( 'Result' => $result )->type( 'string' ) ); } # Seek for deleted plugins // Delete map.pm and conf entry. sub DeletePlugins { my $pluginName = $_[1]; #Up case plugin directory in OCS server for match with actual template for deletion my $pluginNameUc = ucfirst($pluginName); my $pluginsdir = "$ENV{OCS_PLUGINS_CONF_DIR}"; if (-e "$ENV{OCS_PLUGINS_CONF_DIR}/$pluginName.conf"){ unlink "$ENV{OCS_PLUGINS_CONF_DIR}/$pluginName.conf"; } if($pluginNameUc != ""){ my $dirToDel = "$ENV{OCS_PLUGINS_PERL_DIR}/Apache/Ocsinventory/Plugins/$pluginNameUc"; rmtree($dirToDel); } my $result = "Delete_OK"; return( SOAP::Data->name( 'Result' => $result )->type( 'string' ) ); } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/SOAP.pm000066400000000000000000000041121376436473200223300ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::SOAP; BEGIN{ eval{ if($ENV{OCS_MODPERL_VERSION}==1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); require SOAP::Transport::HTTP; our $server = SOAP::Transport::HTTP::Apache->dispatch_to('Apache::Ocsinventory::Interface'); } elsif( $ENV{OCS_MODPERL_VERSION}==2 ){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); require SOAP::Transport::HTTP2; our $server = SOAP::Transport::HTTP2::Apache->dispatch_to('Apache::Ocsinventory::Interface'); } $XML::Simple::PREFERRED_PARSER = 'XML::Parser'; require Apache::Ocsinventory::Interface; }; if($@){ print STDERR "ocsinventory-server: Can't load SOAP::Transport::HTTP* - Web service will be unavailable\n"; } } sub handler { our $apache_req = $_[0]; return APACHE_FORBIDDEN unless $ENV{OCS_OPT_WEB_SERVICE_ENABLED}; $server->handler(@_); } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/000077500000000000000000000000001376436473200225005ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/000077500000000000000000000000001376436473200245455ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Datafilter.pm000066400000000000000000000070541376436473200271700ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Datafilter; use strict; # This block specify which wrapper will be used ( your module will be compliant with all mod_perl versions ) BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } # These are the core modules you must include in addition use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Map; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'DATAFILTER', 'HANDLER_PROLOG_READ' => undef, #or undef # Called before reading the prolog 'HANDLER_PROLOG_RESP' => undef, #or undef # Called after the prolog response building 'HANDLER_PRE_INVENTORY' => \&datafilter_pre_inventory, #or undef # Called before reading inventory 'HANDLER_POST_INVENTORY' => undef, #or undef # Called when inventory is stored without error 'REQUEST_NAME' => undef, #or undef # Value of xml tag 'HANDLER_REQUEST' => undef, #or undef # function that handle the request with the 'REQUEST NAME' 'HANDLER_DUPLICATE' => undef,#or undef # Called when a computer is handle as a duplicate 'TYPE' => OPTION_TYPE_SYNC, # or OPTION_TYPE_ASYNC ASYNC=>with pr without inventory, SYNC=>only when inventory is required 'XML_PARSER_OPT' => { 'ForceArray' => [''] } }; sub datafilter_pre_inventory{ my $current_context = shift; my $xml = $current_context->{'XML_ENTRY'}; my $apache = $current_context->{'APACHE_OBJECT'}; if ($ENV{'OCS_OPT_DATA_FILTER'}) { my ($map_section, $multi_sections, $field, $mask); #Geting table and field from configuration file my %DATA_TO_FILTER = $apache->dir_config->get('OCS_OPT_DATA_TO_FILTER'); for my $section ( keys %DATA_TO_FILTER) { $map_section = lc $section; $field = $DATA_TO_FILTER{$section}; #Deleting data from XML unless ($DATA_MAP{$map_section}{multi}) { delete $xml->{'CONTENT'}->{$section}->{$field} if $xml->{'CONTENT'}->{$section}->{$field}; &_log(1,'datafilter',"$section $field field deleted") if $ENV{'OCS_OPT_LOGLEVEL'};; } } } return INVENTORY_CONTINUE; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Download.pm000066400000000000000000000456511376436473200266650ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Download; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::Capacities::Download::Inventory; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'DOWNLOAD', 'HANDLER_PROLOG_READ' => undef, 'HANDLER_PROLOG_RESP' => \&download_prolog_resp, 'HANDLER_PRE_INVENTORY' => undef, 'HANDLER_POST_INVENTORY' => \&download_post_inventory, 'REQUEST_NAME' => 'DOWNLOAD', 'HANDLER_REQUEST' => \&download_handler, 'HANDLER_DUPLICATE' => \&download_duplicate, 'TYPE' => OPTION_TYPE_ASYNC, 'XML_PARSER_OPT' => { 'ForceArray' => ['PACKAGE'] } }; sub download_prolog_resp{ my $current_context = shift; my $resp = shift; my $dbh = $current_context->{'DBI_HANDLE'}; my $groups = $current_context->{'MEMBER_OF'}; my $hardware_id = $current_context->{'DATABASE_ID'}; my $groupsParams = $current_context->{'PARAMS_G'}; my ( $downloadSwitch, $cycleLatency, $fragLatency, $periodLatency, $periodLength, $timeout,$execTimeout); my($pack_sql, $hist_sql); my($pack_req, $hist_req); my($hist_row, $pack_row); my(@packages, @history, @forced_packages, @scheduled_packages, @postcmd_packages, @dont_repeat); my $blacklist; if($ENV{'OCS_OPT_DOWNLOAD'}){ $downloadSwitch = 1; # Group's parameters for(keys(%$groupsParams)){ $downloadSwitch = $$groupsParams{$_}->{'DOWNLOAD_SWITCH'}->{'IVALUE'} if exists( $$groupsParams{$_}->{'DOWNLOAD_SWITCH'}->{'IVALUE'} ) and $$groupsParams{$_}->{'DOWNLOAD_SWITCH'}->{'IVALUE'} < $downloadSwitch; $cycleLatency = $$groupsParams{$_}->{'DOWNLOAD_CYCLE_LATENCY'}->{'IVALUE'} if ( (exists($$groupsParams{$_}->{'DOWNLOAD_CYCLE_LATENCY'}->{'IVALUE'}) and $$groupsParams{$_}->{'DOWNLOAD_CYCLE_LATENCY'}->{'IVALUE'} > $cycleLatency) or !$cycleLatency); $fragLatency = $$groupsParams{$_}->{'DOWNLOAD_FRAG_LATENCY'}->{'IVALUE'} if ( (exists($$groupsParams{$_}->{'DOWNLOAD_FRAG_LATENCY'}->{'IVALUE'}) and $$groupsParams{$_}->{'DOWNLOAD_FRAG_LATENCY'}->{'IVALUE'} > $fragLatency) or !$fragLatency); $periodLatency = $$groupsParams{$_}->{'DOWNLOAD_PERIOD_LATENCY'}->{'IVALUE'} if ( (exists($$groupsParams{$_}->{'DOWNLOAD_PERIOD_LATENCY'}->{'IVALUE'}) and $$groupsParams{$_}->{'DOWNLOAD_PERIOD_LATENCY'}->{'IVALUE'} > $periodLatency) or !$periodLatency); $periodLength = $$groupsParams{$_}->{'DOWNLOAD_PERIOD_LENGTH'}->{'IVALUE'} if ( (exists($$groupsParams{$_}->{'DOWNLOAD_PERIOD_LENGTH'}->{'IVALUE'}) and $$groupsParams{$_}->{'DOWNLOAD_PERIOD_LENGTH'}->{'IVALUE'} < $periodLength) or !$periodLength); $timeout = $$groupsParams{$_}->{'DOWNLOAD_TIMEOUT'}->{'IVALUE'} if ( (exists($$groupsParams{$_}->{'DOWNLOAD_TIMEOUT'}->{'IVALUE'}) and $$groupsParams{$_}->{'DOWNLOAD_TIMEOUT'}->{'IVALUE'} < $timeout) or !$timeout); $execTimeout = $$groupsParams{$_}->{'DOWNLOAD_EXECUTION_TIMEOUT'}->{'IVALUE'} if ( (exists($$groupsParams{$_}->{'DOWNLOAD_EXECUTION_TIMEOUT'}->{'IVALUE'}) and $$groupsParams{$_}->{'DOWNLOAD_EXECUTION_TIMEOUT'}->{'IVALUE'} < $execTimeout) or !$execTimeout); } } else{ $downloadSwitch = 0; } $downloadSwitch = $current_context->{'PARAMS'}{'DOWNLOAD_SWITCH'}->{'IVALUE'} if defined($current_context->{'PARAMS'}{'DOWNLOAD_SWITCH'}->{'IVALUE'}) and $downloadSwitch; $cycleLatency = $ENV{'OCS_OPT_DOWNLOAD_CYCLE_LATENCY'} unless $cycleLatency; $fragLatency = $ENV{'OCS_OPT_DOWNLOAD_FRAG_LATENCY'} unless $fragLatency; $periodLatency = $ENV{'OCS_OPT_DOWNLOAD_PERIOD_LATENCY'} unless $periodLatency; $periodLength = $ENV{'OCS_OPT_DOWNLOAD_PERIOD_LENGTH'} unless $periodLength; $timeout = $ENV{'OCS_OPT_DOWNLOAD_TIMEOUT'} unless $timeout; $execTimeout = $ENV{'OCS_OPT_DOWNLOAD_EXECUTION_TIMEOUT'} unless $execTimeout; push @packages,{ 'TYPE' => 'CONF', 'ON' => $downloadSwitch, 'CYCLE_LATENCY' => $current_context->{'PARAMS'}{'DOWNLOAD_CYCLE_LATENCY'}->{'IVALUE'} || $cycleLatency, 'FRAG_LATENCY' => $current_context->{'PARAMS'}{'DOWNLOAD_FRAG_LATENCY'}->{'IVALUE'} || $fragLatency, 'PERIOD_LATENCY' => $current_context->{'PARAMS'}{'DOWNLOAD_PERIOD_LATENCY'}->{'IVALUE'} || $periodLatency, 'PERIOD_LENGTH' => $current_context->{'PARAMS'}{'DOWNLOAD_PERIOD_LENGTH'}->{'IVALUE'} || $periodLength, 'TIMEOUT' => $current_context->{'PARAMS'}{'DOWNLOAD_TIMEOUT'}->{'IVALUE'} || $timeout, 'EXECUTION_TIMEOUT' => $current_context->{'PARAMS'}{'DOWNLOAD_EXECUTION_TIMEOUT'}->{'IVALUE'} || $execTimeout }; if($downloadSwitch){ # If this option is set, we send only the needed package to the agent # Can be a performance issue # Agents prior to 4.0.3.0 do not send history data $hist_sql = q { SELECT PKG_ID FROM download_history WHERE HARDWARE_ID=? }; $hist_req = $dbh->prepare( $hist_sql ); $hist_req->execute( $hardware_id ); while( $hist_row = $hist_req->fetchrow_hashref ){ push @history, $hist_row->{'PKG_ID'}; } #We get scheduled packages affected to the computer &get_scheduled_packages($dbh, $hardware_id, \@scheduled_packages); #We get scheduled packages affected with a postcmd command &get_postcmd_packages($dbh, $hardware_id, \@postcmd_packages); #We get packages marked as forced affeted to the computer &get_forced_packages($dbh, $hardware_id, \@forced_packages); #We get packages for groups that computer is member of if( $current_context->{'EXIST_FL'} && $ENV{'OCS_OPT_ENABLE_GROUPS'} && @$groups ){ $pack_sql = q { SELECT IVALUE,FILEID,INFO_LOC,PACK_LOC,CERT_PATH,CERT_FILE FROM devices,download_enable WHERE HARDWARE_ID=? AND devices.NAME='DOWNLOAD' AND download_enable.ID=devices.IVALUE }; my $verif_affected = 'SELECT TVALUE FROM devices WHERE HARDWARE_ID=? AND IVALUE=? AND NAME="DOWNLOAD"'; my $trace_event = 'INSERT INTO devices(HARDWARE_ID,NAME,IVALUE,TVALUE) VALUES(?,"DOWNLOAD",?,NULL)'; $pack_req = $dbh->prepare( $pack_sql ); for( @$groups ){ $pack_req->execute( $_ ); #We get scheduled packages affected to the group &get_scheduled_packages($dbh, $_, \@scheduled_packages); #We get packages affected to the group which contain postcmd command &get_postcmd_packages($dbh, $_, \@postcmd_packages); while( $pack_row = $pack_req->fetchrow_hashref ){ my $fileid = $pack_row->{'FILEID'}; my ($schedule, $scheduled_package, $postcmd, $postcmd_package); if( (grep /^$fileid$/, @history) or (grep /^$fileid$/, @dont_repeat)){ next; } if( $ENV{'OCS_OPT_DOWNLOAD_GROUPS_TRACE_EVENTS'} ){ # We verify if the package is already traced and not already in history my $verif_affected_sth = $dbh->prepare($verif_affected); $verif_affected_sth->execute($hardware_id, $pack_row->{'IVALUE'}); if($verif_affected_sth->rows){ my $verif_affected_row = $verif_affected_sth->fetchrow_hashref(); if($verif_affected_row!~/NULL/ && $verif_affected_row!~/NOTIFIED/){ $verif_affected_sth->finish(); # We do not send package if the current state is fed next; } } else{ $dbh->do($trace_event, {}, $hardware_id, $pack_row->{'IVALUE'}) } } #We check if package is scheduled for $scheduled_package (@scheduled_packages) { if ( $scheduled_package->{'FILEID'} =~ /^$fileid$/ ) { $schedule = $scheduled_package->{'SCHEDULE'}; last; } } #We check if package is affected with a postcmd command for $postcmd_package (@postcmd_packages) { if ( $postcmd_package->{'FILEID'} =~ /^$fileid$/ ) { $postcmd = $postcmd_package->{'POSTCMD'}; last; } } push @packages,{ 'TYPE' => 'PACK', 'ID' => $pack_row->{'FILEID'}, 'INFO_LOC' => $pack_row->{'INFO_LOC'}, 'PACK_LOC' => $pack_row->{'PACK_LOC'}, 'CERT_PATH' => $pack_row->{'CERT_PATH'}?$pack_row->{'CERT_PATH'}:'INSTALL_PATH', 'CERT_FILE' => $pack_row->{'CERT_FILE'}?$pack_row->{'CERT_FILE'}:'INSTALL_PATH', 'SCHEDULE' => $schedule?$schedule:'', 'POSTCMD' => $postcmd?$postcmd:'', 'FORCE' => 0 }; push @dont_repeat, $fileid; } } } #We get packages for this computer $pack_sql = q { SELECT e.ID, e.FILEID, e.INFO_LOC, e.PACK_LOC, e.CERT_PATH, e.CERT_FILE, e.SERVER_ID FROM devices d, download_enable e WHERE d.HARDWARE_ID=? AND d.IVALUE=e.ID AND d.NAME='DOWNLOAD' AND (d.TVALUE IS NULL OR d.TVALUE='NOTIFIED') }; $pack_req = $dbh->prepare( $pack_sql ); # Retrieving packages associated to the current device $pack_req->execute( $hardware_id ); while($pack_row = $pack_req->fetchrow_hashref()){ my $fileid = $pack_row->{'FILEID'}; my $enable_id = $pack_row->{'ID'}; my $pack_loc = $pack_row->{'PACK_LOC'}; my ($forced, $schedule, $scheduled_package, $postcmd, $postcmd_package); #We check if package is scheduled for $scheduled_package (@scheduled_packages) { if ( $scheduled_package->{'FILEID'} == $fileid ) { $schedule = $scheduled_package->{'SCHEDULE'}; last; } } #We check if package is affected with a postcmd command for $postcmd_package (@postcmd_packages) { if ( $postcmd_package->{'FILEID'} == $fileid ) { $postcmd = $postcmd_package->{'POSTCMD'}; last; } } #We check if package is marcked as forced if ( grep /^$fileid$/, @forced_packages ) { $forced = 1; } else { $forced = 0; } # If the package is in history, the device will not be notified # We have to show this behaviour to user. We use the package events. if ($forced == 0){ if ( grep /^$fileid$/, @history ){ $dbh->do(q{ UPDATE devices SET TVALUE='SUCCESS_ALREADY_IN_HISTORY', COMMENTS=? WHERE NAME='DOWNLOAD' AND HARDWARE_ID=? AND IVALUE=? }, {}, scalar localtime(), $current_context->{'DATABASE_ID'}, $enable_id ) ; next ; } } if( grep /^$fileid$/, @dont_repeat){ next; } # Substitude $IP$ with server ipaddress or $NAME with server name my %substitute = ( '$IP$' => {'table' => 'hardware', 'field' => 'IPADDR'}, '$NAME$' => {'table' => 'hardware', 'field' => 'NAME'} ); for my $motif (keys(%substitute)){ if($pack_loc=~/\Q$motif\E/){ my( $srvreq, $srvreq_sth, $srvreq_row); my $field = $substitute{$motif}->{field}; my $table = $substitute{$motif}->{table}; $srvreq = "select $field from $table where ID=?"; $srvreq_sth = $dbh->prepare($srvreq); $srvreq_sth->execute($pack_row->{'SERVER_ID'}); if($srvreq_row=$srvreq_sth->fetchrow_hashref()){ my $template = $srvreq_row->{$field}; $pack_loc =~ s/(.*)\Q$motif\E(.*)/${1}${template}${2}/g; } else{ $pack_loc=''; } } } next if $pack_loc eq ''; push @packages,{ 'TYPE' => 'PACK', 'ID' => $pack_row->{'FILEID'}, 'INFO_LOC' => $pack_row->{'INFO_LOC'}, 'PACK_LOC' => $pack_loc, 'CERT_PATH' => $pack_row->{'CERT_PATH'}?$pack_row->{'CERT_PATH'}:'INSTALL_PATH', 'CERT_FILE' => $pack_row->{'CERT_FILE'}?$pack_row->{'CERT_FILE'}:'INSTALL_PATH', 'SCHEDULE' => $schedule?$schedule:'', 'POSTCMD' => $postcmd?$postcmd:'', 'FORCE' => $forced }; push @dont_repeat, $fileid; } $dbh->do(q{ UPDATE devices SET TVALUE='NOTIFIED', COMMENTS=? WHERE NAME='DOWNLOAD' AND HARDWARE_ID=? AND TVALUE IS NULL } ,{}, scalar localtime(), $current_context->{'DATABASE_ID'} ) if $pack_req->rows; } push @{ $resp->{'OPTION'} },{ 'NAME' => ['DOWNLOAD'], 'PARAM' => \@packages }; return 0; } sub download_post_inventory{ my $current_context = shift; return if !$ENV{'OCS_OPT_DOWNLOAD'}; my $dbh = $current_context->{'DBI_HANDLE'}; my $hardwareId = $current_context->{'DATABASE_ID'}; my $result = $current_context->{'XML_ENTRY'}; my @fromXml = get_history_xml( $result ); my @fromDb; if( $ENV{OCS_OPT_INVENTORY_WRITE_DIFF} ){ @fromDb = get_history_db( $hardwareId, $dbh ); &update_history_diff( $hardwareId, $dbh, \@fromXml, \@fromDb ); } else{ &update_history_full( $hardwareId, $dbh, \@fromXml ); } } sub download_handler{ # Initialize data my $current_context = shift; my $dbh = $current_context->{'DBI_HANDLE'}; my $result = $current_context->{'XML_ENTRY'}; my $r = $current_context->{'APACHE_OBJECT'}; my $hardware_id = $current_context->{'DATABASE_ID'}; my $request; $request = $dbh->prepare(' SELECT ID FROM download_enable WHERE FILEID=? AND ID IN (SELECT IVALUE FROM devices WHERE NAME="download" AND HARDWARE_ID=?)'); $request->execute( $result->{'ID'}, $hardware_id); &_log(2001, 'download', "$result->{'ID'}(".($result->{'ERR'}?$result->{'ERR'}:'UNKNOWN_CODE').")"); if(my $row = $request->fetchrow_hashref()){ $dbh->do('UPDATE devices SET TVALUE=?, COMMENTS=? WHERE NAME="DOWNLOAD" AND HARDWARE_ID=? AND IVALUE=?', {}, $result->{'ERR'}?$result->{'ERR'}:'UNKNOWN_CODE', scalar localtime(), $hardware_id, $row->{'ID'} ) or return(APACHE_SERVER_ERROR); &_set_http_header('content-length', 0, $r); &_send_http_headers($r); return(APACHE_OK); }else{ &_log(2501, 'download', "$result->{'ID'}(".($result->{'ERR'}?$result->{'ERR'}:'UNKNOWN_CODE').")"); &_set_http_header('content-length', 0, $r); &_send_http_headers($r); return(APACHE_OK); } } sub download_duplicate { my $current_context = shift; my $device = shift; my $dbh = $current_context->{'DBI_HANDLE'}; # Handle deployment servers $dbh->do('UPDATE download_enable SET SERVER_ID=? WHERE SERVER_ID=?', {}, $current_context->{'DATABASE_ID'}, $device); $dbh->do('UPDATE download_servers SET HARDWARE_ID=? WHERE HARDWARE_ID=?', {}, $current_context->{'DATABASE_ID'}, $device); # If we encounter problems, it aborts whole replacement return $dbh->do('DELETE FROM download_history WHERE HARDWARE_ID=?', {}, $device); } # Subroutine to get packagesmarked as scheduled sub get_scheduled_packages { my ($dbh, $hardware_id, $scheduled_packages) = @_; my ($scheduled_sql, $scheduled_req, $scheduled_row, $package, @package_ids); $scheduled_sql = q { SELECT FILEID,TVALUE FROM devices,download_enable WHERE HARDWARE_ID=? AND devices.IVALUE=download_enable.ID AND devices.NAME='DOWNLOAD_SCHEDULE' AND TVALUE IS NOT NULL }; $scheduled_req = $dbh->prepare( $scheduled_sql ); $scheduled_req->execute( $hardware_id ); for $package (@$scheduled_packages) { push @package_ids, $package->{'FILEID'}; } while( $scheduled_row = $scheduled_req->fetchrow_hashref ){ # If package is not already in array (to prevent problems with groups) unless ( grep /^$scheduled_row->{'FILEID'}$/, @$scheduled_packages ) { push @$scheduled_packages, { 'FILEID' => $scheduled_row->{'FILEID'}, 'SCHEDULE' => $scheduled_row->{'TVALUE'} }; } } } # Subroutine to get packagesmarked as forced sub get_forced_packages { my ($dbh, $hardware_id, $forced_packages) = @_; my ($forced_sql, $forced_req, $forced_row); $forced_sql = q { SELECT FILEID FROM devices,download_enable WHERE HARDWARE_ID=? AND devices.IVALUE=download_enable.ID AND devices.NAME='DOWNLOAD_FORCE' AND TVALUE=1 }; $forced_req = $dbh->prepare( $forced_sql ); $forced_req->execute( $hardware_id ); while( $forced_row = $forced_req->fetchrow_hashref ){ # If package is not already in array (to prevent problems with groups) unless ( grep /^$forced_row->{'FILEID'}$/, @$forced_packages ) { push @$forced_packages, $forced_row->{'FILEID'}; } } } # Subroutine to get packages affected with a postcmd command sub get_postcmd_packages { my ($dbh, $hardware_id, $postcmd_packages) = @_; my ($postcmd_sql, $postcmd_req, $postcmd_row, $package, @package_ids); $postcmd_sql = q { SELECT FILEID,TVALUE FROM devices,download_enable WHERE HARDWARE_ID=? AND devices.IVALUE=download_enable.ID AND devices.NAME='DOWNLOAD_POSTCMD' AND TVALUE IS NOT NULL }; $postcmd_req = $dbh->prepare( $postcmd_sql ); $postcmd_req->execute( $hardware_id ); for $package (@$postcmd_packages) { push @package_ids, $package->{'FILEID'}; } while( $postcmd_row = $postcmd_req->fetchrow_hashref ){ # If package is not already in array (to prevent problems with groups) unless ( grep /^$postcmd_row->{'FILEID'}$/, @$postcmd_packages ) { push @$postcmd_packages, { 'FILEID' => $postcmd_row->{'FILEID'}, 'POSTCMD' => $postcmd_row->{'TVALUE'} }; } } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Download/000077500000000000000000000000001376436473200263145ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Download/Inventory.pm000066400000000000000000000065101376436473200306510ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Download::Inventory; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / get_history_xml get_history_db update_history_full update_history_diff /; use strict; use Apache::Ocsinventory::Server::System; sub get_history_xml{ my $result = shift; my $base = $result->{CONTENT}->{DOWNLOAD}->{HISTORY}->{PACKAGE}; my @ret; for( @$base ){ push @ret, $_->{ID}; } return @ret; } sub get_history_db{ my ( $hardwareId, $dbh ) = @_; my $sth = $dbh->prepare('SELECT PKG_ID from download_history WHERE HARDWARE_ID=?'); my @ret; if( $sth->execute( $hardwareId ) ){ while( my $row = $sth->fetchrow_hashref ){ push @ret, $row->{PKG_ID}; } } else{ &_log(2502, 'download'); } return @ret; } sub update_history_full{ my ( $hardwareId, $dbh, $pkgList ) = @_; my ( @blacklist, $already_set ); $dbh->do('DELETE FROM download_history WHERE HARDWARE_ID=?', {}, $hardwareId); my $sth = $dbh->prepare('INSERT INTO download_history(HARDWARE_ID, PKG_ID) VALUE(?,?)'); for my $entry ( @{ $pkgList }) { # fix the history handling bug (agent side) $already_set=0; for(@blacklist){ if($_ eq $entry){ $already_set=1; last; } } if(!$already_set){ push @blacklist, $entry; $sth->execute( $hardwareId, $entry ); } } } sub update_history_diff{ my ( $hardwareId, $dbh, $fromXml, $fromDb ) = @_; my @alreadyhandled; for my $l_xml (@$fromXml){ my $found = 0; for my $i_db (0..(@{$fromDb}-1)){ next unless $fromDb->[$i_db]; if($fromDb->[$i_db] eq $l_xml){ $found = 1; # The value has been found, we have to delete it from the db list # (elements remaining will be deleted) delete $fromDb->[$i_db]; last; } } if(!$found){ $dbh->do( 'INSERT INTO download_history(HARDWARE_ID, PKG_ID) VALUE(?,?)', {}, $hardwareId, $l_xml ) unless grep /\Q$l_xml\E/, @alreadyhandled; } push @alreadyhandled, $l_xml; } for( @$fromDb ){ next if !defined ($_); $dbh->do( 'DELETE FROM download_history WHERE HARDWARE_ID=? AND PKG_ID=?', {}, $hardwareId, $_ ); } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Example.pm000066400000000000000000000151721376436473200265040ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ # This core module is used to guide you through the module creation # All modules using modperl api functions must use the wrappers defined in MODPERL1 or 2 .pm # or create a new one in these 2 files if you need to use something that is not wrapped yet package Apache::Ocsinventory::Server::Option::Example; use strict; # This block specify which wrapper will be used ( your module will be compliant with all mod_perl versions ) BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } # These are the core modules you must include in addition use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'EXAMPLE', 'HANDLER_PROLOG_READ' => \&example_prolog_read, #or undef # Called before reading the prolog 'HANDLER_PROLOG_RESP' => \&example_prolog_resp, #or undef # Called after the prolog response building 'HANDLER_PRE_INVENTORY' => \&example_pre_inventory, #or undef # Called before reading inventory 'HANDLER_POST_INVENTORY' => \&example_post_inventory, #or undef # Called when inventory is stored without error 'REQUEST_NAME' => 'EXAMPLE', #or undef # Value of xml tag 'HANDLER_REQUEST' => \&example_handler, #or undef # function that handle the request with the 'REQUEST NAME' 'HANDLER_DUPLICATE' => \&example_duplicate,#or undef # Called when a computer is handle as a duplicate 'TYPE' => OPTION_TYPE_SYNC, # or OPTION_TYPE_ASYNC ASYNC=>with pr without inventory, SYNC=>only when inventory is required 'XML_PARSER_OPT' => { 'ForceArray' => ['xml_tag'] } }; # Default options of your module $Apache::Ocsinventory::OPTIONS{'OCS_OPT_EXAMPLE_FOO'} = 0; $Apache::Ocsinventory::OPTIONS{'OCS_OPT_EXAMPLE_BAR'} = 1; $Apache::Ocsinventory::OPTIONS{'OCS_OPT_EXAMPLE_TOTO'} = 'titi'; # These options will be loaded by ocs when apache will start. # You can put it in ocsinventory.conf using PerlSetEnv directive (Ex: PerlSetEnv OCS_OPT_EXAMPLE_FOO 1) # The settings you put to the configuration file will overload your default # Use it as it was in the apache environnement (ex: $Apache::Ocsinventory::OPTIONS{'OCS_OPT_EXAMPLE_FOO'}-use it as $ENV{'OCS_OPT_EXAMPLE_FOO'} # The GUI refer to it with OCS_OPT_ removed (ex: OCS_OPT_EXAMPLE_FOO => EXAMPLE_FOO). It must be in 'config' table and overload the default settings of this file AND overload the settings in ocsinventory.conf too. # For every module handlers, your functions will be called with certain parameters. # It provides you all the current environnement at the moment of the call # The structure: # #%CURRENT_CONTEXT = ( # 'APACHE_OBJECT' => ref, gives you a pointer to the apache request object -- Always filled # 'DBI_HANDLE' => ref, gives you a pointer to the database handle -- Always filled # 'DEVICEID' => string, gives you the computer's unique deviceid -- Always filled # 'DATABASE_ID' => integer, gives you the computer's database identifier -- Always filled # 'DATA' => ref, gives you a pointer to the initial deflated data (earliest stage) -- Always filled # 'RAW_DATA' => ref, gives you a pointer to the initial compressed data (earliest stage) -- Always filled # 'XML_ENTRY' => ref, gives you a pointer to the data structure generated when parsing the incoming request (with core and optionnal modules parsing options) -- Always filled # 'LOCK_FL' => 1(true) or 0(false), shows if the computer is locked -- Always filled # 'EXIST_FL' => 1(true) or 0(false) shows if the computer whether exists in the database or not (update) -- Always filled # 'MEMBER_OF' => array ref, gives you the groups that computer is member of #); sub example_prolog_read{ # This handler must return either PROLOG_CONTINUE or PROLOG_STOP # This mechanism enables you to completely stop the process at its beginning my $stop = 0; if($stop){ &_log(0,'example','stop prolog !!') if $ENV{'OCS_OPT_LOGLEVEL'}; return PROLOG_STOP; } else{ &_log(0,'example','let prolog go on !!') if $ENV{'OCS_OPT_LOGLEVEL'}; return PROLOG_CONTINUE; } } sub example_prolog_resp{ # Enables you to add tags to xml prolog response # Commonly used to ask an agent module to do something return 1; } sub example_pre_inventory{ # This handler must return either INVENTORY_CONTINUE or INVENTORY_STOP # This mechanism enables you to completely stop the process at its beginning my $stop = 0; if($stop){ &_log(0,'example','I HATE inventory, I stop it !!') if $ENV{'OCS_OPT_LOGLEVEL'}; return INVENTORY_STOP; } else{ &_log(0,'example','I love inventory !!') if $ENV{'OCS_OPT_LOGLEVEL'}; return INVENTORY_CONTINUE; } } sub example_post_inventory{ # This handler is useful to read "extra section" of an inventory # Commonly used to read data added to inventory by an agent module return 1; } sub example_handler{ # This function will be used for a dedicated request (like "INVENTORY" or "PROLOG") # It is designed to implement your own requests by using agent modules # You return from here directly to apache # Then, you must use the apache constants redefined in MODPERL1 or 2 .pm return 1; } sub example_duplicate{ # Useful to manage duplicate with your own tables/structures when a computer is evaluated as a duplicate and replaced return 1; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Filter.pm000066400000000000000000000072421376436473200263350ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ # This core module is used to implement what filter you want. package Apache::Ocsinventory::Server::Capacities::Filter; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'HANDLER_PROLOG_READ' => \&filter_prolog, 'HANDLER_PROLOG_RESP' => undef, 'HANDLER_PRE_INVENTORY' => \&filter_inventory, 'HANDLER_POST_INVENTORY' => undef, 'REQUEST_NAME' => undef, 'HANDLER_REQUEST' => undef, 'HANDLER_DUPLICATE' => undef, 'TYPE' => OPTION_TYPE_SYNC, 'XML_PARSER_OPT' => { 'ForceArray' => [] } }; sub filter_prolog{ # ON/OFF return PROLOG_CONTINUE unless $ENV{'OCS_OPT_PROLOG_FILTER_ON'}; my $current_context = shift; return PROLOG_CONTINUE if $current_context->{IS_TRUSTED}; my @filters = ( ); for( @filters ){ if ( &$_( $current_context ) == PROLOG_STOP ){ return PROLOG_STOP; } } return PROLOG_CONTINUE; } sub filter_inventory{ # ON/OFF return INVENTORY_CONTINUE unless $ENV{'OCS_OPT_INVENTORY_FILTER_ON'}; my $current_context = shift; return INVENTORY_CONTINUE if $current_context->{IS_TRUSTED}; my @filters = ( \&filter_flood_ip_killer ); for( @filters ){ if ( &$_( $current_context ) == INVENTORY_STOP ){ return INVENTORY_STOP; } } return INVENTORY_CONTINUE; } sub filter_flood_ip_killer{ return INVENTORY_CONTINUE unless $ENV{'OCS_OPT_INVENTORY_FILTER_FLOOD_IP'}; my $current_context = shift; my $dbh = $current_context->{DBI_HANDLE}; # In seconds my $flushEverySeconds = $ENV{OCS_OPT_INVENTORY_FILTER_FLOOD_IP_CACHE_TIME}; # Clear cache $dbh->do( 'DELETE FROM conntrack WHERE (UNIX_TIMESTAMP()-UNIX_TIMESTAMP(TIMESTAMP))>?', {}, $flushEverySeconds ); # If we cannot insert ipadress, we consider that it is in cache, then forbid transmission if( !($current_context->{EXIST_FL}) && !( $dbh->do('INSERT INTO conntrack(IP,TIMESTAMP) VALUES(?,NULL)', {}, $current_context->{IPADDRESS})) ){ &_log(519,'filter_flood_ip_killer','new device forbidden') if $ENV{'OCS_OPT_LOGLEVEL'}; return INVENTORY_STOP; } else{ # Everything is ok return INVENTORY_CONTINUE; } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Ipdiscover.pm000066400000000000000000000341141376436473200272150ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Ipdiscover; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::Useragent qw / _get_useragent /; use constant IPD_NEVER => 0; use constant IPD_ON => 1; use constant IPD_MAN => 2; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'IPDISCOVER', 'HANDLER_PROLOG_READ' => undef, 'HANDLER_PROLOG_RESP' => \&_ipdiscover_prolog_resp, 'HANDLER_PRE_INVENTORY' => undef, 'HANDLER_POST_INVENTORY' => \&_ipdiscover_main, 'REQUEST_NAME' => undef, 'HANDLER_REQUEST' => undef, 'HANDLER_DUPLICATE' => undef, 'TYPE' => OPTION_TYPE_SYNC, 'XML_PARSER_OPT' => { 'ForceArray' => ['H', 'NETWORKS'] } }; sub _ipdiscover_prolog_resp{ return unless $ENV{'OCS_OPT_IPDISCOVER'}; my $current_context = shift; return unless $current_context->{'EXIST_FL'}; my $resp = shift; my ($ua, $os, $v); return unless (ref $current_context->{'PARAMS'}{'IPDISCOVER'} eq ref {}); # Not a HASH reference my $lanToDiscover = $current_context->{'PARAMS'}{'IPDISCOVER'}->{'TVALUE'}; my $behaviour = $current_context->{'PARAMS'}{'IPDISCOVER'}->{'IVALUE'}; my $groupsParams = $current_context->{'PARAMS_G'}; my $ipdiscoverLatency; return if !defined($behaviour) or $behaviour == IPD_NEVER; if($lanToDiscover){ &_log(1004,'ipdiscover','incoming') if $ENV{'OCS_OPT_LOGLEVEL'}; # We can use groups to prevent some computers to be elected if( $ENV{'OCS_OPT_ENABLE_GROUPS'} && $ENV{'OCS_OPT_IPDISCOVER_USE_GROUPS'} ){ for(keys(%$groupsParams)){ if(defined($$groupsParams{$_}->{'IPDISCOVER'}->{'IVALUE'}) && $$groupsParams{$_}->{'IPDISCOVER'}->{'IVALUE'} == IPD_NEVER){ &_log(1005,'ipdiscover','conflict') if $ENV{'OCS_OPT_LOGLEVEL'}; return; } } } $resp->{'RESPONSE'} = [ 'SEND' ]; # Agents newer than 13(linux) ans newer than 4027(Win32) receive new xml formatting (including ipdisc_lat) $ua = $current_context->{'USER_AGENT'}; my $legacymode; if( $ua=~/OCS-NG_(\w+)_client_v(\d+)/ ){ $legacymode = 1 if ($1 eq "windows" && $2<=4027) or ($1 eq "linux" && $2<=13); } if( $legacymode ){ push @{$$resp{'OPTION'}}, { 'NAME' => [ 'IPDISCOVER' ], 'PARAM' => [ $lanToDiscover ] }; } else{ if(defined( $current_context->{'PARAMS'}{'IPDISCOVER_LATENCY'}->{'IVALUE'} )){ $ipdiscoverLatency = $current_context->{'PARAMS'}{'IPDISCOVER_LATENCY'}->{'IVALUE'}; } else{ for(keys(%$groupsParams)){ $ipdiscoverLatency = $$groupsParams{$_}->{'IPDISCOVER_LATENCY'}->{'IVALUE'} if (exists($$groupsParams{$_}->{'IPDISCOVER_LATENCY'}->{'IVALUE'}) and $$groupsParams{$_}->{'IPDISCOVER_LATENCY'}->{'IVALUE'}>$ipdiscoverLatency) or !$ipdiscoverLatency; } } unless( $ipdiscoverLatency ){ $ipdiscoverLatency = $ENV{'OCS_OPT_IPDISCOVER_LATENCY'}?$ENV{'OCS_OPT_IPDISCOVER_LATENCY'}:100; } push @{$$resp{'OPTION'}}, { 'NAME' => [ 'IPDISCOVER' ], 'PARAM' => { 'IPDISC_LAT' => $ipdiscoverLatency, 'content' => $lanToDiscover } }; } &_set_http_header('Connection', 'close', $current_context->{'APACHE_OBJECT'}); return 1; }else{ return 0; } } sub _ipdiscover_main{ my $request; my $row; my $subnet; my $remove; return unless $ENV{'OCS_OPT_IPDISCOVER'}; my $current_context = shift; return if $current_context->{'LOCAL_FL'}; return unless (ref $current_context->{'PARAMS'}{'IPDISCOVER'} eq ref {}); # Not a HASH reference my $DeviceID = $current_context->{'DATABASE_ID'}; my $dbh = $current_context->{'DBI_HANDLE'}; my $result = $current_context->{'XML_ENTRY'}; my $lanToDiscover = $current_context->{'PARAMS'}{'IPDISCOVER'}->{'TVALUE'}; my $behaviour = $current_context->{'PARAMS'}{'IPDISCOVER'}->{'IVALUE'}; my $groupsParams = $current_context->{'PARAMS_G'}; #Special array to define agents that could be automatic ipdscover elected my @ipdiscover_agents = ( 'OCS-NG_unified_unix_agent', 'OCS-NG_windows_client', 'OCS-NG_WINDOWS_AGENT', ); #IVALUE = 0 means that computer will not ever be elected if( defined($behaviour) && $behaviour == IPD_NEVER ){ return 0; } # We can use groups to prevent some computers to be elected if( $ENV{'OCS_OPT_ENABLE_GROUPS'} && $ENV{'OCS_OPT_IPDISCOVER_USE_GROUPS'} ){ for(keys(%$groupsParams)){ return 0 if defined($$groupsParams{$_}->{'IPDISCOVER'}->{'IVALUE'}) && $$groupsParams{$_}->{'IPDISCOVER'}->{'IVALUE'} == IPD_NEVER; } } # Is the device already have the ipdiscover function ? if($lanToDiscover){ # get 1 on removing and 0 if ok $remove = &_ipdiscover_read_result($dbh, $result, $lanToDiscover); if( $behaviour == IPD_MAN ){ $remove = 0; } if(!defined($remove)){ return 1; } }else{ my $useragent = &_get_useragent(); unless (grep /^($useragent->{'NAME'})$/, @ipdiscover_agents){ return 0; } # Get quality and fidelity $request = $dbh->prepare('SELECT QUALITY,FIDELITY FROM hardware WHERE ID=?'); $request->execute($DeviceID); if($row = $request->fetchrow_hashref){ if( ($row->{'FIDELITY'} > 2 and $row->{'QUALITY'} != 0) || $ENV{'OCS_OPT_IPDISCOVER_NO_POSTPONE'} ){ $subnet = &_ipdiscover_find_iface($result, $current_context->{'DBI_HANDLE'}); if(!$subnet){ return &_ipdiscover_evaluate($result, $row->{'FIDELITY'}, $row->{'QUALITY'}, $dbh, $DeviceID); }elsif($subnet =~ /^(\d{1,3}(?:\.\d{1,3}){3})$/){ # The computer is elected, we have to write it in devices $dbh->do('INSERT INTO devices(HARDWARE_ID, NAME, IVALUE, TVALUE, COMMENTS) VALUES(?,?,?,?,?)',{},$DeviceID,'IPDISCOVER',1,$subnet,'') or return 1; &_log(1001,'ipdiscover','elected'."($subnet)") if $ENV{'OCS_OPT_LOGLEVEL'}; return 0; }else{ return 0; } }else{ return 0; } } } # If needed, we remove if($remove){ if(!$dbh->do('DELETE FROM devices WHERE HARDWARE_ID=? AND NAME="IPDISCOVER"', {}, $DeviceID)){ return 1; } $dbh->commit; &_log(1002,'ipdiscover','removed') if $ENV{'OCS_OPT_LOGLEVEL'}; } 0; } sub _ipdiscover_read_result{ my ($dbh, $result, $subnet) = @_; my $mask; my $update_req; my $insert_req; my $request; my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; if(exists($result->{CONTENT}->{IPDISCOVER})){ my $base = $result->{CONTENT}->{NETWORKS}; # Retrieve netmask for(@$base){ if($_->{IPSUBNET} eq $subnet){ $mask = $_->{IPMASK}; last; } } $base = $result->{CONTENT}->{IPDISCOVER}->{H}; if( $ENV{'OCS_OPT_IPDISCOVER_LINK_TAG_NETWORK'} ) { my $request_tag = $dbh->prepare('SELECT TAG FROM accountinfo WHERE HARDWARE_ID=?'); my $tag = undef; unless($request_tag->execute($DeviceID)){ &_log(519,'ipdiscover','computer tag error') if $ENV{'OCS_OPT_LOGLEVEL'}; return(1); } my $row = $request_tag->fetchrow_hashref; if (defined $row->{'TAG'}) { $tag = $row->{'TAG'}; } # We insert the results (MAC/IP) for(@$base){ unless($_->{I}=~/^(\d{1,3}(?:\.\d{1,3}){3})$/ and $_->{M}=~/.{2}(?::.{2}){5}/){ &_log(1003,'ipdiscover','bad_result') if $ENV{'OCS_OPT_LOGLEVEL'}; next; } my $request_verif = $dbh->prepare('SELECT TAG FROM netmap WHERE MAC=?'); $request_verif->execute($_->{M}); my $row_verif = $request_verif->fetchrow_hashref; if (defined $row_verif->{'TAG'}) { $update_req = $dbh->prepare('UPDATE netmap SET IP=?,MASK=?,NETID=?,DATE=NOW(), NAME=? WHERE MAC=? AND TAG=?'); $update_req->execute($_->{I}, $mask, $subnet, $_->{N}, $_->{M}, $tag); } else { $update_req = $dbh->prepare('UPDATE netmap SET IP=?,MASK=?,NETID=?,DATE=NOW(), NAME=?, TAG=? WHERE MAC=?'); $update_req->execute($_->{I}, $mask, $subnet, $_->{N}, $tag, $_->{M}); } unless($update_req->rows){ $insert_req = $dbh->prepare('INSERT INTO netmap(IP, MAC, MASK, NETID, NAME, TAG) VALUES(?,?,?,?,?,?)'); $insert_req->execute($_->{I}, $_->{M}, $mask, $subnet, $_->{N}, $tag); } } } else { # We insert the results (MAC/IP) $update_req = $dbh->prepare('UPDATE netmap SET IP=?,MASK=?,NETID=?,DATE=NOW(), NAME=? WHERE MAC=?'); $insert_req = $dbh->prepare('INSERT INTO netmap(IP, MAC, MASK, NETID, NAME) VALUES(?,?,?,?,?)'); for(@$base){ unless($_->{I}=~/^(\d{1,3}(?:\.\d{1,3}){3})$/ and $_->{M}=~/.{2}(?::.{2}){5}/){ &_log(1003,'ipdiscover','bad_result') if $ENV{'OCS_OPT_LOGLEVEL'}; next; } $update_req->execute($_->{I}, $mask, $subnet, $_->{N}, $_->{M}); unless($update_req->rows){ $insert_req->execute($_->{I}, $_->{M}, $mask, $subnet, $_->{N}); } } } $dbh->commit; }else{ return 1; } # Maybe There are too much ipdiscover per subnet ? $request=$dbh->prepare('SELECT HARDWARE_ID FROM devices WHERE TVALUE=? AND NAME="IPDISCOVER"'); $request->execute($subnet); if($request->rows > $ENV{'OCS_OPT_IPDISCOVER'}){ $request->finish; return 1; } # check ignored subnet $request=$dbh->prepare('SELECT SUBNET FROM blacklist_subnet WHERE SUBNET=?'); $request->execute($subnet); if($request->rows > 0){ return 1; } return 0; } sub _ipdiscover_find_iface{ my $result = shift; my $base = $result->{CONTENT}->{NETWORKS}; my $dbh = shift; my $request; my @worth; for(@$base){ if($_->{DESCRIPTION}!~/ppp/i){ if($_->{STATUS}=~/up/i){ if($_->{IPMASK}=~/^(?:255\.){2}|^0x(?:ff){2}/){ if($_->{IPSUBNET}=~/^(\d{1,3}(?:\.\d{1,3}){3})$/){ # check ignored subnet $request = $dbh->prepare('SELECT SUBNET FROM blacklist_subnet WHERE SUBNET=?'); $request->execute($_->{IPSUBNET}); if($request->rows > 0){ next; } # Looking for a need of ipdiscover $request = $dbh->prepare('SELECT HARDWARE_ID FROM devices WHERE TVALUE=? AND NAME="IPDISCOVER"'); $request->execute($_->{IPSUBNET}); if($request->rows < $ENV{'OCS_OPT_IPDISCOVER'}){ $request->finish; return $_->{IPSUBNET}; } $request->finish; }}}} # Looking for ipdiscover older than ipdiscover_max_value # and compare current computer with actual ipdiscover } return 0; } sub _ipdiscover_evaluate{ my ($result, $fidelity, $quality, $dbh, $DeviceID) = @_; my $request; my $row; my $time = time(); my $max_age = $ENV{'OCS_OPT_IPDISCOVER_MAX_ALIVE'}*86400; my $over; my @worth; my $base = $result->{CONTENT}->{NETWORKS}; for(@$base){ if(defined($_->{IPSUBNET}) and $_->{IPSUBNET}=~/^(\d{1,3}(?:\.\d{1,3}){3})$/ ){ $request = $dbh->prepare(' SELECT h.ID AS ID, h.QUALITY AS QUALITY, UNIX_TIMESTAMP(h.LASTDATE) AS LAST FROM hardware h,devices d WHERE d.HARDWARE_ID=h.ID AND d.TVALUE=? AND h.ID<>? AND d.IVALUE<>? AND d.NAME="IPDISCOVER"'); $request->execute($_->{IPSUBNET}, $DeviceID, IPD_MAN); while($row = $request->fetchrow_hashref){ # If we find an ipdiscover that is older than IP_MAX_ALIVE, we replace it with the current if( (($time - $row->{'LAST'}) > $max_age) and $max_age){ @worth = ($row->{'ID'}, $row->{'QUALITY'} ); $over = 1; last; } # For the first round unless(@worth){ @worth = ($row->{'ID'}, $row->{'QUALITY'} ); next; } # Put the worth in @worth @worth = ( $row->{'ID'}, $row->{'QUALITY'} ) if $worth[1] < $row->{'QUALITY'}; } # If not over, we compare our quality with the one of the worth on this subnet. # If it is better more than one, we replace it if(@worth){ if(($quality < $worth[1] and (($worth[1]-$quality)>$ENV{'OCS_OPT_IPDISCOVER_BETTER_THRESHOLD'})) or $over){ # Compare to the current and replace it if needed if(!$dbh->do('UPDATE devices SET HARDWARE_ID=? WHERE HARDWARE_ID=? AND NAME="IPDISCOVER"', {}, $DeviceID, $worth[0])){ return 1; } $dbh->commit; &_log(1001,'ipdiscover',($over?'over':'better')."($_->{IPSUBNET})"."(OLD=($worth[0],$worth[1]),NEW=($DeviceID,$quality))(THRESHOLD=$ENV{'OCS_OPT_IPDISCOVER_BETTER_THRESHOLD'})") if $ENV{'OCS_OPT_LOGLEVEL'}; return 0; } } }else{ next; } } return 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Notify.pm000066400000000000000000000116771376436473200263670ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Notify; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'NOTIFY', 'HANDLER_PROLOG_READ' => undef, 'HANDLER_PROLOG_RESP' => undef, 'HANDLER_PRE_INVENTORY' => undef, 'HANDLER_POST_INVENTORY' => undef, 'REQUEST_NAME' => 'NOTIFY', 'HANDLER_REQUEST' => \¬ify_handler, 'HANDLER_DUPLICATE' => undef, 'TYPE' => OPTION_TYPE_ASYNC, 'XML_PARSER_OPT' => { 'ForceArray' => ['IFACE'] } }; sub notify_handler{ my $current_context = shift; if( !$current_context->{EXIST_FL} ){ &_log(322, 'notify', 'no_device'); return APACHE_OK; } &_log(322, 'notify', $current_context->{'XML_ENTRY'}->{TYPE}); if( $current_context->{'XML_ENTRY'}->{TYPE} eq 'IP' ){ &update_ip( $current_context ); } else{ &_log(529, 'notify', 'not_supported'); } return APACHE_OK; } sub update_ip{ # Initialize data my $current_context = shift; my $update_hardware; my $dbh = $current_context->{'DBI_HANDLE'}; my $result = $current_context->{'XML_ENTRY'}; my $hardwareId = $current_context->{'DATABASE_ID'}; my $select_h_sql = 'SELECT IPADDR,MACADDR FROM hardware h,networks n WHERE IPADDR=IPADDRESS AND h.ID=?'; my $updateMainIp_sql = 'UPDATE hardware SET IPADDR=? WHERE ID=?'; # Get default IP my $sth = $dbh->prepare( $select_h_sql ); $sth->execute( $hardwareId ); my $row = $sth->fetchrow_hashref; my $defaultIface = $row->{MACADDR}; my $defaultIp = $row->{IPADDR}; $sth->finish; if( exists $result->{IFACE} ){ for my $newIface ( @{$result->{IFACE}} ){ next if !$newIface->{IP} or !$newIface->{MASK} or !$newIface->{MAC}; my (@update_fields, @update_values); #We create update request using existing values only if ($newIface->{GW}) { push @update_fields,'IPGATEWAY=?'; push @update_values,$newIface->{GW}; } if ($newIface->{DHCP}) { push @update_fields,'IPDHCP=?'; push @update_values,$newIface->{DHCP}; } if ($newIface->{SUBNET}) { push @update_fields,'IPSUBNET=?'; push @update_values,$newIface->{SUBNET}; } if ($newIface->{IP}) { push @update_fields,'IPADDRESS=?'; push @update_values,$newIface->{IP}; } if ($newIface->{MASK}) { push @update_fields,'IPMASK=?'; push @update_values,$newIface->{MASK}; } push @update_values,$newIface->{MAC}; push @update_values,$hardwareId; my $updateIp_sql= 'UPDATE networks SET '.(join ',', @update_fields).' WHERE MACADDR=? AND HARDWARE_ID=?'; my $err = $dbh->do( $updateIp_sql, {}, @update_values ); if( !$err ){ &_log(530, 'notify', 'error'); } elsif( $err==0E0 ){ &_log(324, 'notify', $newIface->{MAC}); } else{ &_log(323, 'notify', "$newIface->{MAC}<$newIface->{IP}>"); if (exists $result->{HARDWARE}) { #New behaviour with additional tag $dbh->do( $updateMainIp_sql, {}, $result->{HARDWARE}->{IPADDR}, $hardwareId); $update_hardware = 1; } #We update CHECKSUM value in hardware table my $mask = $DATA_MAP{networks}{mask}; $mask = $mask|1 if $update_hardware; $dbh->do("UPDATE hardware SET CHECKSUM=($mask|CHECKSUM) WHERE ID=$hardwareId"); } } } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Registry.pm000066400000000000000000000057451376436473200267260ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Registry; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Map; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'REGISTRY', 'HANDLER_PROLOG_READ' => undef, 'HANDLER_PROLOG_RESP' => \&_registry_prolog_resp, 'HANDLER_PRE_INVENTORY' => undef, 'HANDLER_POST_INVENTORY' => undef, 'REQUEST_NAME' => undef, 'HANDLER_REQUEST' => undef, 'HANDLER_DUPLICATE' => undef, 'TYPE' => OPTION_TYPE_SYNC, 'XML_PARSER_OPT' => { 'ForceArray' => ['REGISTRY'] } }; sub _registry_prolog_resp{ return unless $ENV{'OCS_OPT_REGISTRY'}; my $current_context = shift; my $resp = shift; my $dbh = $current_context->{'DBI_HANDLE'}; # Sync option return if $resp->{'RESPONSE'} eq 'STOP'; my $request; my $row; ################################# #REGISTRY ######### # Ask computer to retrieve the requested registry keys my @registry; $request=$dbh->prepare('SELECT * FROM regconfig'); $request->execute; while($row = $request->fetchrow_hashref){ push @registry, { 'REGTREE' => $row->{'REGTREE'} , 'REGKEY' => $row->{'REGKEY'} , 'NAME' => $row->{'NAME'} , 'content' => $row->{'REGVALUE'} }; } if(@registry){ push @{ $resp->{'OPTION'} }, { 'NAME' => [ 'REGISTRY' ], 'PARAM' => \@registry }; return 1; }else{ return 0; } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Snmp.pm000066400000000000000000000264431376436473200260310ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ # This core module is used to guide you through the module creation # All modules using modperl api functions must use the wrappers defined in MODPERL1 or 2 .pm # or create a new one in these 2 files if you need to use something that is not wrapped yet package Apache::Ocsinventory::Server::Capacities::Snmp; use XML::Simple; use strict; # This block specify which wrapper will be used ( your module will be compliant with all mod_perl versions ) BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } # These are the core modules you must include in addition use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::Capacities::Snmp::Data; use Apache::Ocsinventory::Server::Capacities::Snmp::Inventory; #Getting sections for the 'ForceArray' option my @forceArray = ('DEVICE'); &_get_snmp_parser_ForceArray(\@forceArray); # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'SNMP', 'HANDLER_PROLOG_READ' => undef, #or undef # Called before reading the prolog 'HANDLER_PROLOG_RESP' => \&snmp_prolog_resp, #or undef # Called after the prolog response building 'HANDLER_PRE_INVENTORY' => undef , #or undef # Called before reading inventory 'HANDLER_POST_INVENTORY' => undef, #or undef # Called when inventory is stored without error 'REQUEST_NAME' => 'SNMP', #or undef # Value of xml tag 'HANDLER_REQUEST' => \&snmp_handler, #or undef # function that handle the request with the 'REQUEST NAME' 'HANDLER_DUPLICATE' => \&snmp_duplicate, #or undef # Called when a computer is handle as a duplicate 'TYPE' => OPTION_TYPE_SYNC, # or OPTION_TYPE_ASYNC ASYNC=>with pr without inventory, SYNC=>only when inventory is required 'XML_PARSER_OPT' => { 'ForceArray' => [@forceArray] } }; sub snmp_prolog_resp{ my $current_context = shift; my $resp = shift; my $select_ip_req; my $select_communities_req; my $select_snmp_type_req; my $select_deviceid_req; my $select_network_req; my $select_mibs_req; my @devicesToScan; my @networksToScan; my @communities; my @snmp_types; my @mibs; my @snmp_rework; #Verify if SNMP is enable for this computer or in config my $snmpSwitch = &_get_snmp_switch($current_context); return unless $snmpSwitch; ######### #SNMP ######### # Ask computer to scan the requested snmp network devices my @snmp; my $dbh = $current_context->{'DBI_HANDLE'}; my $lanToDiscover = $current_context->{'PARAMS'}{'IPDISCOVER'}->{'TVALUE'}; my $behaviour = $current_context->{'PARAMS'}{'IPDISCOVER'}->{'IVALUE'}; my $groupsParams = $current_context->{'PARAMS_G'}; #Only if communication is https if ($current_context->{'APACHE_OBJECT'}->subprocess_env('https')) { $select_deviceid_req=$dbh->prepare('SELECT DEVICEID FROM hardware WHERE DEVICEID=?'); $select_deviceid_req->execute($current_context->{'DEVICEID'}); #Only if agent deviceid already exists in database if ($select_deviceid_req->fetchrow_hashref) { #Getting networks specified for scans $select_network_req=$dbh->prepare("SELECT TVALUE FROM devices WHERE HARDWARE_ID=? AND NAME='SNMP_NETWORK'"); $select_network_req->execute($current_context->{'DATABASE_ID'}); #Getting networks separated by commas (will be removed when GUI will be OK to add several networks cleanly) my $row = $select_network_req->fetchrow_hashref; #Only one line per HARDWARE_ID @networksToScan= split(',',$row->{TVALUE}); #TODO: use this lines instead of previous ones when GUI will be OK to add several networks cleanly #while(my $row = $select_network_req->fetchrow_hashref){ # push @networksToScan,$row; #} if (@networksToScan) { #Adding devices informations in the XML foreach my $network (@networksToScan) { push @snmp,{ #'SUBNET' => $network->{TVALUE}, #TODO: uncomment this line when GUI will be OK to add several networks cleanly 'SUBNET' => $network, 'TYPE' => 'NETWORK', }; } } #If the computer is Ipdicover elected if ($behaviour == 1 || $behaviour == 2) { #Getting non inventoried network devices for the agent subnet $select_ip_req=$dbh->prepare('SELECT IP,MAC FROM netmap WHERE NETID=? AND mac NOT IN (SELECT DISTINCT(macaddr) FROM networks WHERE macaddr IS NOT NULL AND IPSUBNET=?)'); $select_ip_req->execute($lanToDiscover,$lanToDiscover); while(my $row = $select_ip_req->fetchrow_hashref){ push @devicesToScan,$row; } if (@devicesToScan) { #Adding devices informations in the XML foreach my $device (@devicesToScan) { push @snmp,{ 'IPADDR' => $device->{IP}, 'MACADDR' => $device->{MAC}, 'TYPE' => 'DEVICE', }; } } } #Getting snmp types $select_snmp_type_req = $dbh->prepare('SELECT t.TYPE_NAME, t.CONDITION_OID, t.CONDITION_VALUE, t.TABLE_TYPE_NAME, l.LABEL_NAME, c.OID FROM snmp_types t LEFT JOIN snmp_configs c ON t.ID = c.TYPE_ID LEFT JOIN snmp_labels l ON l.ID = c.LABEL_ID'); $select_snmp_type_req->execute(); while(my $row = $select_snmp_type_req->fetchrow_hashref){ push @snmp_types,$row; } if (@snmp_types) { foreach my $type (@snmp_types) { push @snmp,{ 'TYPE_NAME' => $type->{'TYPE_NAME'}?$type->{'TYPE_NAME'}:'', 'CONDITION_OID' => $type->{'CONDITION_OID'}?$type->{'CONDITION_OID'}:'', 'CONDITION_VALUE'=> $type->{'CONDITION_VALUE'}?$type->{'CONDITION_VALUE'}:'', 'TABLE_TYPE_NAME' => $type->{'TABLE_TYPE_NAME'}?$type->{'TABLE_TYPE_NAME'}:'', 'LABEL_NAME'=> $type->{'LABEL_NAME'}?$type->{'LABEL_NAME'}:'', 'OID' => $type->{'OID'}?$type->{'OID'}:'', 'TYPE' => 'SNMP_TYPE', }; } } if (@snmp) { #Getting snmp communities $select_communities_req = $dbh->prepare('SELECT VERSION,NAME,USERNAME,AUTHKEY,AUTHPASSWD FROM snmp_communities'); $select_communities_req->execute(); while(my $row = $select_communities_req->fetchrow_hashref){ push @communities,$row; } if (@communities) { foreach my $community (@communities) { push @snmp,{ 'VERSION' => $community->{'VERSION'}?$community->{'VERSION'}:'', 'NAME' => $community->{'NAME'}?$community->{'NAME'}:'', 'USERNAME'=> $community->{'USERNAME'}?$community->{'USERNAME'}:'', 'AUTHKEY' => $community->{'AUTHKEY'}?$community->{'AUTHKEY'}:'', 'AUTHPASSWD' => $community->{'AUTHPASSWD'}?$community->{'AUTHPASSWD'}:'', 'TYPE' => 'COMMUNITY', }; } } #Getting custom mibs informations $select_mibs_req = $dbh->prepare('SELECT VENDOR,URL,CHECKSUM,VERSION,PARSER FROM snmp_mibs'); $select_mibs_req->execute(); while(my $row = $select_mibs_req->fetchrow_hashref){ push @mibs,$row; } if (@mibs) { foreach my $mib (@mibs) { push @snmp,{ 'VENDOR' => $mib->{'VENDOR'}?$mib->{'VENDOR'}:'', 'URL'=> $mib->{'URL'}?$mib->{'URL'}:'', 'CHECKSUM' => $mib->{'CHECKSUM'}?$mib->{'CHECKSUM'}:'', 'VERSION' => $mib->{'VERSION'}?$mib->{'VERSION'}:'', 'PARSER' => $mib->{'PARSER'}?$mib->{'PARSER'}:'', 'TYPE' => 'MIB', }; } } #Final XML push @{ $resp->{'OPTION'} },{ 'NAME' => ['SNMP'], 'PARAM' => \@snmp, }; } } else { &_log(104,'snmp',"error: agent must have a deviceid in database !!") if $ENV{'OCS_OPT_LOGLEVEL'}; } } else { &_log(103,'snmp',"error: agent must communicate using https to be able to get SNMP communities (only affects OCS unix agent) !!") if $ENV{'OCS_OPT_LOGLEVEL'} and $ENV{'OCS_OPT_SNMP_PRINT_HTTPS_ERROR'} } } sub snmp_handler{ my $current_context = shift; #Verify if SNMP is enable for this computer or in config my $snmpSwitch = &_get_snmp_switch($current_context); return unless $snmpSwitch; my $dbh = $current_context->{'DBI_HANDLE'}; my $result = $current_context->{'XML_ENTRY'}; my $r = $current_context->{'APACHE_OBJECT'}; my $hardware_id = $current_context->{'DATABASE_ID'}; # Remanent data my ( %SNMP_SECTIONS, @SNMP_SECTIONS ); #We get snmp tables references from Map.pm &_init_snmp_map( \%SNMP_SECTIONS, \@SNMP_SECTIONS ); #Inventory incoming &_log(100,'snmp','inventory incoming') if $ENV{'OCS_OPT_LOGLEVEL'}; # Putting the SNMP inventory in the database if (&_snmp_inventory( \%SNMP_SECTIONS, \@SNMP_SECTIONS, $current_context->{'DATABASE_ID'})) { &_log(101,'snmp','inventory error !!') if $ENV{'OCS_OPT_LOGLEVEL'}; } else { &_log(102,'snmp','inventory transmitted') if $ENV{'OCS_OPT_LOGLEVEL'}; } #Sending Response to the agent &_set_http_header('content-length', 0, $r); &_send_http_headers($r); return (APACHE_OK); } sub snmp_duplicate{ # Useful to manage duplicate with your own tables/structures when a computer is evaluated as a duplicate and replaced return 1; } sub _get_snmp_switch { my $current_context = shift ; my $groupsParams = $current_context->{'PARAMS_G'}; my $snmpSwitch ; if($ENV{'OCS_OPT_SNMP'}){ $snmpSwitch = 1; # Groups custom parameter for(keys(%$groupsParams)){ $snmpSwitch = $$groupsParams{$_}->{'SNMP_SWITCH'}->{'IVALUE'} if exists( $$groupsParams{$_}->{'SNMP_SWITCH'}->{'IVALUE'} ) and $$groupsParams{$_}->{'SNMP_SWITCH'}->{'IVALUE'} < $snmpSwitch; } } else{ $snmpSwitch = 0; } #Computer custom parameter $snmpSwitch = $current_context->{'PARAMS'}{'SNMP_SWITCH'}->{'IVALUE'} if defined($current_context->{'PARAMS'}{'SNMP_SWITCH'}->{'IVALUE'}) and $snmpSwitch; return ($snmpSwitch); } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Snmp/000077500000000000000000000000001376436473200254625ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Snmp/Data.pm000066400000000000000000000164011376436473200266730ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Snmp::Data; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _init_snmp_map _get_snmp_bind_values _get_snmp_parser_ForceArray _snmp_has_changed /; use Digest::MD5 qw(md5_base64); use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::System qw / :server /; #TODO: see if we can use a comman Data.pm for standard inventory and snmp inventory. Maybe a var for HARDWARE_ID and SNMp_ID and a common grep to select tables ? sub _init_snmp_map{ my ($sectionsMeta, $sectionsList) = @_; my $section; my @bind_num; my $field; my $fields_string; my $field_index; # Parse snmp sections only for $section (keys(%DATA_MAP)){ if ($DATA_MAP{$section}->{capacities} =~ /^snmp$/ ) { $field_index = 0; # Field array (from data_map field hash keys), filtered fields and cached fields $sectionsMeta->{$section}->{field_arrayref} = []; $sectionsMeta->{$section}->{field_filtered} = []; $sectionsMeta->{$section}->{field_cached} = {}; ############################################## # Don't process the non-auto-generated sections next if !$DATA_MAP{$section}->{auto}; $sectionsMeta->{$section}->{multi} = 1 if $DATA_MAP{$section}->{multi}; $sectionsMeta->{$section}->{mask} = $DATA_MAP{$section}->{mask}; $sectionsMeta->{$section}->{delOnReplace} = 1 if $DATA_MAP{$section}->{delOnReplace}; $sectionsMeta->{$section}->{writeDiff} = 1 if $DATA_MAP{$section}->{writeDiff}; $sectionsMeta->{$section}->{cache} = 1 if $DATA_MAP{$section}->{cache}; $sectionsMeta->{$section}->{mandatory} = 1 if $DATA_MAP{$section}->{mandatory}; $sectionsMeta->{$section}->{name} = $section; # $sectionsMeta->{$section}->{hasChanged} is set while inventory update # Parse fields of the current section for $field ( keys(%{$DATA_MAP{$section}->{fields}} ) ){ if(!$DATA_MAP{$section}->{fields}->{$field}->{noSql}){ push @{$sectionsMeta->{$section}->{field_arrayref}}, $field; $sectionsMeta->{$section}->{noSql} = 1 unless $sectionsMeta->{$section}->{noSql}; } if($DATA_MAP{$section}->{fields}->{$field}->{filter}){ next unless $ENV{OCS_OPT_INVENTORY_FILTER_ENABLED}; push @{$sectionsMeta->{$section}->{field_filtered}}, $field; $sectionsMeta->{$section}->{filter} = 1 unless $sectionsMeta->{$section}->{filter}; } if($DATA_MAP{$section}->{fields}->{$field}->{cache}){ next unless $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED}; $sectionsMeta->{$section}->{field_cached}->{$field} = $field_index; $sectionsMeta->{$section}->{cache} = 1 unless $sectionsMeta->{$section}->{cache}; } if(defined $DATA_MAP{$section}->{fields}->{$field}->{fallback}){ $sectionsMeta->{$section}->{fields}->{$field}->{fallback} = $DATA_MAP{$section}->{fields}->{$field}->{fallback}; } if(defined $DATA_MAP{$section}->{fields}->{$field}->{type}){ $sectionsMeta->{$section}->{fields}->{$field}->{type} = $DATA_MAP{$section}->{fields}->{$field}->{type}; } $field_index++; } # Build the "DBI->prepare" sql insert string $fields_string = join ',', ('SNMP_ID', @{$sectionsMeta->{$section}->{field_arrayref}}); $sectionsMeta->{$section}->{sql_insert_string} = "INSERT INTO $section($fields_string) VALUES("; for(0..@{$sectionsMeta->{$section}->{field_arrayref}}){ push @bind_num, '?'; } $sectionsMeta->{$section}->{sql_insert_string}.= (join ',', @bind_num).')'; @bind_num = (); # Build the "DBI->prepare" sql select string $sectionsMeta->{$section}->{sql_select_string} = "SELECT ID,$fields_string FROM $section WHERE SNMP_ID=? ORDER BY ".$DATA_MAP{$section}->{sortBy}; # Build the "DBI->prepare" sql deletion string $sectionsMeta->{$section}->{sql_delete_string} = "DELETE FROM $section WHERE SNMP_ID=? AND ID=?"; # to avoid many "keys" push @$sectionsList, $section; } } } sub _get_snmp_bind_values{ my ($refXml, $sectionMeta, $arrayToFeed) = @_; my $bind_value; for my $field ( @{ $sectionMeta->{field_arrayref} } ) { if(defined($refXml->{$field}) && $refXml->{$field} ne '' && $refXml->{$field} ne '??' && $refXml->{$field}!~/^N\/?A$/){ $bind_value = $refXml->{$field} } else{ if( defined $sectionMeta->{fields}->{$field}->{fallback} ){ $bind_value = $sectionMeta->{fields}->{$field}->{fallback}; &_log( 000, 'fallback', "$field:".$sectionMeta->{fields}->{$field}->{fallback}) if $ENV{'OCS_OPT_LOGLEVEL'}>1; } else{ &_log( 000, 'generic-fallback', "$field:".$sectionMeta->{fields}->{$field}->{fallback}) if $ENV{'OCS_OPT_LOGLEVEL'}>1; $bind_value = ''; } } # We have to substitute the value with the ID matching "type_section_field.name" if the field is tagged "type". # It allows to support different DB structures if( defined $sectionMeta->{fields}->{$field}->{type} ){ $bind_value = _get_type_id($sectionMeta->{name}, $field, $bind_value); } if($ENV{'OCS_OPT_UNICODE_SUPPORT'}) { my $utf8 = $bind_value; utf8::decode($utf8); push @$arrayToFeed, $utf8; } else { push @$arrayToFeed, $bind_value; } } } sub _snmp_has_changed{ my ($refXml,$XmlSection,$section,$snmpContext) = @_; # Don't use inventory diff if section mask is return 1 if $DATA_MAP{$section}->{mask}==0; my $md5_hash = md5_base64(XML::Simple::XMLout($refXml)); # Check laststate for this section from previous snmp inventory my $laststate = $snmpContext->{'LASTSTATE'}->{$XmlSection}; if ( $laststate ne $md5_hash ) { return(1); #section has changed } return 0; } sub _get_snmp_parser_ForceArray{ my $arrayRef = shift ; for my $section (keys(%DATA_MAP)){ if (defined($DATA_MAP{$section}->{capacities}) && ($DATA_MAP{$section}->{capacities} =~ /^snmp$/)) { # Feed the multilines section array in order to parse xml correctly if ($DATA_MAP{$section}->{multi}) { #We delete the snmp_ pattern to be in concordance with XML $section =~ s/snmp_//g; push @$arrayRef, uc $section; } } } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Snmp/Inventory.pm000066400000000000000000000172041376436473200300210ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Capacities::Snmp::Inventory; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _snmp_inventory /; use Digest::MD5 qw(md5_base64); use Apache::Ocsinventory::Server::System qw / :server /; use Apache::Ocsinventory::Server::Capacities::Snmp::Data; sub _snmp_context { my $snmpDeviceId = shift; my $request; my $snmpDatabaseId; my $snmpContext = {}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; # Retrieve Device ID if exists $request = $dbh->prepare('SELECT ID FROM snmp WHERE SNMPDEVICEID=?' ); #TODO:retrieve the unless here like standard Inventory.pm $request->execute($snmpDeviceId); if($request->rows){ my $row = $request->fetchrow_hashref; $snmpContext->{DATABASE_ID} = $row->{'ID'}; $snmpContext->{EXIST_FL} = 1; } else { #We add the new device in snmp table $dbh->do('INSERT INTO snmp(SNMPDEVICEID) VALUES(?)', {}, $snmpDeviceId); $request = $dbh->prepare('SELECT ID FROM snmp WHERE SNMPDEVICEID=?'); unless($request->execute($snmpDeviceId)){ &_log(518,'snmp','id_error') if $ENV{'OCS_OPT_LOGLEVEL'}; return(1); } my $row = $request->fetchrow_hashref; $snmpContext->{DATABASE_ID} = $row->{'ID'}; #We add the device in snmp_accountinfo ans snmp_laststate tables; $dbh->do('INSERT INTO snmp_accountinfo(SNMP_ID) VALUES(?)', {}, $row->{'ID'}); $dbh->do('INSERT INTO snmp_laststate(SNMP_ID) VALUES(?)', {}, $row->{'ID'}); $dbh->commit; } if($ENV{'OCS_OPT_SNMP_INVENTORY_DIFF'}){ #Getting laststate data for this device $request = $dbh->prepare('SELECT * FROM snmp_laststate WHERE SNMP_ID=?' ); unless ($request->execute($snmpContext->{DATABASE_ID})) { &_log(519,'snmp','laststate_error') if $ENV{'OCS_OPT_LOGLEVEL'}; return(1); } if($request->rows) { my $row = $request->fetchrow_hashref; $snmpContext->{LASTSTATE}=$row; } } return($snmpContext); } sub _snmp_inventory{ my ( $sectionsMeta, $sectionsList, $agentDatabaseId ) = @_; my ($section,$XmlSection); my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $snmp_devices = $result->{CONTENT}; #Getting data for the several snmp devices that we have in the xml while (my ($key, $value) = each (%{$snmp_devices})) { if(ref $value eq 'ARRAY') { while (my ($keybis, $valuebis) = each (@{$value})) { insert_snmp_inventory($key, $valuebis); } } else { insert_snmp_inventory($key, $value); } } } sub insert_snmp_inventory{ my ($key, $value) = @_; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my @columns; my @bind_num; my @arguments; my @update; my $i = 1; foreach my $snmp_infos (keys %{$value}) { push @columns, $snmp_infos; push @bind_num, '?'; push @arguments, $value->{$snmp_infos}; push @update, $snmp_infos." = ?"; } my $column = join ',', @columns; my $args_prepare = join ',', @bind_num; my $update_prepare = join ',', @update; my $query = $dbh->prepare("INSERT INTO $key($column) VALUES($args_prepare) ON DUPLICATE KEY UPDATE $update_prepare"); foreach my $values (@arguments) { $query->bind_param($i, $values); $i++; } foreach my $values (@arguments) { $query->bind_param($i, $values); $i++; } $query->execute; } sub _update_snmp_inventory_section{ my ($snmpDeviceXml, $snmpContext, $section, $XmlSection, $sectionMeta) = @_; my $snmpDatabaseId = $snmpContext->{DATABASE_ID}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my @bind_values; my $refXml = $snmpDeviceXml->{$XmlSection}; # We continue only if data for this section return 0 unless ($refXml); #TODO: prevent a bug if one (or more) of the snmp tables has no SNMP_ID field) #We delete related data for this device if already exists if ($snmpContext->{EXIST_FL}) { if($ENV{'OCS_OPT_SNMP_INVENTORY_DIFF'}){ if( _snmp_has_changed($refXml,$XmlSection,$section,$snmpContext) ){ &_log( 113, 'snmp', "u:$XmlSection") if $ENV{'OCS_OPT_LOGLEVEL'}; $sectionMeta->{hasChanged} = 1; } else { return 0; #We don't update this section } } else { $sectionMeta->{hasChanged} = 1; } if( $sectionMeta->{delOnReplace}) { if(!$dbh->do("DELETE FROM $section WHERE SNMP_ID=?", {}, $snmpDatabaseId)){ return(1); } } } # Processing values my $sth = $dbh->prepare( $sectionMeta->{sql_insert_string} ); # Multi lines (forceArray) if($sectionMeta->{multi}){ for my $line (@$refXml){ &_get_snmp_bind_values($line, $sectionMeta, \@bind_values); if(!$sth->execute($snmpDatabaseId, @bind_values)){ return(1); } @bind_values = (); } } # One line (hash) else{ &_get_snmp_bind_values($refXml, $sectionMeta, \@bind_values); if( !$sth->execute($snmpDatabaseId, @bind_values) ){ return(1); } } #Getting laststate for this section my $md5_hash = md5_base64(XML::Simple::XMLout($refXml)); push @{$snmpContext->{'LASTSTATE_UPDATE_VALUES'}} , "$XmlSection='$md5_hash'"; #We compute checksum for this section $snmpDeviceXml->{'COMMON'}->{'CHECKSUM'} |= $sectionMeta->{mask}; $dbh->commit; 0; } sub _snmp_common{ my $base= shift; my $snmpDatabaseId = shift; my $agentDatabaseId = shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; #Store the COMMON data from XML $dbh->do("UPDATE snmp SET IPADDR=".$dbh->quote($base->{IPADDR}).", LASTDATE=NOW(), CHECKSUM=(".$base->{CHECKSUM}."|CHECKSUM|1), MACADDR=".$dbh->quote($base->{MACADDR}).", SNMPDEVICEID=".$dbh->quote($base->{SNMPDEVICEID}).", NAME=".$dbh->quote($base->{NAME}).", DESCRIPTION=".$dbh->quote($base->{DESCRIPTION}).", CONTACT=".$dbh->quote($base->{CONTACT}).", LOCATION=".$dbh->quote($base->{LOCATION}).", UPTIME=".$dbh->quote($base->{UPTIME}).", DOMAIN=".$dbh->quote($base->{DOMAIN}).", TYPE=".$dbh->quote($base->{TYPE})." WHERE ID = $snmpDatabaseId") or return(1); $dbh->commit; #We get and store the TAG of the computer doing SNMP inventory my $request = $dbh->prepare('SELECT TAG FROM accountinfo WHERE HARDWARE_ID=?'); unless($request->execute($agentDatabaseId)){ &_log(519,'snmp','computer tag error') if $ENV{'OCS_OPT_LOGLEVEL'}; return(1); } my $row = $request->fetchrow_hashref; if (defined $row->{'TAG'}) { $dbh->do("UPDATE snmp_accountinfo SET TAG=".$dbh->quote($row->{'TAG'})." WHERE SNMP_ID=$snmpDatabaseId"); $dbh->commit; } 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Capacities/Update.pm000066400000000000000000000126621376436473200263340ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Capacities::Update; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw //; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'UPDATE', 'HANDLER_PROLOG_READ' => undef, 'HANDLER_PROLOG_RESP' => undef, 'HANDLER_PRE_INVENTORY' => undef, 'HANDLER_POST_INVENTORY' => undef, 'REQUEST_NAME' => 'UPDATE', 'HANDLER_REQUEST' => \&_update_handler, 'HANDLER_DUPLICATE' => undef, 'TYPE' => undef, 'XML_PARSER_OPT' => { 'ForceArray' => [] } }; # Default $Apache::Ocsinventory::{OPTIONS}{'OCS_OPT_UPDATE'} = 0; # To manage the update request sub _update_handler{ my $current_context = shift; my $dbh = $current_context->{'DBI_HANDLE'}; my $query = $current_context->{'XML_ENTRY'}; my %resp; my @agent; my @dmi; my @ipdiscover; my $Acurrent; my $Dcurrent; my $Icurrent; my $Iversion; my $agent; my $dmi; my $ip; my $platform; my $Dversion; my $Aversion; my $request; my $row; #Looking for option status unless($ENV{'OCS_OPT_UPDATE'}){ &_send_response({'RESPONSE',['NO_UPDATE']}); return APACHE_OK; } # OS type $platform = $query->{PLATFORM}; # Version of the agent $Aversion = $query->{AGENT}; # Eventually, the DMI version if(defined($query->{DMI})){$Dversion = $query->{DMI}}; if(defined($query->{IPDISCOVER})){$Iversion = $query->{IPDISCOVER}}; if(!defined($Aversion) || !($platform=~/^WINDOWS$|^MAC$|^LINUX$/)){ &_log(508,'update','') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_BAD_REQUEST; } # What are the available versions in the database $request = $dbh->prepare('SELECT * FROM files WHERE OS=?'); $request->execute($platform); # If no file available, tell to the client not to update unless($request->rows){ &_send_response({ 'RESPONSE' => ['NO_UPDATE'] }); $request->finish; return APACHE_OK; }else{ # Files are available, does the client have to download and install it ? # Get versions number while($row=$request->fetchrow_hashref()){ # Version of the agent in the database if($row->{'NAME'}=~/agent/i){ push @agent, $row->{'VERSION'}; } # Maybe a dmi reader version(on a linux computer) if(defined($Dversion)){ # Version of the dmi in the database if($row->{'NAME'}=~/dmi/i){ push @dmi, $row->{'VERSION'}; } } if(defined($Iversion)){ # Version of ipdiscover in the database if($row->{'NAME'}=~/ipdiscover/i){ push @ipdiscover, $row->{'VERSION'}; } } } # Determine the upper agent version available if(@agent){ # Looking for the latest version $Acurrent = 0; for(@agent){ if($_>$Acurrent){$Acurrent = $_;} } # Compare to the client version. If different, we tell you to update $agent = ($Aversion==$Acurrent)?0:1; }else{ $agent = 0; } # DMI $Dcurrent = 0; if(defined($Dversion) and @dmi){ for(@dmi){ if($_>$Dcurrent){$Dcurrent = $_;} } # Compare to the client version. If different, we tell you to update $dmi = ($Dversion==$Dcurrent)?0:1; } # IPDISCOVER if(defined($Iversion) and @ipdiscover){ for(@ipdiscover){ if($_>$Icurrent){$Icurrent = $_;} } # Compare to the client version. If different, we tell you to update $ip = ($Iversion==$Icurrent)?0:1; } } $request->finish; # Generate the response unless(($agent) or ($dmi) or $ip){ &_send_response({'RESPONSE',['NO_UPDATE']}); return APACHE_OK; } $resp{'RESPONSE'} = ['UPDATE']; if( $agent ){ $resp{'AGENT'} = [ $Acurrent ] } if( $dmi ){ $resp{'DMI'} = [ $Dcurrent ] } if( $ip ){ $resp{'IPDISCOVER'} = [ $Icurrent ] } # Send it &_send_response(\%resp); return APACHE_OK; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Communication.pm000066400000000000000000000213351376436473200256470ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Communication; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _send_response _prolog /; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::System(qw/ :server _modules_get_prolog_readers _modules_get_prolog_writers /); use Apache::Ocsinventory::Server::Communication::Session; # Subroutine which answer to client prolog sub _prolog{ my $frequency; my $quality; my $now; my $lastdate; my $request; my $row; my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $info = $Apache::Ocsinventory::CURRENT_CONTEXT{'DETAILS'}; my $read = &_prolog_read(); if( $read == PROLOG_STOP ){ &_log(106,'prolog','stopped by module') if $ENV{'OCS_OPT_LOGLEVEL'}; &_prolog_resp(PROLOG_RESP_BREAK); return APACHE_OK; } elsif( $read == BAD_USERAGENT ) { #If we detect a wrong useragent &_log(106,'prolog','stopped by module') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_BAD_REQUEST; } $frequency = $ENV{'OCS_OPT_FREQUENCY'}; # If we do not have the default frequency unless(defined($frequency)){ &_prolog_resp(PROLOG_RESP_STOP); &_log(503,'prolog','no_frequency') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_OK; } # We have this computer in the database if($Apache::Ocsinventory::CURRENT_CONTEXT{'EXIST_FL'}){ # Get the current timestamp $now = time(); # Compute quality if($info->{'FIDELITY'} > 1){ $quality = ((($now-$info->{'LCOME'})/86400) + ($info->{'QUALITY'}*$info->{'FIDELITY'}))/(($info->{'FIDELITY'})+1); }else{ # We increment the number of visits $quality = (($now-$info->{'LCOME'})/86400); } # We update device data if(!$dbh->do('UPDATE hardware SET FIDELITY=FIDELITY+1,QUALITY=?,LASTCOME=NOW(),USERAGENT=? WHERE DEVICEID=?', {}, $quality, $Apache::Ocsinventory::CURRENT_CONTEXT{'USER_AGENT'}, $DeviceID)){ return APACHE_SERVER_ERROR; } ########## # If special value 0, we always accept if($frequency==0){ &_prolog_resp(PROLOG_RESP_SEND); return APACHE_OK; # If -1, we always reject }elsif($frequency==(-1)){ &_prolog_resp(PROLOG_RESP_BREAK); return APACHE_OK; } # Saving lastdate $lastdate = $info->{'LDATE'}; # Maybe there are computer's special frequency $request=$dbh->prepare('SELECT IVALUE FROM devices WHERE HARDWARE_ID IN ('.($Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}.(@{$Apache::Ocsinventory::CURRENT_CONTEXT{'MEMBER_OF'}}?',':''). join(',',@{$Apache::Ocsinventory::CURRENT_CONTEXT{'MEMBER_OF'}})).') AND NAME="FREQUENCY" ORDER BY IVALUE DESC'); $request->execute(); while($row=$request->fetchrow_hashref()){ $frequency=$row->{'IVALUE'}; } $request->finish; # If special values... if($frequency==0){ &_prolog_resp(PROLOG_RESP_SEND); return APACHE_OK; }elsif($frequency==(-1)){ &_prolog_resp(PROLOG_RESP_BREAK); return APACHE_OK; } unless ($lastdate){ &_prolog_resp(PROLOG_RESP_SEND); return APACHE_OK; } # Have we override the period ? if((($lastdate-$now)+$frequency*86400)<0){ &_prolog_resp(PROLOG_RESP_SEND); return APACHE_OK; }else{ &_prolog_resp(PROLOG_RESP_STOP); return APACHE_OK; } }else{#This is a new Device ID if($frequency==(-1)){ &_prolog_resp(PROLOG_RESP_BREAK); return APACHE_OK; }else{ &_log(103,'prolog','new_deviceid') if $ENV{'OCS_OPT_LOGLEVEL'}; &_prolog_resp(PROLOG_RESP_SEND); return APACHE_OK; } } } sub _send_response{ my $response = shift; my( $xml, $message, $d, $status, $inflated ); my $r = $Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}; # Generate the response # Generation of xml message $message = XML::Simple::XMLout( $response, RootName => 'REPLY', XMLDecl => "", NoSort => 1, SuppressEmpty => undef); # send unless($inflated = &{$Apache::Ocsinventory::CURRENT_CONTEXT{'DEFLATE_SUB'}}( $message )){ &_log(506,'send_response','compress_stage') if $ENV{'OCS_OPT_LOGLEVEL'}; #TODO: clean exit } &_set_http_header('content-length', length($inflated),$r); &_set_http_header('Cache-control', 'no-cache',$r); &_set_http_content_type('application/x-compressed',$r); &_send_http_headers($r); $r->print($inflated); return 0; } sub _prolog_resp{ my $decision = shift; my %resp; &_prolog_build_resp($decision, \%resp); if($resp{'RESPONSE'}[0] eq 'STOP'){ &_log(102,'prolog','declined') if $ENV{'OCS_OPT_LOGLEVEL'}; }elsif($resp{'RESPONSE'}[0] eq 'SEND'){ &_log(100,'prolog','accepted') if $ENV{'OCS_OPT_LOGLEVEL'}; &start_session( \%Apache::Ocsinventory::CURRENT_CONTEXT ); }elsif($resp{'RESPONSE'}[0] eq 'OTHER'){ &_log(105,'prolog','') if $ENV{'OCS_OPT_LOGLEVEL'}; } &_send_response(\%resp); return 0; } sub _prolog_build_resp{ my ($decision, $resp) = @_; my $module; my $state; #Agent execution periodicity if(defined($Apache::Ocsinventory::CURRENT_CONTEXT{'PARAMS'}{'PROLOG_FREQ'}->{'IVALUE'})){ $resp->{'PROLOG_FREQ'} = [$Apache::Ocsinventory::CURRENT_CONTEXT{'PARAMS'}{'PROLOG_FREQ'}->{'IVALUE'}]; } else{ my ($groupFreq, $groupsParams); if($ENV{'OCS_OPT_ENABLE_GROUPS'}){ $groupsParams = $Apache::Ocsinventory::CURRENT_CONTEXT{'PARAMS_G'}; for(keys(%$groupsParams)){ $groupFreq = $$groupsParams{$_}->{'PROLOG_FREQ'}->{'IVALUE'} if (exists($$groupsParams{$_}->{'PROLOG_FREQ'}->{'IVALUE'}) and $$groupsParams{$_}->{'PROLOG_FREQ'}->{'IVALUE'}<$groupFreq) or !$groupFreq; } } $resp->{'PROLOG_FREQ'} = [ $groupFreq || $ENV{'OCS_OPT_PROLOG_FREQ'} ]; } #Agent inventory on startup feature if(defined($Apache::Ocsinventory::CURRENT_CONTEXT{'PARAMS'}{'INVENTORY_ON_STARTUP'}->{'IVALUE'})){ $resp->{'INVENTORY_ON_STARTUP'} = [$Apache::Ocsinventory::CURRENT_CONTEXT{'PARAMS'}{'INVENTORY_ON_STARTUP'}->{'IVALUE'}]; }else{ my ($groupFreq, $groupsParams); if($ENV{'OCS_OPT_ENABLE_GROUPS'}){ $groupsParams = $Apache::Ocsinventory::CURRENT_CONTEXT{'PARAMS_G'}; for(keys(%$groupsParams)){ $groupFreq = $$groupsParams{$_}->{'INVENTORY_ON_STARTUP'}->{'IVALUE'} if (exists($$groupsParams{$_}->{'INVENTORY_ON_STARTUP'}->{'IVALUE'}) and $$groupsParams{$_}->{'INVENTORY_ON_STARTUP'}->{'IVALUE'}<$groupFreq) or !$groupFreq; } } $resp->{'INVENTORY_ON_STARTUP'} = [ $groupFreq || $ENV{'OCS_OPT_INVENTORY_ON_STARTUP'} ]; } if($decision == PROLOG_RESP_BREAK){ $resp->{'RESPONSE'} = [ 'STOP' ]; return 0; }elsif($decision == PROLOG_RESP_STOP){ $resp->{'RESPONSE'} = [ 'STOP' ]; }elsif($decision == PROLOG_RESP_SEND){ $resp->{'RESPONSE'} = [ 'SEND' ]; } for(&_modules_get_prolog_writers()){ last if $_ == 0; &$_(\%Apache::Ocsinventory::CURRENT_CONTEXT, $resp); } return 0; } sub _prolog_read{ for(&_modules_get_prolog_readers()){ last if $_==0; my $resp=&$_(\%Apache::Ocsinventory::CURRENT_CONTEXT); if($resp==PROLOG_STOP){ return PROLOG_STOP; } if($resp==BAD_USERAGENT){ return BAD_USERAGENT; } } return PROLOG_CONTINUE; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Communication/000077500000000000000000000000001376436473200253055ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Communication/Session.pm000066400000000000000000000107341376436473200272730ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Communication::Session; use strict; use Apache::Ocsinventory::Server::System(qw/ :server /); require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / start_session check_session kill_session /; sub start_session{ my $current_context = shift; my $dbh = $current_context->{DBI_HANDLE}; my $deviceId = $current_context->{DEVICEID}; clean_sessions( $current_context ); # Trying to start session if( !$dbh->do( 'INSERT INTO prolog_conntrack(DEVICEID,PID,TIMESTAMP) VALUES(?,?,UNIX_TIMESTAMP())', {}, $deviceId, $$) ){ &_log(525,'session', 'failed') if $ENV{'OCS_OPT_LOGLEVEL'}; return 0; } &_log(311,'session', 'started') if $ENV{'OCS_OPT_LOGLEVEL'}; return 1; } sub clean_sessions{ my $current_context = shift; my $dbh = $current_context->{DBI_HANDLE}; # To avoid race conditions if( !$dbh->do("INSERT INTO engine_mutex(NAME, PID, TAG) VALUES('SESSION',?,'CLEAN')", {}, $$) ){ &_log(315,'session',"already handled") if $ENV{'OCS_OPT_LOGLEVEL'}; return; } # We have to make it every SESSION_CLEAN_TIME seconds my $check_clean = $dbh->prepare('SELECT UNIX_TIMESTAMP()-IVALUE AS IVALUE FROM engine_persistent WHERE NAME="SESSION_CLEAN_DATE"'); if($check_clean->execute() && $check_clean->rows()){ my $row = $check_clean->fetchrow_hashref(); if($row->{IVALUE}< $ENV{OCS_OPT_SESSION_CLEAN_TIME} ){ $dbh->do('DELETE FROM engine_mutex WHERE PID=? AND NAME="SESSION" AND TAG="CLEAN"', {}, $$ ); return; } } &_log(314,'session', "clean(check)") if $ENV{'OCS_OPT_LOGLEVEL'}; # Delete old sessions $dbh->do('INSERT INTO engine_persistent(NAME,IVALUE) VALUES("SESSION_CLEAN_DATE", UNIX_TIMESTAMP())') if($dbh->do('UPDATE engine_persistent SET IVALUE=UNIX_TIMESTAMP() WHERE NAME="SESSION_CLEAN_DATE"')==0E0); my $cleaned = $dbh->do('DELETE FROM prolog_conntrack WHERE UNIX_TIMESTAMP()-TIMESTAMP>?', {}, $ENV{OCS_OPT_SESSION_CLEAN_TIME} ); $dbh->do('DELETE FROM engine_mutex WHERE PID=? AND NAME="SESSION" AND TAG="CLEAN"', {}, $$ ); &_log(316,'session', "clean($cleaned)") if $cleaned && ($cleaned!=0E0) && $ENV{'OCS_OPT_LOGLEVEL'}; } sub check_session { my $current_context = shift; my $dbh = $current_context->{DBI_HANDLE}; my $deviceId = $current_context->{DEVICEID}; unless( $ENV{OCS_OPT_SESSION_VALIDITY_TIME} ){ &_log(317,'session', 'always_true') if $ENV{'OCS_OPT_LOGLEVEL'}; return 1; } my $check = $dbh->do('SELECT DEVICEID FROM prolog_conntrack WHERE DEVICEID=? AND (UNIX_TIMESTAMP()-TIMESTAMP{DBI_HANDLE}; my $deviceId = $current_context->{DEVICEID}; my $code = $dbh->do('DELETE FROM prolog_conntrack WHERE DEVICEID=?', {}, $deviceId); if(!$code){ &_log(527,'session', 'error') if $ENV{'OCS_OPT_LOGLEVEL'}; return 0; } elsif( $code != 0E0 ){ &_log(320,'session', 'end') if $ENV{'OCS_OPT_LOGLEVEL'}; return 1; } else{ return 0; } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Constants.pm000066400000000000000000000046771376436473200250300ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Constants; use strict; use Apache::Ocsinventory::Map; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw/ PROLOG_RESP_BREAK PROLOG_RESP_STOP PROLOG_RESP_SEND OPTION_TYPE_SYNC OPTION_TYPE_ASYNC LOGPATH CHECKSUM_MAX_VALUE DUP_HOSTNAME_FL DUP_SERIAL_FL DUP_MACADDR_FL DUP_SMODEL_FL DUP_UUID_FL DUP_ASSETTAG_FL PROLOG_STOP PROLOG_CONTINUE INVENTORY_STOP INVENTORY_CONTINUE BAD_USERAGENT /; use constant PROLOG_RESP_BREAK => 0; use constant PROLOG_RESP_STOP => 1; use constant PROLOG_RESP_SEND => 2; use constant OPTION_TYPE_SYNC => 0; use constant OPTION_TYPE_ASYNC => 1; my $checksum_max_value = &get_checksum(); use constant CHECKSUM_MAX_VALUE => $checksum_max_value; # To enable user to set how auto-duplicates works use constant DUP_HOSTNAME_FL => 1 ; use constant DUP_SERIAL_FL => 2 ; use constant DUP_MACADDR_FL => 4 ; use constant DUP_SMODEL_FL => 8 ; use constant DUP_UUID_FL => 16 ; use constant DUP_ASSETTAG_FL => 32 ; use constant PROLOG_STOP => 1; use constant BAD_USERAGENT => 2; use constant PROLOG_CONTINUE => 0; use constant INVENTORY_STOP => 1; use constant INVENTORY_CONTINUE => 0; sub get_checksum { my $checksum; for my $section (keys %DATA_MAP){ $checksum|=$DATA_MAP{$section}->{mask}; } return $checksum; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Duplicate.pm000066400000000000000000000256601376436473200247610ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Duplicate; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _duplicate_main /; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::System qw /:server _modules_get_duplicate_handlers/; use Apache::Ocsinventory::Map; # Subroutine called at the end of database inventory insertions sub _duplicate_main{ my %exist; my $red; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; # workaround agent old_deviceid bug if(!$result->{CONTENT}->{OLD_DEVICEID} and $result->{CONTENT}->{DOWNLOAD}->{HISTORY}->{OLD_DEVICEID}) { $result->{CONTENT}->{OLD_DEVICEID} = $result->{CONTENT}->{DOWNLOAD}->{HISTORY}->{OLD_DEVICEID}; } # If the duplicate is specified if($result->{CONTENT}->{OLD_DEVICEID} and $result->{CONTENT}->{OLD_DEVICEID} ne $Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'}){ &_log(326,'duplicate',$result->{CONTENT}->{OLD_DEVICEID}) if $ENV{'OCS_OPT_LOGLEVEL'}; # Looking for database id of old deviceid my $request = $dbh->prepare('SELECT ID FROM hardware WHERE DEVICEID=?'); $request->execute($result->{CONTENT}->{OLD_DEVICEID}); if(my $row = $request->fetchrow_hashref){ if(&_duplicate_replace($row->{'ID'})){ # If there is an invalid old deviceid &_log(513,'duplicate','old deviceid') if $ENV{'OCS_OPT_LOGLEVEL'}; $dbh->rollback; }else{ $dbh->commit; $red = 1; } } } # Handle duplicates if $ENV{'OCS_OPT_AUTO_DUPLICATE_LVL'} is set if($ENV{'OCS_OPT_AUTO_DUPLICATE_LVL'}){ # Trying to find some duplicate evidences &_duplicate_detect(\%exist); # For each result, we are trying to know if it is a true duplicate (according to AUTO_DUPLICATE_LVL for(sort keys(%exist)){ if(&_duplicate_evaluate(\%exist, $_)){ if(&_duplicate_replace($_)){ &_log(517,'duplicate','replacing_error') if $ENV{'OCS_OPT_LOGLEVEL'}; $dbh->rollback; }else{ $dbh->commit; $red = 1; } } } } return $red; } sub _already_in_array { my $lookfor = shift; my $ref = shift; foreach (@$ref){ return 1 if($lookfor eq $_); } return 0; } sub _duplicate_evaluate{ my $exist = shift; my $key = shift; # Check duplicate , according to AUTO_DUPLICATE_LVL $exist->{$key}->{'MASK'} = 0; $exist->{$key}->{'MASK'}|=DUP_HOSTNAME_FL if $exist->{$key}->{'HOSTNAME'}; $exist->{$key}->{'MASK'}|=DUP_SERIAL_FL if $exist->{$key}->{'SSN'}; $exist->{$key}->{'MASK'}|=DUP_MACADDR_FL if $exist->{$key}->{'MACADDRESS'}; $exist->{$key}->{'MASK'}|=DUP_SMODEL_FL if $exist->{$key}->{'SMODEL'}; $exist->{$key}->{'MASK'}|=DUP_UUID_FL if $exist->{$key}->{'UUID'}; $exist->{$key}->{'MASK'}|=DUP_ASSETTAG_FL if $exist->{$key}->{'ASSETTAG'}; if((($ENV{'OCS_OPT_AUTO_DUPLICATE_LVL'} & $exist->{$key}->{'MASK'})) == $ENV{'OCS_OPT_AUTO_DUPLICATE_LVL'}){ return(1); }else{ return(0); } } sub _duplicate_detect{ my $exist = shift; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; my $request; my $row; my(@bad_serial, @bad_mac); # Retrieve generic mac addresses $request = $dbh->prepare('SELECT MACADDRESS FROM blacklist_macaddresses'); $request->execute(); push @bad_mac, $row->{MACADDRESS} while($row = $request->fetchrow_hashref()); # Retrieve generic serials $request = $dbh->prepare('SELECT SERIAL FROM blacklist_serials'); $request->execute(); push @bad_serial, $row->{SERIAL} while($row = $request->fetchrow_hashref()); # Do we already have the hostname $request = $dbh->prepare('SELECT ID, NAME FROM hardware WHERE NAME=? AND ID<>? ORDER BY ID'); $request->execute($result->{CONTENT}->{HARDWARE}->{NAME}, $DeviceID); while($row = $request->fetchrow_hashref()){ if(!($row->{'NAME'} eq '')){ $exist->{$row->{'ID'}}->{'HOSTNAME'}=1; } } # Do we already have the assettag ? $request = $dbh->prepare('SELECT HARDWARE_ID, ASSETTAG FROM bios WHERE ASSETTAG=? AND HARDWARE_ID<>? ORDER BY HARDWARE_ID'); $request->execute($result->{CONTENT}->{BIOS}->{ASSETTAG}, $DeviceID); while($row = $request->fetchrow_hashref()){ if(!($row->{'ASSETTAG'} eq '')){ $exist->{$row->{'ID'}}->{'ASSETTAG'}=1; } } # Do we already have the uuid ? $request = $dbh->prepare('SELECT ID, UUID FROM hardware WHERE UUID=? AND ID<>? ORDER BY ID'); $request->execute($result->{CONTENT}->{HARDWARE}->{UUID}, $DeviceID); while($row = $request->fetchrow_hashref()){ if(!($row->{'UUID'} eq '')){ $exist->{$row->{'ID'}}->{'UUID'}=1; } } # ...and one MAC of this machine for(@{$result->{CONTENT}->{NETWORKS}}){ $request = $dbh->prepare('SELECT HARDWARE_ID,DESCRIPTION,MACADDR FROM networks WHERE MACADDR=? AND HARDWARE_ID<>?'); $request->execute($_->{MACADDR}, $DeviceID); while($row = $request->fetchrow_hashref()){ if(!&_already_in_array($row->{'MACADDR'}, \@bad_mac)){ $exist->{$row->{'HARDWARE_ID'}}->{'MACADDRESS'}++; } } } # ...or its serial if($result->{CONTENT}->{BIOS}->{SSN}){ $request = $dbh->prepare('SELECT HARDWARE_ID, SSN FROM bios WHERE SSN=? AND HARDWARE_ID<>?'); $request->execute($result->{CONTENT}->{BIOS}->{SSN}, $DeviceID); while($row = $request->fetchrow_hashref()){ if(!&_already_in_array($row->{'SSN'}, \@bad_serial)){ $exist->{$row->{'HARDWARE_ID'}}->{'SSN'}=1; } } } # ...or its serial model if($result->{CONTENT}->{BIOS}->{SMODEL}){ $request = $dbh->prepare('SELECT HARDWARE_ID, SMODEL FROM bios WHERE SMODEL=? AND HARDWARE_ID<>?'); $request->execute($result->{CONTENT}->{BIOS}->{SMODEL}, $DeviceID); while($row = $request->fetchrow_hashref()){ $exist->{$row->{'HARDWARE_ID'}}->{'SMODEL'}=1; } } $request->finish; } sub _duplicate_replace{ my $device = shift; #Locks the device if( &_lock($device) ){ &_log( 516, 'duplicate', 'device locked'); return 1; } my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; # We keep the old quality and fidelity my $request=$dbh->prepare('SELECT QUALITY,FIDELITY,CHECKSUM,USERID FROM hardware WHERE ID=?'); $request->execute($device); # If it does not exist unless($request->rows){ &_unlock($device); return(1); } my $row = $request->fetchrow_hashref; my $quality = $row->{'QUALITY'}?$row->{'QUALITY'}:0; my $fidelity = $row->{'FIDELITY'}; my $checksum = $row->{'CHECKSUM'}; my $userid = $row->{'USERID'}; $request->finish; # Current userid or previous one ? if( $result->{CONTENT}->{HARDWARE}->{USERID}!~/system|localsystem/i ){ $userid = $result->{CONTENT}->{HARDWARE}->{USERID}; } # TODO: catch the queries return code # Keeping few informations from hardware $dbh->do(" UPDATE hardware SET QUALITY=".$dbh->quote($quality).", FIDELITY=".$dbh->quote($fidelity).", CHECKSUM=(".(defined($checksum)?$checksum:CHECKSUM_MAX_VALUE)."|".(defined($result->{CONTENT}->{HARDWARE}->{CHECKSUM})?$result->{CONTENT}->{HARDWARE}->{CHECKSUM}:CHECKSUM_MAX_VALUE)."), USERID=".$dbh->quote($userid)." WHERE ID=".$DeviceID ) ; $dbh->do("DELETE FROM hardware WHERE ID=?", {}, $device) ; # We keep the informations of the following tables: devices, accountinfo, itmgmt_comments $dbh->do('DELETE FROM accountinfo WHERE HARDWARE_ID=?', {}, $DeviceID) ; $dbh->do('UPDATE accountinfo SET HARDWARE_ID=? WHERE HARDWARE_ID=?', {}, $DeviceID, $device) ; $dbh->do('DELETE FROM devices WHERE HARDWARE_ID=?', {}, $DeviceID) ; $dbh->do('UPDATE devices SET HARDWARE_ID=? WHERE HARDWARE_ID=?', {}, $DeviceID, $device) ; $dbh->do('UPDATE itmgmt_comments SET HARDWARE_ID=? WHERE HARDWARE_ID=?', {}, $DeviceID, $device) ; # We keep the static inclusions/exclusions (STATIC=1|2) $dbh->do('UPDATE groups_cache SET HARDWARE_ID=? WHERE HARDWARE_ID=? AND (STATIC=1 OR STATIC=2)', {}, $DeviceID, $device) ; # The computer may not correspond to the previous dynamic groups, as its inventory could potentially change $dbh->do('DELETE FROM groups_cache WHERE HARDWARE_ID=?', {}, $device) ; # Drop old computer from "auto" tables in Map # TODO: is it possible to manage the not auto section => not auto for import but auto for deletion ? for (keys(%DATA_MAP)){ next if !$DATA_MAP{$_}->{delOnReplace} || !$DATA_MAP{$_}->{auto} || $DATA_MAP{$_}->{capacities}; unless($dbh->do("DELETE FROM $_ WHERE HARDWARE_ID=?", {}, $device)){ &_unlock($device); return(1); } } # Trace duplicate if needed if($ENV{'OCS_OPT_TRACE_DELETED'}){ unless( $dbh->do('INSERT INTO deleted_equiv(DATE,DELETED,EQUIVALENT) VALUES(NULL,?,?)', {} , $device,$DeviceID)){ &_unlock($device); return(1); } } # To enable option managing duplicates for(&_modules_get_duplicate_handlers()){ last if $_==0; # Returning 1 will abort replacement unless(&$_(\%Apache::Ocsinventory::CURRENT_CONTEXT, $device)){ &_unlock($device); return(1); } } &_log(300,'duplicate',"$device => $DeviceID") if $ENV{'OCS_OPT_LOGLEVEL'}; #Remove lock &_unlock($device); 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Groups.pm000066400000000000000000000173011376436473200243170ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Groups; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } use Apache::Ocsinventory::Server::System(qw/ :server /); require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _get_groups / ; sub _get_groups{ my($request, @groups); # We ensure that cache is not out-of-date &_validate_groups_cache(); # Sending the groups the computer is part of $request = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}->prepare('SELECT GROUP_ID FROM groups_cache WHERE HARDWARE_ID=? AND (STATIC=0 OR STATIC=1)'); $request->execute( $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'} ); while( my $row = $request->fetchrow_hashref){ push @groups, $row->{'GROUP_ID'}; } return @groups; } sub _validate_groups_cache{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; return unless $ENV{'OCS_OPT_GROUPS_CACHE_REVALIDATE'}; # Test cache validity my $request = $dbh->prepare(' SELECT g.HARDWARE_ID FROM `groups` g LEFT OUTER JOIN locks l ON l.HARDWARE_ID=g.HARDWARE_ID WHERE UNIX_TIMESTAMP()-REVALIDATE_FROM > ? AND l.HARDWARE_ID IS NULL' ); # Updating cache when needed return unless $request->execute( $ENV{'OCS_OPT_GROUPS_CACHE_REVALIDATE'} ); while(my $row = $request->fetchrow_hashref()){ # We lock it like a computer if( !&_lock($row->{'HARDWARE_ID'}) ){ # Check if the group has already been computed my $check_request = $dbh->prepare('SELECT HARDWARE_ID, (UNIX_TIMESTAMP()-REVALIDATE_FROM) AS OFF FROM `groups` WHERE UNIX_TIMESTAMP()-REVALIDATE_FROM > ? AND HARDWARE_ID=?'); $check_request->execute($ENV{'OCS_OPT_GROUPS_CACHE_REVALIDATE'}, $row->{'HARDWARE_ID'}); if(!$check_request->rows()){ &_unlock($row->{'HARDWARE_ID'}); $check_request->finish(); next; } &_log(306,'groups','cache_out-of-date('.$row->{'HARDWARE_ID'}.')') if $ENV{'OCS_OPT_LOGLEVEL'}; # We build the new cache &_build_group_cache( $row->{'HARDWARE_ID'} ); # Unlock group &_unlock($row->{'HARDWARE_ID'}); } else{ &_log(306,'groups','cache_in_process('.$row->{'HARDWARE_ID'}.')') if $ENV{'OCS_OPT_LOGLEVEL'}; } } } sub _build_group_cache{ my $group_id = shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $dbh_sl = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_SL_HANDLE'}; my $offset = int rand($ENV{OCS_OPT_GROUPS_CACHE_OFFSET}); my (@ids,@quoted_ids); my ($id_field, $error); # Build cache request my $build_cache = $dbh->prepare('INSERT INTO groups_cache(GROUP_ID, HARDWARE_ID, STATIC) VALUES(?,?,0)'); my $delete_cache = 'DELETE FROM groups_cache WHERE GROUP_ID=? AND STATIC=0'; # Retrieving the group request. It must be a SELECT statement on ID(hardware) my $get_request = $dbh->prepare('SELECT REQUEST,XMLDEF FROM `groups` WHERE HARDWARE_ID=?'); $get_request->execute( $group_id ); my $row = $get_request->fetchrow_hashref(); # legacy: one request per group if($row->{'REQUEST'} ne '' and $row->{'REQUEST'} ne 'NULL' ){ my $group_request = $dbh_sl->prepare( $row->{'REQUEST'} ); if($group_request->execute()){ # Deleting the current cache $dbh->do($delete_cache, {}, $group_id); while( my @cache = $group_request->fetchrow_array() ){ push @ids, $cache[0] ; } #We verify that HARDWARE_IDs are not groups &verify_ids($row->{'REQUEST'},\@ids); # Build the cache for( @ids ){ $build_cache->execute($group_id, $_); } } else{ &_log(520,'groups','bad_request('.$row->{'HARDWARE_ID'}.')') if $ENV{'OCS_OPT_LOGLEVEL'}; } } # New behaviour : multiple requests for one group xml encoded elsif( $row->{'XMLDEF'} ne '' and $row->{'XMLDEF'} ne 'NULL' ){ my $xml = XML::Simple::XMLin($row->{'XMLDEF'}, ForceArray => ['REQUEST'] ); for my $request (@{$xml->{REQUEST}}){ if(@ids){ for(@ids){ push @quoted_ids, $dbh_sl->quote($_); } # When request is from hardware, the id is called "ID", if not "HARDWARE_ID" if( $request =~ /^select\s+(distinct\s+)?ID/i ){ $id_field = 'ID'; } else{ $id_field = 'HARDWARE_ID'; } my $string = join ",", @quoted_ids; $request = $request." AND $id_field IN ($string)"; @ids=@quoted_ids=(); } my $group_request = $dbh_sl->prepare( $request ); unless($group_request->execute){ &_log(520,'groups','bad_request('.$row->{'HARDWARE_ID'}.')') if $ENV{'OCS_OPT_LOGLEVEL'}; last; } # If no results for one request, we stop the computing (always AND statements) if(!$group_request->rows){ &_log(307,'groups','empty') if $ENV{'OCS_OPT_LOGLEVEL'}; @ids=@quoted_ids=(); $error = 1; } while( my @cache = $group_request->fetchrow_array() ){ push @ids, $cache[0]; } #We verify that HARDWARE_IDs are not groups $error = &verify_ids($request,\@ids); } # Deleting the current cache $dbh->do($delete_cache, {}, $group_id); unless($error){ # Build the cache for( @ids ){ $build_cache->execute($group_id, $_); } } else{ &_log(520,'groups','will not build('.$row->{'HARDWARE_ID'}.')') if $ENV{'OCS_OPT_LOGLEVEL'}; } } # Updating cache time $dbh->do("UPDATE `groups` SET CREATE_TIME=UNIX_TIMESTAMP(), REVALIDATE_FROM=UNIX_TIMESTAMP()+? WHERE HARDWARE_ID=?", {}, $offset, $group_id); &_log(307,'groups', "revalidate_cache($group_id(".scalar @ids."))") if $ENV{'OCS_OPT_LOGLEVEL'}; } 1; sub verify_ids { my ($request,$ids) = @_; my $error; my $dbh_sl = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_SL_HANDLE'}; unless ($request =~ m/and\s+deviceid(\s+)?<>(\s+)?'_SYSTEMGROUP_'\s+and\s+deviceid(\s+)?<>(\s+)?'_DOWNLOADGROUP_'/i) { #We will have to verify that HARDWARE_IDs are not groups my $ids_list= join(',',@$ids); @$ids=(); my $verify_request = $dbh_sl->prepare("SELECT distinct ID from hardware where ID in ($ids_list) and deviceid <> '_SYSTEMGROUP_' AND deviceid <> '_DOWNLOADGROUP_'"); $verify_request->execute(); if(!$verify_request->rows){ &_log(307,'groups','empty') if $ENV{'OCS_OPT_LOGLEVEL'}; @$ids=(); $error = 1; } while( my @cache = $verify_request->fetchrow_array() ){ push @$ids, $cache[0]; } } return $error; } OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory.pm000066400000000000000000000164351376436473200250440ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw /_inventory_handler/; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::System qw / :server /; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Communication::Session; use Apache::Ocsinventory::Server::Duplicate; use Apache::Ocsinventory::Server::Inventory::Data; use Apache::Ocsinventory::Server::Inventory::Capacities; use Apache::Ocsinventory::Server::Inventory::Export; use Apache::Ocsinventory::Server::Inventory::Update; use Apache::Ocsinventory::Server::Inventory::Filter; use Apache::Ocsinventory::Server::Inventory::Update::AccountInfos; use Apache::Ocsinventory::Server::Inventory::Software; use Apache::Ocsinventory::Interface::SoftwareCategory; use Apache::Ocsinventory::Interface::AssetCategory; our %XML_PARSER_OPT = ( 'ForceArray' => [] ); # Remanent data my ( %SECTIONS, @SECTIONS ); &_init_map( \%SECTIONS, \@SECTIONS ); &_get_parser_ForceArray( $XML_PARSER_OPT{ForceArray} ); sub _context{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; if(!$Apache::Ocsinventory::CURRENT_CONTEXT{'EXIST_FL'}){ $dbh->do('INSERT INTO hardware(DEVICEID) VALUES(?)', {}, $Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'}) or return(1); my $request = $dbh->prepare('SELECT ID FROM hardware WHERE DEVICEID=?'); unless($request->execute($Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'})){ &_log(518,'inventory','id_error') if $ENV{'OCS_OPT_LOGLEVEL'}; return(1); } my $row = $request->fetchrow_hashref; $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'} = $row->{'ID'}; } return(0); } sub _inventory_handler{ # Call to preinventory handlers if( &_pre_options() == INVENTORY_STOP ){ &_log(107,'inventory','stopped_by_module') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_FORBIDDEN; } return APACHE_SERVER_ERROR if &_context(); my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; # Lock device if(&_lock($Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'})){ &_log( 516, 'inventory', 'device_locked'); return(APACHE_FORBIDDEN); } # Check prolog if( !check_session( \%Apache::Ocsinventory::CURRENT_CONTEXT ) ){ &_log( 114, 'inventory', 'no_session'); if( !$Apache::Ocsinventory::CURRENT_CONTEXT{'IS_TRUSTED'} && $ENV{OCS_OPT_INVENTORY_SESSION_ONLY} ){ &_log( 115, 'inventory', 'refused'); return(APACHE_FORBIDDEN); } } #Inventory incoming &_log(104,'inventory','incoming') if $ENV{'OCS_OPT_LOGLEVEL'}; # Put the inventory in the database return APACHE_SERVER_ERROR if &_update_inventory( \%SECTIONS, \@SECTIONS ); #Committing inventory $dbh->commit; #Call to post inventory handlers &_post_options(); ############# # Manage several questions, including duplicates &_post_inventory(); # That's all &_log(101,'inventory','transmitted') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_OK; } sub _post_inventory{ my $request; my $row; my $red; my $accountkey; my %elements; my @accountFields = _get_account_fields(); my $deviceId = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; set_category(); &_insert_software(); set_asset_category(); &_generate_ocs_file(); &kill_session( \%Apache::Ocsinventory::CURRENT_CONTEXT ); $red = &_duplicate_main(); # We verify accountinfo diff if the machine was already in the database if($Apache::Ocsinventory::CURRENT_CONTEXT{'EXIST_FL'} or $red){ # We put back the account infos to the agent if necessary $request = $dbh->prepare('SELECT * FROM accountinfo WHERE HARDWARE_ID=?'); $request->execute($deviceId); if($row = $request->fetchrow_hashref()){ my $up = 0; # Compare the account infos with the user's ones for $accountkey (@accountFields){ for(@{$result->{CONTENT}->{ACCOUNTINFO}}){ if($_->{KEYNAME} eq $accountkey){ utf8::encode($_->{KEYVALUE}); #We encode string to be able to make comparison if string is UTF8 $up=1,last if($_->{KEYVALUE} ne $row->{$accountkey}); } } } # If there is something new in the table if( !exists($result->{CONTENT}->{ACCOUNTINFO}) || @accountFields != @{$result->{CONTENT}->{ACCOUNTINFO}} ) { $up = 1 } if($up){ # we write the xml data $elements{'RESPONSE'} = [ 'ACCOUNT_UPDATE' ]; for(@accountFields){ push @{$elements{'ACCOUNTINFO'}}, { 'KEYNAME' => [ $_ ], 'KEYVALUE' => [ $row->{$_} ] }; } $request->finish; # send the update to the client &_send_response(\%elements); return; }else{ $request->finish; &_send_response({'RESPONSE' => [ 'NO_ACCOUNT_UPDATE' ]}); return; } }else{ # There is a problem. The device MUST be present in the table &_log(509,'postinventory','no_account_infos') if $ENV{'OCS_OPT_LOGLEVEL'}; $request->finish; $elements{'RESPONSE'} = [ 'ACCOUNT_UPDATE' ]; for(@{$result->{CONTENT}->{ACCOUNTINFO}}){ if($_->{KEYNAME} eq 'TAG'){ push @{$elements{'ACCOUNTINFO'}}, { 'KEYNAME' => [$_->{KEYNAME}], 'KEYVALUE' => [ 'LOST' ] }; }else{ push @{$elements{'ACCOUNTINFO'}}, { 'KEYNAME' => [ $_->{KEYNAME} ], 'KEYVALUE' => [ $_->{KEYVALUE} ] }; } } # call accountinfo to insert agent values in addition to the LOST value in TAG &_accountinfo("lost"); # send the update to the client with TAG=LOST &_send_response(\%elements); return; } }else{ &_send_response({'RESPONSE' => [ 'NO_ACCOUNT_UPDATE' ]}); return; } 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/000077500000000000000000000000001376436473200244755ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Cache.pm000066400000000000000000000121071376436473200260370ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Cache; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _reset_inventory_cache _cache /; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::System qw / :server /; sub _cache{ my ($op, $section, $sectionMeta, $values ) = @_; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my @fields_array = keys %{ $sectionMeta->{field_cached} }; for my $field ( @fields_array ){ my $table = $section.'_'.lc $field.'_cache'; my $err = $dbh->do("SELECT $field FROM $table WHERE $field=?", {}, $values->[ $sectionMeta->{field_cached}->{$field} ]); if( $err && $err == 0E0 && $op eq 'add'){ $dbh->do("INSERT INTO $table($field) VALUES(?)", {}, $values->[ $sectionMeta->{field_cached}->{$field} ]); } elsif( $err != 0E0 && $op eq 'del'){ my $err2 = $dbh->do("SELECT $field FROM $section WHERE $field=? LIMIT 0,1", {}, $values->[ $sectionMeta->{field_cached}->{$field} ]); if( $err2 && $err2 == 0E0 ){ $dbh->do("DELETE FROM $table WHERE $field=?", {}, $values->[ $sectionMeta->{field_cached}->{$field} ]); } } } } sub _reset_inventory_cache{ my ( $sectionsMeta, $sectionsList ) = @_; return if !$ENV{OCS_OPT_INVENTORY_CACHE_REVALIDATE}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; if( &_check_cache_validity() ){ &_log(110,'inventory_cache','checking') if $ENV{'OCS_OPT_LOGLEVEL'}; if( &_lock_cache() ){ for my $section ( @$sectionsList ){ my @fields_array = keys %{ $sectionsMeta->{$section}->{field_cached} }; for my $field (@fields_array){ my $table = $section.'_'.lc $field.'_cache'; &_log(108,'inventory_cache',"cache($section.$field)") if $ENV{'OCS_OPT_LOGLEVEL'}; my $src_table = lc $section; $dbh->do("LOCK TABLES $table WRITE, $src_table READ"); if( $dbh->do("DELETE FROM $table") ){ my $err = $dbh->do("INSERT INTO $table($field) SELECT DISTINCT $field FROM $src_table"); $dbh->do('UNLOCK TABLES'); if( $err ){ &_log(109,'inventory_cache',"ok:$section.$field") if $ENV{'OCS_OPT_LOGLEVEL'}; } else{ &_log(522,'inventory_cache',"fault:$section.$field") if $ENV{'OCS_OPT_LOGLEVEL'}; &_lock_cache_release(); return; } } else{ $dbh->do('UNLOCK TABLES'); &_log(523,'inventory_cache',"fault:$section.$field") if $ENV{'OCS_OPT_LOGLEVEL'}; &_lock_cache_release(); return; } } } } else{ &_log(111,'inventory_cache','already_handled') if $ENV{'OCS_OPT_LOGLEVEL'}; return; } $dbh->do('INSERT INTO engine_persistent(NAME,IVALUE) VALUES("INVENTORY_CACHE_CLEAN_DATE", UNIX_TIMESTAMP(NOW()))') if($dbh->do('UPDATE engine_persistent SET IVALUE=UNIX_TIMESTAMP(NOW()) WHERE NAME="INVENTORY_CACHE_CLEAN_DATE"')==0E0); &_lock_cache_release(); &_log(109,'inventory_cache','done') if $ENV{'OCS_OPT_LOGLEVEL'}; } else{ return; } } sub _check_cache_validity{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $check_cache = $dbh->prepare('SELECT UNIX_TIMESTAMP(NOW())-IVALUE AS IVALUE FROM engine_persistent WHERE NAME="INVENTORY_CACHE_CLEAN_DATE"'); $check_cache->execute(); if($check_cache->rows()){ my $row = $check_cache->fetchrow_hashref(); if($row->{IVALUE}< $ENV{OCS_OPT_INVENTORY_CACHE_REVALIDATE}*86400 ){ return 0; } else{ return 1; } } else{ return 1; } } sub _lock_cache{ return $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}->do("INSERT INTO engine_mutex(NAME, PID, TAG) VALUES('INVENTORY_CACHE_REVALIDATE',?,'ALL')", {}, $$) } sub _lock_cache_release{ return $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}->do("DELETE FROM engine_mutex WHERE NAME='INVENTORY_CACHE_REVALIDATE' AND PID=?", {}, $$); } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Capacities.pm000066400000000000000000000035031376436473200271010ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Capacities; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _pre_options _post_options /; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::System qw / :server _modules_get_pre_inventory_options _modules_get_post_inventory_options /; sub _pre_options{ for(&_modules_get_pre_inventory_options()){ last if $_== 0; if (&$_(\%Apache::Ocsinventory::CURRENT_CONTEXT) == INVENTORY_STOP){ return INVENTORY_STOP; } } } sub _post_options{ for(&_modules_get_post_inventory_options()){ last if $_== 0; &$_(\%Apache::Ocsinventory::CURRENT_CONTEXT); } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Data.pm000066400000000000000000000226611376436473200257130ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Data; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _init_map _get_bind_values _has_changed _get_parser_ForceArray /; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::System qw / :server /; sub _init_map{ my ($sectionsMeta, $sectionsList) = @_; my $section; my @bind_num; my $field; my $fields_string; my $field_index; # Parse every section for $section (keys(%DATA_MAP)){ $field_index = 0; # Field array (from data_map field hash keys), filtered fields and cached fields $sectionsMeta->{$section}->{field_arrayref} = []; $sectionsMeta->{$section}->{field_filtered} = []; $sectionsMeta->{$section}->{field_cached} = {}; ############################################## #Don't process the sections that are use for capacities special inventory next if $DATA_MAP{$section}->{capacities}; # Don't process the non-auto-generated sections next if !$DATA_MAP{$section}->{auto}; $sectionsMeta->{$section}->{multi} = 1 if $DATA_MAP{$section}->{multi}; $sectionsMeta->{$section}->{mask} = $DATA_MAP{$section}->{mask}; $sectionsMeta->{$section}->{delOnReplace} = 1 if $DATA_MAP{$section}->{delOnReplace}; $sectionsMeta->{$section}->{writeDiff} = 1 if $DATA_MAP{$section}->{writeDiff}; $sectionsMeta->{$section}->{cache} = 1 if $DATA_MAP{$section}->{cache}; $sectionsMeta->{$section}->{mandatory} = 1 if $DATA_MAP{$section}->{mandatory}; $sectionsMeta->{$section}->{auto} = 1 if $DATA_MAP{$section}->{auto}; $sectionsMeta->{$section}->{name} = $section; # $sectionsMeta->{$section}->{hasChanged} is set while inventory update # Parse fields of the current section for $field ( keys(%{$DATA_MAP{$section}->{fields}} ) ){ if(!$DATA_MAP{$section}->{fields}->{$field}->{noSql}){ push @{$sectionsMeta->{$section}->{field_arrayref}}, $field; $sectionsMeta->{$section}->{noSql} = 1 unless $sectionsMeta->{$section}->{noSql}; } if($DATA_MAP{$section}->{fields}->{$field}->{filter}){ next unless $ENV{OCS_OPT_INVENTORY_FILTER_ENABLED}; push @{$sectionsMeta->{$section}->{field_filtered}}, $field; $sectionsMeta->{$section}->{filter} = 1 unless $sectionsMeta->{$section}->{filter}; } if($DATA_MAP{$section}->{fields}->{$field}->{cache}){ next unless $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED}; $sectionsMeta->{$section}->{field_cached}->{$field} = $field_index; $sectionsMeta->{$section}->{cache} = 1 unless $sectionsMeta->{$section}->{cache}; } if(defined $DATA_MAP{$section}->{fields}->{$field}->{fallback}){ $sectionsMeta->{$section}->{fields}->{$field}->{fallback} = $DATA_MAP{$section}->{fields}->{$field}->{fallback}; } if(defined $DATA_MAP{$section}->{fields}->{$field}->{type}){ $sectionsMeta->{$section}->{fields}->{$field}->{type} = $DATA_MAP{$section}->{fields}->{$field}->{type}; } $field_index++; } # Build the "DBI->prepare" sql insert string $fields_string = join ',', ('HARDWARE_ID', @{$sectionsMeta->{$section}->{field_arrayref}}); $sectionsMeta->{$section}->{sql_insert_string} = "INSERT INTO $section($fields_string) VALUES("; for(0..@{$sectionsMeta->{$section}->{field_arrayref}}){ push @bind_num, '?'; } $sectionsMeta->{$section}->{sql_insert_string}.= (join ',', @bind_num).')'; @bind_num = (); # Build the "DBI->prepare" sql select string $sectionsMeta->{$section}->{sql_select_string} = "SELECT ID,$fields_string FROM $section WHERE HARDWARE_ID=? ORDER BY ".$DATA_MAP{$section}->{sortBy}; # Build the "DBI->prepare" sql deletion string $sectionsMeta->{$section}->{sql_delete_string} = "DELETE FROM $section WHERE HARDWARE_ID=? AND ID=?"; # to avoid many "keys" push @$sectionsList, $section; } #Special treatment for hardware section $sectionsMeta->{'hardware'} = &_get_hardware_fields; push @$sectionsList, 'hardware'; } sub _get_bind_values{ my ($refXml, $sectionMeta, $arrayToFeed) = @_; my ($bind_value, $xmlvalue, $xmlfield); for my $field ( @{ $sectionMeta->{field_arrayref} } ) { if(ref($refXml) eq 'HASH'){ if(defined($refXml->{$field}) && !defined($sectionMeta->{fields}->{$field}->{type}) && $refXml->{$field} ne '' && $refXml->{$field} ne '??' && $refXml->{$field}!~/^N\/?A$/) { $bind_value = $refXml->{$field} } else{ if( defined $sectionMeta->{fields}->{$field}->{fallback} ){ $bind_value = $sectionMeta->{fields}->{$field}->{fallback}; &_log( 000, 'fallback', "$field:".$sectionMeta->{fields}->{$field}->{fallback}) if $ENV{'OCS_OPT_LOGLEVEL'}>1; } else{ &_log( 000, 'generic-fallback', "$field:".$sectionMeta->{fields}->{$field}->{fallback}) if $ENV{'OCS_OPT_LOGLEVEL'}>1; $bind_value = ''; } } } # We have to substitute the value with the ID matching "type_section_field.name" if the field is tagged "type". # It allows to support different DB structures if(defined $sectionMeta->{fields}->{$field}->{type}) { $xmlfield = $field; $xmlfield =~ s/_ID//g; #We delete the _ID pattern to be in concordance with XML if(defined $sectionMeta->{fields}->{$field}->{fallback}) { $bind_value = _get_type_id($sectionMeta->{name}, $xmlfield, $sectionMeta->{fields}->{$field}->{fallback} ); &_log( 000, 'fallback', "$field:".$sectionMeta->{fields}->{$field}->{fallback}) if $ENV{'OCS_OPT_LOGLEVEL'}>1; } else { #No fallback for this field $xmlvalue = $refXml->{$xmlfield}; $bind_value = _get_type_id($sectionMeta->{name}, $xmlfield, $xmlvalue); } } push @$arrayToFeed, $bind_value; } } sub _get_parser_ForceArray{ my $arrayRef = shift; for my $section (keys(%DATA_MAP)){ unless ($DATA_MAP{$section}->{capacities}) { # Feed the multilines section array in order to parse xml correctly push @{ $arrayRef }, uc $section if $DATA_MAP{$section}->{multi}; } } } sub _has_changed{ my $section = shift; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; # Don't use inventory diff if section mask is return 1 if $DATA_MAP{$section}->{mask}==0; # Check checksum to know if section has changed if( defined($result->{CONTENT}->{HARDWARE}->{CHECKSUM}) ){ return $DATA_MAP{$section}->{mask} & $result->{CONTENT}->{HARDWARE}->{CHECKSUM}; } else{ &_log( 524, 'inventory', "$section (no checksum)") if $ENV{'OCS_OPT_LOGLEVEL'}; return 1; } } sub _get_type_id { #TODO: create it if needed # Type table structure # CREATE TABLE type_${section}_$field ( # ID INTEGER NOT NULL auto_increment, # NAME VARCHAR(255)) # ENGINE=INNODB, DEFAULT CHARSET=UTF8 ; # For migration, add the following line : # ALTER TABLE $section CHANGE COLUMN $field $field_ID INTEGER NOT NULL ; my ($section, $field, $value) = @_ ; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'} ; my ($id, $existsReq, $createSql); my $table_name = 'type_'.lc $section.'_'.lc $field ; if ($value eq '') { #Value from XML is empty $existsReq = $dbh->prepare("SELECT ID FROM $table_name WHERE NAME IS NULL") ; $createSql = "INSERT INTO $table_name(NAME) VALUES(NULL)" ; $existsReq->execute() ; } else { $existsReq = $dbh->prepare("SELECT ID FROM $table_name WHERE NAME=?") ; $createSql = "INSERT INTO $table_name(NAME) VALUES(?)" ; $existsReq->execute($value) ; } # It exists if($existsReq->rows){ my $row = $existsReq->fetchrow_hashref() ; $id = $row->{ID} ; } # It does not exist else{ if ($value eq '') { $dbh->do($createSql) && $existsReq->execute(); } else { $dbh->do($createSql, {}, $value) && $existsReq->execute($value); } my $row = $existsReq->fetchrow_hashref() ; $id = $row->{ID} ; } return $id ; } sub _get_hardware_fields { my $sectionMeta = {}; my $field; my $field_index=0; #Variable for feeding in _cache function #We only get cache fields for $field ( keys(%{$DATA_MAP{'hardware'}->{fields}} ) ){ if($DATA_MAP{'hardware'}->{fields}->{$field}->{cache}){ next unless $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED}; $sectionMeta->{field_cached}->{$field}=$field_index; $field_index++; } } return $sectionMeta; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Export.pm000066400000000000000000000045011376436473200263140ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Export; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _generate_ocs_file /; use Apache::Ocsinventory::Server::System qw / :server /; sub _generate_ocs_file{ return if !$ENV{'OCS_OPT_GENERATE_OCS_FILES'}; my $ocs_path = $ENV{'OCS_OPT_OCS_FILES_PATH'}; my $ocs_file_name = $Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'}; my $ocs_file = $ocs_path.'/'.$ocs_file_name.'.ocs'; my $format; my $v=1; $format = 'ocs' unless $format = $ENV{'OCS_OPT_OCS_FILES_FORMAT'}; if(!$ENV{'OCS_OPT_OCS_FILES_OVERWRITE'}){ while(-e $ocs_file){ $ocs_file=~s/(.+-\d{4}(-\d{2}){5})(?:-\d+)?\.ocs/$1-$v.ocs/; $v++; } } if( !open FILE, ">$ocs_file" ){ &_log(520,'postinventory',"$ocs_file: $!") if $ENV{'OCS_OPT_LOGLEVEL'}; } else{ if($format=~/^ocs$/i){ binmode FILE ; print FILE ${$Apache::Ocsinventory::CURRENT_CONTEXT{'RAW_DATA'}}; } elsif($format=~/^xml$/i){ print FILE ${$Apache::Ocsinventory::CURRENT_CONTEXT{'DATA'}}; } else{ &_log(521,'postinventory','wrong file format') if $ENV{'OCS_OPT_LOGLEVEL'}; } close(FILE); } return; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Filter.pm000066400000000000000000000030221376436473200262550ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Filter; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw //; use Apache::Ocsinventory::Server::System qw / :server /; #sub _inventory_filter{ # my $section = shift; # return unless $SECTIONS{$section}->{filter}; #There is at least one field to filter # my $fields_array = $SECTIONS{$section}->{field_filtered}; #} 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Software.pm000066400000000000000000000164241376436473200266340ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2020 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Software; use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; use strict; use warnings; use Switch; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _get_info_software _del_all_soft _insert_software _prepare_sql _insert_software_name /; sub _prepare_sql { my ($sql, @arguments) = @_; my $query; my $i = 1; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; $query = $dbh->prepare($sql); foreach my $value (@arguments) { $query->bind_param($i, $value); $i++; } $query->execute; return $query; } sub _insert_software_name { my ($name, $cat) = @_; my $sql; my $categoryVerif = undef; my $valueResult = undef; my $result; # Verif if value exist my @argVerif = (); $sql = "SELECT ID, CATEGORY FROM software_name WHERE NAME = ?"; push @argVerif, $name; $result = _prepare_sql($sql, @argVerif); while(my $row = $result->fetchrow_hashref()){ $valueResult = $row->{ID}; $categoryVerif = $row->{CATEGORY}; } if(!defined $valueResult) { my @argInsert = (); if(!defined $cat) { # Insert if undef $sql = "INSERT INTO software_name (NAME) VALUES(?)"; push @argInsert, $name; } else { # Insert if undef $sql = "INSERT INTO software_name (NAME,CATEGORY) VALUES(?,?)"; push @argInsert, $name; push @argInsert, $cat; } _prepare_sql($sql, @argInsert); # Get last Insert or Update ID my @argSelect = (); $sql = "SELECT ID FROM software_name WHERE NAME = ?"; push @argSelect, $name; $result = _prepare_sql($sql, @argSelect); while(my $row = $result->fetchrow_hashref()){ $valueResult = $row->{ID}; } } if(defined $cat) { if((!defined $categoryVerif) || ($cat != $categoryVerif)) { my @argUpdate = (); my $sqlUpdate = "UPDATE software_name SET CATEGORY = ? WHERE ID = ?"; push @argUpdate, $cat; push @argUpdate, $valueResult; _prepare_sql($sqlUpdate, @argUpdate); } } return $valueResult; } sub _get_info_software { my ($value, $table, $column) = @_; my $sql; my $valueResult = undef; my $result; my $resultVerif; # Verif if value exist my @argVerif = (); $sql = "SELECT ID FROM $table WHERE $column = ?"; push @argVerif, $value; $resultVerif = _prepare_sql($sql, @argVerif); while(my $row = $resultVerif->fetchrow_hashref()){ $valueResult = $row->{ID}; } if(!defined $valueResult) { my @argInsert = (); # Insert if undef $sql = "INSERT INTO $table ($column) VALUES(?)"; push @argInsert, $value; _prepare_sql($sql, @argInsert); # Get last Insert or Update ID my @argSelect = (); $sql = "SELECT ID FROM $table WHERE $column = ?"; push @argSelect, $value; $result = _prepare_sql($sql, @argSelect); while(my $row = $result->fetchrow_hashref()){ $valueResult = $row->{ID}; } } return $valueResult; } sub _del_all_soft { my ($hardware_id) = @_; my $sql; my @arg = (); my $result; my $id = 0; $sql = "DELETE FROM software WHERE HARDWARE_ID = ?"; push @arg, $hardware_id; $result = _prepare_sql($sql, @arg); } sub _insert_software { my $sql; my $hardware_id = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; my @arrayRef = ('HARDWARE_ID', 'NAME_ID', 'PUBLISHER_ID', 'VERSION_ID', 'FOLDER', 'COMMENTS', 'FILENAME', 'FILESIZE', 'SOURCE', 'GUID', 'LANGUAGE', 'INSTALLDATE', 'BITSWIDTH'); _del_all_soft($hardware_id); foreach my $software (@{$Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}->{CONTENT}->{SOFTWARES}}) { my %arrayValue = ( "HARDWARE_ID" => $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}, "NAME_ID" => 1, "PUBLISHER_ID" => 1, "VERSION_ID" => 1, "FOLDER" => $software->{FOLDER} // "", "COMMENTS" => $software->{COMMENTS} // "", "FILENAME" => $software->{FILENAME} // "", "FILESIZE" => $software->{FILESIZE} // 0, "SOURCE" => $software->{SOURCE} // 0, "GUID" => $software->{GUID} // "", "LANGUAGE" => $software->{LANGUAGE} // "", "INSTALLDATE" => $software->{INSTALLDATE}, "BITSWIDTH" => $software->{BITSWIDTH} // 0 ); my $name = $software->{NAME}; my $publisher = $software->{PUBLISHER}; my $version = $software->{VERSION}; my @bind_num; my @bind_update; # Get software Name ID if exists if(defined $name) { $arrayValue{NAME_ID} = _insert_software_name($name, $software->{CATEGORY}); } # Get software Publisher ID if exists if(defined $publisher && $publisher ne '') { $arrayValue{PUBLISHER_ID} = _get_info_software($publisher, "software_publisher", "PUBLISHER"); } # Get software Version ID if exists if(defined $version && $version ne '') { $arrayValue{VERSION_ID} = _get_info_software($version, "software_version", "VERSION"); } my $arrayRefString = join ',', @arrayRef; my @arg = (); foreach my $arrayKey(@arrayRef) { push @bind_num, '?'; push @bind_update, $arrayKey.' = ?'; push @arg, $arrayValue{$arrayKey}; } $sql = "INSERT INTO software ($arrayRefString) VALUES("; $sql .= (join ',', @bind_num).') '; _prepare_sql($sql, @arg); } } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Update.pm000066400000000000000000000152621376436473200262630ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Update; use Apache::Ocsinventory::Server::Inventory::Cache; use Apache::Ocsinventory::Server::Inventory::Update::Hardware; use Apache::Ocsinventory::Server::Inventory::Update::AccountInfos; use Apache::Ocsinventory::Server::Inventory::Software; use Apache::Ocsinventory::Interface::SoftwareCategory; use Apache::Ocsinventory::Interface::AssetCategory; use Apache::Ocsinventory::Interface::Saas; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _update_inventory /; use Apache::Ocsinventory::Server::System qw / :server /; use Apache::Ocsinventory::Server::Inventory::Data; sub _update_inventory{ my ( $sectionsMeta, $sectionsList ) = @_; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $section; set_category(); &_insert_software(); set_asset_category(); set_saas(); &_reset_inventory_cache( $sectionsMeta, $sectionsList ) if $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED}; # Call special sections update if(&_hardware($sectionsMeta->{'hardware'}) or &_accountinfo()){ return 1; } # Call the _update_inventory_section for each section for $section (@{$sectionsList}){ #Only if section exists in XML or if table is mandatory if (($result->{CONTENT}->{uc $section} || $sectionsMeta->{$section}->{mandatory}) && $sectionsMeta->{$section}->{auto}) { if(_update_inventory_section($section, $sectionsMeta->{$section})){ return 1; } } } } sub _update_inventory_section{ my ($section, $sectionMeta) = @_; my @bind_values; my $deviceId = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; # The computer exists. # We check if this section has changed since the last inventory (only if activated) # We delete the previous entries if($Apache::Ocsinventory::CURRENT_CONTEXT{'EXIST_FL'}){ if($ENV{'OCS_OPT_INVENTORY_DIFF'}){ if( _has_changed($section) ){ &_log( 113, 'inventory', "u:$section") if $ENV{'OCS_OPT_LOGLEVEL'}; $sectionMeta->{hasChanged} = 1; } else{ return 0; } } else{ $sectionMeta->{hasChanged} = 1; } if( $sectionMeta->{delOnReplace} && !($sectionMeta->{writeDiff} && $ENV{'OCS_OPT_INVENTORY_WRITE_DIFF'}) ){ if(!$dbh->do("DELETE FROM $section WHERE HARDWARE_ID=?", {}, $deviceId)){ return(1); } } } # DEL AND REPLACE, or detect diff on elements of the section (more load on frontends, less on DB backend) if($Apache::Ocsinventory::CURRENT_CONTEXT{'EXIST_FL'} && $ENV{'OCS_OPT_INVENTORY_WRITE_DIFF'} && $sectionMeta->{writeDiff}){ my @fromDb; my @fromXml; my $refXml = $result->{CONTENT}->{uc $section}; my $sth = $dbh->prepare($sectionMeta->{sql_select_string}); $sth->execute($deviceId) or return 1; while(my @row = $sth->fetchrow_array){ push @fromDb, [ @row ]; } for my $line (@$refXml){ &_get_bind_values($line, $sectionMeta, \@bind_values); push @fromXml, [ @bind_values ]; @bind_values = (); } #TODO: Sorting XML entries, to compare more quickly with DB elements my $new=0; my $del=0; for my $l_xml (@fromXml){ my $found = 0; for my $i_db (0..$#fromDb){ next unless $fromDb[$i_db]; my @line = @{$fromDb[$i_db]}; my $comp_xml = join '', @$l_xml; my $comp_db = join '', @line[2..$#line]; if( $comp_db eq $comp_xml ){ $found = 1; # The value has been found, we have to delete it from the db list # (elements remaining will be deleted) delete $fromDb[$i_db]; last; } } if(!$found){ $new++; $dbh->do( $sectionMeta->{sql_insert_string}, {}, $deviceId, @$l_xml ) or return 1; if( $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED} && $sectionMeta->{cache} ){ &_cache( 'add', $section, $sectionMeta, $l_xml ); } } } # Now we have to delete from DB elements that still remain in fromDb for (@fromDb){ next if !defined (${$_}[0]); $del++; $dbh->do( $sectionMeta->{sql_delete_string}, {}, $deviceId, ${$_}[0]) or return 1; my @ldb = @$_; @ldb = @ldb[ 2..$#ldb ]; if( $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED} && $sectionMeta->{cache} && !$ENV{OCS_OPT_INVENTORY_CACHE_KEEP}){ &_cache( 'del', $section, $sectionMeta, \@ldb ); } } if( $new||$del ){ &_log( 113, 'write_diff', "ch:$section(+$new-$del)") if $ENV{'OCS_OPT_LOGLEVEL'}; } } else{ # Processing values my $sth = $dbh->prepare( $sectionMeta->{sql_insert_string} ); # Multi lines (forceArray) my $refXml = $result->{CONTENT}->{uc $section}; if($sectionMeta->{multi}){ for my $line (@$refXml){ &_get_bind_values($line, $sectionMeta, \@bind_values); if(!$sth->execute($deviceId, @bind_values)){ return(1); } if( $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED} && $sectionMeta->{cache} ){ &_cache( 'add', $section, $sectionMeta, \@bind_values ); } @bind_values = (); } } # One line (hash) else{ &_get_bind_values($refXml, $sectionMeta, \@bind_values); if( !$sth->execute($deviceId, @bind_values) ){ return(1); } if( $ENV{OCS_OPT_INVENTORY_CACHE_ENABLED} && $sectionMeta->{cache} ){ &_cache( 'add', $section, $sectionMeta, \@bind_values ); } } } $dbh->commit unless $ENV{'OCS_OPT_INVENTORY_TRANSACTION'}; 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Update/000077500000000000000000000000001376436473200257175ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Update/AccountInfos.pm000066400000000000000000000065261376436473200306610ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Update::AccountInfos; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw/_get_account_fields _accountinfo/; use Apache::Ocsinventory::Server::System qw/ :server /; sub _get_account_fields{ my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $request = $dbh->prepare('SHOW COLUMNS FROM accountinfo'); my @accountFields; $request->execute; while(my $row=$request->fetchrow_hashref){ push @accountFields, $row->{'Field'} if($row->{'Field'} ne 'HARDWARE_ID'); } return @accountFields; } sub _accountinfo{ my $lost=shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $hardwareId = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; # We have to look for the field's names because this table has a dynamic structure my ($row, $request, $accountkey, @accountFields); @accountFields = _get_account_fields(); # The default behavior of the server is to ignore TAG changes from the # agent if( $ENV{OCS_OPT_ACCEPT_TAG_UPDATE_FROM_CLIENT} || !$Apache::Ocsinventory::CURRENT_CONTEXT{'EXIST_FL'} || $lost ){ # writing (if new id, but duplicate, it will be erased at the end of the execution) $dbh->do('INSERT INTO accountinfo(HARDWARE_ID) VALUES(?)', {}, $hardwareId); # Now, we know what are the account info name fields # We can insert the client's data. This data will be kept only one time, in the first inventory if( exists ($result->{CONTENT}->{ACCOUNTINFO}) ){ for $accountkey (@accountFields){ my $array = $result->{CONTENT}->{ACCOUNTINFO}; for(@$array){ if($_->{KEYNAME} eq $accountkey){ if(!$dbh->do('UPDATE accountinfo SET '.$accountkey."=".$dbh->quote($_->{KEYVALUE}).' WHERE HARDWARE_ID='.$hardwareId)){ return 1; } } } } } else{ &_log(528,'accountinfos','missing') if $ENV{'OCS_OPT_LOGLEVEL'}; } } if($lost){ if(!$dbh->do('UPDATE accountinfo SET TAG = "LOST" WHERE HARDWARE_ID=?', {}, $hardwareId)){ return(1); } } $dbh->commit unless $ENV{'OCS_OPT_INVENTORY_TRANSACTION'}; 0; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Inventory/Update/Hardware.pm000066400000000000000000000107031376436473200300130ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Inventory::Update::Hardware; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _hardware /; use Apache::Ocsinventory::Server::Inventory::Cache; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Server::System qw / :server /; sub _hardware{ my $sectionMeta = shift; my $result = $Apache::Ocsinventory::CURRENT_CONTEXT{'XML_ENTRY'}; my $base = $result->{CONTENT}->{HARDWARE}; my $ua = $Apache::Ocsinventory::CURRENT_CONTEXT{'USER_AGENT'}; my $deviceId = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; # We replace all data but quality and fidelity. The last come becomes the last date. my $userid = ''; $userid = "USERID=".$dbh->quote($base->{USERID})."," if( $base->{USERID}!~/(system|localsystem)/i ); my $ipAddress = &_get_default_iface(); $dbh->do("UPDATE hardware SET USERAGENT=".$dbh->quote($ua).", LASTDATE=".((defined($base->{LASTDATE})&&($base->{LASTDATE} ne "1970-01-01"))?$dbh->quote($base->{LASTDATE}):"NOW()").", LASTCOME=NOW(), CHECKSUM=(".(defined($base->{CHECKSUM})?$base->{CHECKSUM}:CHECKSUM_MAX_VALUE)."|CHECKSUM|1), NAME=".$dbh->quote($base->{NAME}).", WORKGROUP=".$dbh->quote($base->{WORKGROUP}).", USERDOMAIN=".$dbh->quote($base->{USERDOMAIN}).", OSNAME=".$dbh->quote($base->{OSNAME}).", OSVERSION=".$dbh->quote($base->{OSVERSION}).", OSCOMMENTS=".$dbh->quote($base->{OSCOMMENTS}).", PROCESSORT=".$dbh->quote($base->{PROCESSORT}).", PROCESSORS=".(defined($base->{PROCESSORS})?$base->{PROCESSORS}:0).", PROCESSORN=".(defined($base->{PROCESSORN})?$base->{PROCESSORN}:0).", MEMORY=".(defined($base->{MEMORY})?$base->{MEMORY}:0).", SWAP=".(defined($base->{SWAP})?$base->{SWAP}:0).", IPADDR=".$dbh->quote($ipAddress).", DNS=".$dbh->quote($base->{DNS}).", DEFAULTGATEWAY=".$dbh->quote($base->{DEFAULTGATEWAY}).", ETIME=NULL, $userid TYPE=".(defined($base->{TYPE})?$base->{TYPE}:0).", DESCRIPTION=".$dbh->quote($base->{DESCRIPTION}).", WINCOMPANY=".$dbh->quote($base->{WINCOMPANY}).", WINOWNER=".$dbh->quote($base->{WINOWNER}).", WINPRODID=".$dbh->quote($base->{WINPRODID}).", WINPRODKEY=".$dbh->quote($base->{WINPRODKEY}).", IPSRC=".$dbh->quote($Apache::Ocsinventory::CURRENT_CONTEXT{IPADDRESS}).", UUID=".$dbh->quote($base->{UUID}).", ARCH=".$dbh->quote($base->{ARCH}).", CATEGORY_ID=".$dbh->quote($base->{CATEGORY_ID})." WHERE ID=".$deviceId) or return(1); #We feed cache tables associated to hardware fields if ($ENV{OCS_OPT_INVENTORY_CACHE_ENABLED}) { my $cache_values =[]; for (keys %{ $sectionMeta->{field_cached}} ) { #Feeding array for cache values $cache_values->[ $sectionMeta->{field_cached}->{$_} ] = $base->{$_}; } &_cache( 'add', 'hardware', $sectionMeta, $cache_values ); } $dbh->commit unless $ENV{'OCS_OPT_INVENTORY_TRANSACTION'}; 0; } sub _get_default_iface{ return undef if !defined $Apache::Ocsinventory::CURRENT_CONTEXT{XML_ENTRY}->{CONTENT}->{NETWORKS}; my $networks = $Apache::Ocsinventory::CURRENT_CONTEXT{XML_ENTRY}->{CONTENT}->{NETWORKS}; for( @$networks ){ if( $_->{IPADDRESS} eq $Apache::Ocsinventory::CURRENT_CONTEXT{IPADDRESS}){ return $_->{IPADDRESS}; } } return $Apache::Ocsinventory::CURRENT_CONTEXT{XML_ENTRY}->{CONTENT}->{HARDWARE}->{IPADDR}; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Modperl1.pm000066400000000000000000000047701376436473200245310ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Modperl1; # For compatibilities with apache 1,5 ##################################### use mod_perl; use constant MP2 => $mod_perl::VERSION >= 1.99; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw/ APACHE_SERVER_ERROR APACHE_FORBIDDEN APACHE_OK APACHE_BAD_REQUEST _set_http_header _set_http_content_type _get_http_header _send_http_headers /; BEGIN{ if(MP2){ require Apache::compat; Apache::compat->import(); require Apache::Const; Apache::Const->import(-compile => qw(:common :http)); }else{ require Apache::Constants; Apache::Constants->import(qw(:common :response)); } } # retrieve apache constants use constant APACHE_SERVER_ERROR => MP2?Apache::SERVER_ERROR:Apache::Constants::SERVER_ERROR; use constant APACHE_FORBIDDEN => MP2?Apache::FORBIDDEN:Apache::Constants::FORBIDDEN; use constant APACHE_OK => MP2?Apache::OK:Apache::Constants::OK; use constant APACHE_BAD_REQUEST => MP2?Apache::BAD_REQUEST:Apache::Constants::BAD_REQUEST; # Wrappers sub _set_http_header{ my ($header, $value, $r) = @_; $r->header_out($header => $value); return(0); } sub _set_http_content_type{ my ($type, $r) = @_; $r->content_type($type); } sub _get_http_header{ my ($header, $r) = @_; return $r->headers_in->{$header}; } sub _send_http_headers{ my $r = shift; $r->send_http_header; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Modperl2.pm000066400000000000000000000045211376436473200245240ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Modperl2; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw/ APACHE_SERVER_ERROR APACHE_FORBIDDEN APACHE_OK APACHE_BAD_REQUEST _set_http_header _set_http_content_type _get_http_header _send_http_headers /; # mod-perl2 ############ use Apache2::Connection (); use Apache2::SubRequest (); use Apache2::Access (); use Apache2::RequestIO (); use Apache2::RequestUtil (); use Apache2::RequestRec (); use Apache2::ServerUtil (); use Apache2::Log; use APR::Table (); use Apache2::Const -compile => qw(OK HTTP_FORBIDDEN SERVER_ERROR HTTP_BAD_REQUEST); # retrieve apache constants use constant APACHE_SERVER_ERROR => Apache2::Const::SERVER_ERROR; use constant APACHE_FORBIDDEN => Apache2::Const::HTTP_FORBIDDEN; use constant APACHE_OK => Apache2::Const::OK; use constant APACHE_BAD_REQUEST => Apache2::Const::HTTP_BAD_REQUEST; # Wrappers sub _set_http_header{ my ($header, $value, $r) = @_; $r->headers_out->{$header} = $value; } sub _set_http_content_type{ my ($type, $r) = @_; $r->content_type($type); } sub _get_http_header{ my ($header, $r) = @_; return $r->headers_in->{$header}; } sub _send_http_headers{ return; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/System.pm000066400000000000000000000354401376436473200243300ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::System::Config; use strict; BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } &check_config(); } require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _log _debug _lock _unlock _send_file /; our %EXPORT_TAGS = ( 'server' => [ qw/ _get_xml_parser_opt _get_sys_options _database_connect _end _check_deviceid _log _debug _lock _unlock _send_file _inflate _get_spec_params _get_spec_params_g / ] ); our @EXPORT_OK = ( qw / _log _lock _modules_get_request_handler _modules_get_pre_inventory_options _modules_get_post_inventory_options _modules_get_prolog_readers _modules_get_prolog_writers _modules_get_duplicate_handlers / ); Exporter::export_ok_tags('server'); use Apache::Ocsinventory::Server::Constants; sub _get_sys_options{ return 0 if $ENV{OCS_OPT_OPTIONS_NOT_OVERLOADED}; # Which options enabled ? ############# # We read the table config looking for the ivalues of these options my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $row; my $request = $dbh->prepare('SELECT * FROM config'); $request->execute; # read options defined in ocs GUI while($row=$request->fetchrow_hashref){ for( keys %CONFIG ){ if( $row->{'NAME'} eq $_){ $ENV{'OCS_OPT_'.$_} = $row->{ $CONFIG{$_}->{type} }; } } } $request->finish; 0; } # Try other compress algorithm sub _inflate{ my @inflate_subs = ( # gzip file content sub { my $data_ref = shift; if(my $result = Compress::Zlib::memGunzip( ${$data_ref})){ $Apache::Ocsinventory::CURRENT_CONTEXT{'DEFLATE_SUB'} = \&Compress::Zlib::memGzip; &_log(321,'system', 'gzip') if $ENV{'OCS_OPT_LOGLEVEL'}; return $result; } undef; }, sub { my $ref = shift; if($$ref =~ /^<\?xml/i){ $Apache::Ocsinventory::CURRENT_CONTEXT{'DEFLATE_SUB'} = sub {return $_[0]}; &_log(321,'system', 'not_deflated') if $ENV{'OCS_OPT_LOGLEVEL'}; return $$ref; } undef; } ); my $data_ref = shift; my $inflated_ref = shift; for( @inflate_subs ){ last if( $$inflated_ref = &{$_}($data_ref) ); }; 1; } # Database connection sub _database_connect{ my $mode = shift; my %params; my ($host, $database, $port, $user, $password); my $env_mode_prefix = 'OCS_DB'; if($mode eq 'write'){ ($host, $database, $port, $user, $password) = ( $ENV{'OCS_DB_HOST'}, $ENV{'OCS_DB_NAME'}, $ENV{'OCS_DB_PORT'}, $ENV{'OCS_DB_USER'}, $Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}->dir_config('OCS_DB_PWD') ); } # Local Mode elsif($mode eq 'local'){ ($host, $port, $user, $password) = ( $ENV{'OCS_DB_HOST'}, $ENV{'OCS_DB_PORT'}, $ENV{'OCS_DB_USER'}, $Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}->dir_config('OCS_DB_PWD') ); $database = $ENV{'OCS_DB_LOCAL'}||$ENV{'OCS_DB_NAME'}; } # Slave mode elsif($mode eq 'read'){ if($ENV{'OCS_DB_SL_HOST'}){ $host = $ENV{'OCS_DB_SL_HOST'}; $database = $ENV{'OCS_DB_SL_NAME'}||'ocsweb'; $port = $ENV{'OCS_DB_SL_PORT'}||'3306'; $user = $ENV{'OCS_DB_SL_USER'}; $password = $Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}->dir_config('OCS_DB_SL_PWD'); $env_mode_prefix .= '_SL'; } else{ $host = $ENV{'OCS_DB_HOST'}; $database = $ENV{'OCS_DB_NAME'}||'ocsweb'; $port = $ENV{'OCS_DB_PORT'}||'3306'; $user = $ENV{'OCS_DB_USER'}; $password = $Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}->dir_config('OCS_DB_PWD'); } } else{ &_log(521,'database_connect', 'invalid_mode') if $ENV{'OCS_OPT_LOGLEVEL'}; return undef; } $params{'AutoCommit'} = 0; $params{'PrintError'} = $ENV{'OCS_OPT_DBI_PRINT_ERROR'}; # Optionnaly a mysql socket different than the client's built in $params{'mysql_socket'} = $ENV{'OCS_OPT_DBI_MYSQL_SOCKET'} if $ENV{'OCS_OPT_DBI_MYSQL_SOCKET'}; my $mysql_ssl_mode = ''; if( defined($ENV{$env_mode_prefix.'_SSL_ENABLED'}) and $ENV{$env_mode_prefix.'_SSL_ENABLED'} == 1 ) { if( defined($ENV{$env_mode_prefix.'_SSL_MODE'}) and $ENV{$env_mode_prefix.'_SSL_MODE'} eq 'SSL_MODE_PREFERRED' ) { $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_optional=1'; } elsif( defined($ENV{$env_mode_prefix.'_SSL_MODE'}) and $ENV{$env_mode_prefix.'_SSL_MODE'} eq 'SSL_MODE_REQUIRED' ) { $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_verify_server_cert=0'; } elsif( defined($ENV{$env_mode_prefix.'_SSL_MODE'}) and $ENV{$env_mode_prefix.'_SSL_MODE'} eq 'SSL_MODE_STRICT' ) { $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_verify_server_cert=1'; } else { # SSL Is enabled but mode hasn't been provided. Let's put PREFERRED mode by default $mysql_ssl_mode = ';mysql_ssl=1;mysql_ssl_optional=1'; } if( defined( $ENV{$env_mode_prefix.'_SSL_CLIENT_KEY'} ) and defined( $ENV{$env_mode_prefix.'_SSL_CLIENT_CERT'} ) and defined( $ENV{$env_mode_prefix.'_SSL_CA_CERT'} ) ) { $mysql_ssl_mode .= ';mysql_ssl_client_key='.$ENV{$env_mode_prefix.'_SSL_CLIENT_KEY'}.';mysql_ssl_client_cert='.$ENV{$env_mode_prefix.'_SSL_CLIENT_CERT'}.';mysql_ssl_ca_file='.$ENV{$env_mode_prefix.'_SSL_CA_CERT'}; } } # Connection... my $dbh = DBI->connect("DBI:mysql:database=$database;host=$host;port=$port".$mysql_ssl_mode, $user, $password, \%params); unless($dbh) { &_log(521, 'database_connect', DBI->errstr); return undef; } $dbh->do("SET NAMES 'utf8'") if($dbh && $ENV{'OCS_OPT_UNICODE_SUPPORT'}); $dbh->do("SET sql_mode='NO_ENGINE_SUBSTITUTION'"); return $dbh; } sub _check_deviceid{ my $DeviceID = shift; # If we do not find it unless(defined($DeviceID)){ return(1); } # If it is not conform unless($DeviceID=~/^.+-\d{4}(?:-\d{2}){5}$/){ return(1); } 0; } sub _lock{ my $device = shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'} || shift; if($dbh->do('INSERT INTO locks(HARDWARE_ID, ID, SINCE) VALUES(?,?,NOW())', {} , $device, $$ )){ $Apache::Ocsinventory::CURRENT_CONTEXT{'LOCK_FL'} = 1 if $device eq ${Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}}; return(0); }else{ if( $ENV{'OCS_OPT_LOCK_REUSE_TIME'} ){ if( $dbh->do( 'SELECT * FROM locks WHERE HARDWARE_ID=? AND (UNIX_TIMESTAMP()-UNIX_TIMESTAMP(SINCE))>?', {}, $device, $ENV{'OCS_OPT_LOCK_REUSE_TIME'} ) != '0E0' ) { &_log(516,'lock', 'reuse_lock') if $ENV{'OCS_OPT_LOGLEVEL'}; if( $dbh->do('UPDATE locks SET ID=? WHERE HARDWARE_ID=?', {}, $$, $device) ){ $Apache::Ocsinventory::CURRENT_CONTEXT{'LOCK_FL'} = 1; return 0; } else{ &_log(516,'lock', 'failed') if $ENV{'OCS_OPT_LOGLEVEL'}; return 1; } } } return 1; } } sub _unlock{ my $device = shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'} || shift; if($dbh->do('DELETE FROM locks WHERE HARDWARE_ID=? AND ID=?', {}, $device, $$)){ $Apache::Ocsinventory::CURRENT_CONTEXT{'LOCK_FL'} = 0 if $device eq ${Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}}; return(0); }else{ return(1); } } sub _log{ my $code = shift; my $phase = shift; my $comment = shift; my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DEVICEID'}||'NA'; my $ipaddress = $Apache::Ocsinventory::CURRENT_CONTEXT{'IPADDRESS'}||'??'; our $LOG; if(!$LOG){ open LOG, '>>'.$ENV{'OCS_OPT_LOGPATH'}.'/activity.log' or die "Failed to open log file : $! ($ENV{'OCS_OPT_LOGPATH'})\n"; # We don't want buffer, so we always flush the handles select(LOG); $|=1; $LOG = \*LOG; } print $LOG localtime().";$$;$code;$DeviceID;$ipaddress;".&_get_http_header('User-agent',$Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}).";$phase;".($comment?$comment:"")."\n"; } # Subroutine called at the end of execution sub _end{ my $ret = shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $DeviceID = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; #Non-transactionnal table &_unlock($DeviceID) if $Apache::Ocsinventory::CURRENT_CONTEXT{'LOCK_FL'}; if( $ret==APACHE_SERVER_ERROR ){ &_log(515,'end', 'error') if $ENV{'OCS_OPT_LOGLEVEL'}; $dbh->rollback; } elsif( $ret eq APACHE_BAD_REQUEST ){ &_log(515,'end', 'bad_request') if $ENV{'OCS_OPT_LOGLEVEL'}; } else{ $dbh->commit; } close(our $LOG) && undef $LOG if defined $LOG; $dbh->disconnect; return $ret; } # Retrieve option request handler sub _modules_get_request_handler{ my $request = shift; my %search = ( 'REQUEST_NAME' => $request ); my @ret = &_modules_search(\%search, 'HANDLER_REQUEST'); return($ret[0]); } # Retrieve options with preinventory handler sub _modules_get_pre_inventory_options{ return(&_modules_search(undef, 'HANDLER_PRE_INVENTORY')); } # Retrieve options with postinventory handler sub _modules_get_post_inventory_options{ return(&_modules_search(undef, 'HANDLER_POST_INVENTORY')); } # Retrieve options with prolog_read sub _modules_get_prolog_readers{ return(&_modules_search(undef, 'HANDLER_PROLOG_READ')); } # Retrieve options with prolog_resp sub _modules_get_prolog_writers{ return(&_modules_search(undef, 'HANDLER_PROLOG_RESP')); } # Retrieve duplicate handlers sub _modules_get_duplicate_handlers{ return(&_modules_search(undef, 'HANDLER_DUPLICATE')); } # Read options structures sub _modules_search{ # Take a hash ref and return an array # The hash indicate the desire handler is the second arg my $search = shift; my $handler = shift; my @ret; my $count; my $module; my $search_key; my $module_key; for $module (@{$Apache::Ocsinventory::OPTIONS_STRUCTURE}){ $count = 0; if($search){ for $search_key (keys(%$search)){ if($search_key eq 'REQUEST_NAME'){ $count ++ if defined($module->{$search_key}) and ($module->{$search_key} eq $search->{$search_key}); }elsif($search_key eq 'TYPE'){ $count ++ if defined($module->{$search_key}) and ($module->{$search_key} == $search->{$search_key}); } } if($count == keys(%$search)){ push @ret, $module->{$handler} if $module->{$handler}; $count = 0; } }else{ push @ret, $module->{$handler} if $module->{$handler}; } } if(@ret){ return(@ret); }else{ return(0); } } sub _get_xml_parser_opt{ my $hash_ref = shift; $hash_ref->{'ParserOpts'} = [ NoLWP => 1 ]; # Prevent XXE (see CVE-2018-14473) $hash_ref->{'SuppressEmpty'} = 1; $hash_ref->{'ForceArray'} = []; @{$hash_ref->{'ForceArray'}} = &_get_xml_parser_opt_force_array(); } sub _get_xml_parser_opt_force_array{ my @ret; # Core push @ret, @{$Apache::Ocsinventory::Server::Inventory::XML_PARSER_OPT{'ForceArray'}}; # Options push @ret, @Apache::Ocsinventory::XMLParseOptForceArray; for my $module (@{$Apache::Ocsinventory::OPTIONS_STRUCTURE}){ push @ret, @{$module->{'XML_PARSER_OPT'}->{'ForceArray'}} if $module->{'XML_PARSER_OPT'}->{'ForceArray'}=~/ARRAY/; } return @ret; } # sub _send_file{ # We want to know if the file is available my $context = shift; my $request; my $row; my $r = $Apache::Ocsinventory::CURRENT_CONTEXT{'APACHE_OBJECT'}; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; if($context eq 'deploy'){ my $file = shift; $request=$dbh->prepare('SELECT CONTENT FROM deploy WHERE NAME=?'); $request->execute($file); # If not, we return a bad request and log the event unless($request->rows){ &_log(511,'deploy','no_file') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_BAD_REQUEST; }else{ # We extract the file and send it $row = $request->fetchrow_hashref(); # We force this content type to avoid the direct interpretation of, for example, a plain text file &_set_http_header('Cache-control' => $ENV{'OCS_OPT_PROXY_REVALIDATE_DELAY'},$r); &_set_http_header('Content-length' => length($row->{'CONTENT'}),$r); &_set_http_content_type('Application/octet-stream',$r); &_send_http_headers($r); $r->print($row->{'CONTENT'}); # We log it &_log(302,'deploy','file_transmitted') if $ENV{'OCS_OPT_LOGLEVEL'}; return APACHE_OK; } } } sub _get_spec_params{ my $hardwareId = $Apache::Ocsinventory::CURRENT_CONTEXT{'DATABASE_ID'}; return &_params_from_devices($hardwareId); } sub _get_spec_params_g{ my $groups = $Apache::Ocsinventory::CURRENT_CONTEXT{'MEMBER_OF'}; my %result; for(@$groups){ $result{$_} = {&_params_from_devices($_)} ; } return %result; } sub _params_from_devices{ my $hardwareId = shift; my $dbh = $Apache::Ocsinventory::CURRENT_CONTEXT{'DBI_HANDLE'}; my $sth; my $row; my %result; $sth = $dbh->prepare('SELECT NAME,IVALUE,TVALUE FROM devices WHERE HARDWARE_ID=?'); $sth->execute($hardwareId); while( $row = $sth->fetchrow_hashref()){ if(exists($result{ $row->{'NAME'} })){ if($result{ $row->{'NAME'} } =~ /ARRAY/){ push @{$result{$row->{'NAME'}}}, { 'IVALUE' => $row->{'IVALUE'}, 'TVALUE' => $row->{'TVALUE'} }; } else{ my $temp = $result{ $row->{'NAME'} }; $result{ $row->{'NAME'} } = []; push @{$result{$row->{'NAME'}}}, $temp; } } else{ $result{ $row->{'NAME'} } = { 'IVALUE' => $row->{'IVALUE'}, 'TVALUE' => $row->{'TVALUE'} }; } } return %result; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/System/000077500000000000000000000000001376436473200237645ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/System/Config.pm000066400000000000000000000335671376436473200255450ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::System::Config; use strict; require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / get_settings check_config %CONFIG CRITICAL IMPORTANT CANSKIP DEPRECATED /; use constant CRITICAL => 0; use constant IMPORTANT => 1; use constant CANSKIP => 2; use constant DEPRECATED=> 3; our %CONFIG = ( LOGPATH => { type => 'TVALUE', default => '/var/log/ocsinventory-server', unit => 'NA', description => 'Path to log directory (must be writeable)', level => CRITICAL, filter => qr '^(.+)$' }, FREQUENCY => { type => 'IVALUE', default => 0, unit => 'day', description => 'Specify the validity of inventory data', level => CRITICAL, filter => qr '^(-1|\d+)$' }, PROLOG_FREQ => { type => 'IVALUE', default => 12, unit => 'hour', description => 'Specify agent\'s prolog frequency', level => CRITICAL, filter => qr '^([1-9]\d*)$' }, INVENTORY_ON_STARTUP => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Launch inventory on agent service statup', level => IMPORTANT, filter => qr '^(1|0)$' }, DEPLOY => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable ocs engine to deliver agent\'s files (deprecated)', level => DEPRECATED, filter => qr '^(1|0)$' }, TRACE_DELETED => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable the history tracking system (useful for external data synchronisation', level => CANSKIP, filter => qr '^(1|0)$' }, AUTO_DUPLICATE_LVL => { type => 'IVALUE', default => 15, unit => 'NA', description => 'Configure the duplicates detection system', level => IMPORTANT, filter => qr '^(\d+)$' }, LOGLEVEL => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable engine logs (see LOGPATH setting)', level => IMPORTANT, filter => qr '^(1|0)$' }, INVENTORY_DIFF => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Configure engine to update inventory regarding to CHECKSUM agent value (lower DB backend load)', level => CRITICAL, filter => qr '^(1|0)$' }, INVENTORY_WRITE_DIFF => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Configure engine to make a differential update of inventory sections (row level). Lower DB backend load, higher frontend load', level => CRITICAL, filter => qr '^(1|0)$' }, INVENTORY_TRANSACTION => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Make engine consider an inventory as a transaction (lower concurency, better disk usage)', level => IMPORTANT, filter => qr '^(1|0)$' }, INVENTORY_CACHE_ENABLED => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Enable some stuff to improve DB queries, especially for GUI multicriteria searching system', level => IMPORTANT, filter => qr '^(1|0)$' }, INVENTORY_CACHE_REVALIDATE => { type => 'IVALUE', default => 7, unit => 'day', description => 'Specify when the engine will reset the inventory cache structures', level => CRITICAL, filter => qr '^(\d+)$' }, INVENTORY_CACHE_KEEP => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Specify if ou want to keep trace of every elements encountered in the db life', level => IMPORTANT, filter => qr '^(1|0)$' }, INVENTORY_FILTER_ENABLED => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable core filter system to modify some things "on the fly"', level => CANSKIP, filter => qr '^(1|0)$' }, INVENTORY_SESSION_ONLY => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Accept an inventory only if there is a prolog before', level => CANSKIP, filter => qr '^(1|0)$' }, PROXY_REVALIDATE_DELAY => { type => 'IVALUE', default => 3600, unit => '', description => 'Set the proxy cache validity in http headers when sending a file', level => DEPRECATED, filter => qr '^(\d+)$' }, LOCK_REUSE_TIME => { type => 'IVALUE', default => 600, unit => 'second', description => 'Validity of a computer\'s lock', level => CANSKIP, filter => qr '^(\d+)$' }, ENABLE_GROUPS => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Enable the computer\s groups feature', level => IMPORTANT, filter => qr '^(1|0)$' }, GROUPS_CACHE_REVALIDATE => { type => 'IVALUE', default => 43200, unit => 'second', description => 'Specify the validity of computer\'s groups (default: compute it once a day - see offset)', level => CRITICAL, filter => qr '^(\d+)$' }, GROUPS_CACHE_OFFSET => { type => 'IVALUE', default => 43200, unit => 'second', description => 'Random number computed in the defined range. Designed to avoid computing many groups in the same process', level => CRITICAL, filter => qr '^(\d+)$' }, GENERATE_OCS_FILES => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Use with ocsinventory-injector, enable the multi entities feature', level => IMPORTANT, filter => qr '^(1|0)$' }, OCS_FILES_OVERWRITE => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Specify if you want to keep trace of all inventory between to synchronisation with the higher level server', level => IMPORTANT, filter => qr '^(1|0)$' }, OCS_FILES_PATH => { type => 'TVALUE', default => '/tmp', unit => 'NA', description => 'Path to ocs files directory (must be writeable)', level => IMPORTANT, filter => qr '^(.+)$' }, OCS_FILES_FORMAT => { type => 'TVALUE', default => 'OCS', unit => 'NA', description => 'Generate either compressed file or clear XML text', level => IMPORTANT, filter => qr '^(OCS|XML)$' }, SECURITY_LEVEL => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Futur security improvements', level => CANSKIP, filter => qr '^(\d+)$' }, IPDISCOVER => { type => 'IVALUE', default => 2, unit => 'NA', description => 'Specify how much agent per LAN will discovered connected peripherals (0 to disable)', level => CRITICAL, filter => qr '^(\d+)$' }, IPDISCOVER_MAX_ALIVE => { type => 'IVALUE', default => 14, unit => 'day', description => 'Specify when to remove a computer when it has not come until this period', level => CANSKIP, filter => qr '^([1-9]\d*)$' }, IPDISCOVER_BETTER_THRESHOLD => { type => 'IVALUE', default => 1, unit => 'day', description => 'Specify the minimal difference to replace an ipdiscover agent', level => IMPORTANT, filter => qr '^(\d+(?:,\d+)?)$' }, IPDISCOVER_LATENCY => { type => 'IVALUE', default => 100, unit => 'millisecond', description => 'Time between 2 arp requests (mini: 10 ms)', level => CRITICAL, filter => qr '^([1-9]\d+)$' }, IPDISCOVER_USE_GROUPS => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Enable groups for ipdiscover (for example, you might want to prevent some groups to be ipdiscover agents)', level => IMPORTANT, filter => qr '^(1|0)$' }, IPDISCOVER_NO_POSTPONE => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Disable the time before a first election (not recommended)', level => CANSKIP, filter => qr '^(1|0)$' }, IPDISCOVER_LINK_TAG_NETWORK => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Link Ipdiscover network to computer TAG', level => CANSKIP, filter => qr '^(1|0)$' }, REGISTRY => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Enable the registry capacity', level => IMPORTANT, filter => qr '^(1|0)$' }, UPDATE => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Deprecated', level => DEPRECATED, filter => qr '^(1|0)$' }, DOWNLOAD => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable the softwares deployment capacity (bandwidth control)', level => CRITICAL, filter => qr '^(1|0)$' }, DOWNLOAD_FRAG_LATENCY => { type => 'IVALUE', default => 60, unit => 'second', description => 'Time between two fragment downloads (bandwidth control)', level => CRITICAL, filter => qr '^([1-9]\d*)$' }, DOWNLOAD_CYCLE_LATENCY => { type => 'IVALUE', default => 60, unit => 'second', description => 'Time between two download cycles (bandwidth control)', level => CRITICAL, filter => qr '^(\d+)$' }, DOWNLOAD_PERIOD_LATENCY => { type => 'IVALUE', default => 60, unit => 'second', description => 'Time between two download periods (bandwidth control)', level => CRITICAL, filter => qr '^(\d+)$' }, DOWNLOAD_TIMEOUT => { type => 'IVALUE', default => 7, unit => 'day', description => 'Agents will send ERR_TIMEOUT event and clean the package it is older than this setting', level => IMPORTANT, filter => qr '^([1-9]\d*)$' }, DOWNLOAD_EXECUTION_TIMEOUT => { type => 'IVALUE', default => 120, unit => 'minute', description => 'Agents will send an error event and clean the package if package command does not respond during this setting', level => IMPORTANT, filter => qr '^([1-9]\d*)$' }, DOWNLOAD_GROUPS_TRACE_EVENTS => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Specify if you want to track packages affected to a group on computer\'s level', level => IMPORTANT, filter => qr '^(1|0)$' }, DOWNLOAD_PERIOD_LENGTH => { type => 'IVALUE', default => 10, unit => 'cycle', description => 'Specify the number of cycle within a period', level => IMPORTANT, filter => qr '^([1-9]\d*)$' }, PROLOG_FILTER_ON => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable prolog filter stack', level => CANSKIP, filter => qr '^(1|0)$' }, INVENTORY_FILTER_ON => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable inventory filter stack', level => CANSKIP, filter => qr '^(1|0)$' }, INVENTORY_FILTER_FLOOD_IP => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Enable inventory flooding filter. A dedicated ipaddress ia allowed to send a new computer only once in this period', level => CANSKIP, filter => qr '^(1|0)$' }, INVENTORY_FILTER_FLOOD_IP_CACHE_TIME => { type => 'IVALUE', default => 300, unit => 'second', description => 'Period definition for INVENTORY_FILTER_FLOOD_IP', level => CANSKIP, filter => qr '^(\d+)$' }, SESSION_VALIDITY_TIME => { type => 'IVALUE', default => 3600, unit => 'second', description => 'Set the validity of a session (prolog => end)', level => CANSKIP, filter => qr '^(\d+)$' }, SESSION_CLEAN_TIME => { type => 'IVALUE', default => 86400, unit => 'second', description => 'Clean old sessions every <> seconds', level => CANSKIP, filter => qr '^(\d+)$' }, COMPRESS_TRY_OTHERS => { type => 'IVALUE', default => 0, unit => 'NA', description => 'Configure engine to try other compress algorithm than raw zlib', level => CANSKIP, filter => qr '^(1|0)$' }, SNMP => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Activate SNMP scans feature', level => IMPORTANT, filter => qr '^(1|0)$' }, SNMP_INVENTORY_DIFF => { type => 'IVALUE', default => 1, unit => 'NA', description => 'Configure engine to update snmp inventory regarding to snmp_laststate table (lower DB backend load)', level => IMPORTANT, filter => qr '^(1|0)$' }, ); sub get_settings{ my $realName = shift; if($realName){ my @ret; push @ret, "OCS_OPT_$_" for keys %CONFIG; return sort @ret; } else{ return sort keys %CONFIG; } } sub check_config{ my $verbose = shift; for my $name ( keys( %CONFIG ) ){ my $truename = 'OCS_OPT_'.$name; if( !defined($ENV{$truename}) ){ print STDERR "ocsinventory-server: Bad setting. `$name` is not set. Default: `$CONFIG{$name}->{default}`\n"; $ENV{$truename} = $CONFIG{$name}->{default}; } elsif( $ENV{$truename} !~ $CONFIG{$name}->{filter} ){ print STDERR "ocsinventory-server: Bad setting. `$name` is set to `$ENV{$truename}`. Default: `$CONFIG{$name}->{default}`\n"; $ENV{$truename} = $CONFIG{$name}->{default}; } else{ print "ocsinventory-server: Parameter `$truename` is ok\n" if $verbose; } } return undef; } 1; OCSInventory-Server-2.8.1/Apache/Ocsinventory/Server/Useragent.pm000066400000000000000000000103531376436473200247750ustar00rootroot00000000000000############################################################################### ## Copyright 2005-2016 OCSInventory-NG/OCSInventory-Server contributors. ## See the Contributors file for more details about them. ## ## This file is part of OCSInventory-NG/OCSInventory-ocsreports. ## ## OCSInventory-NG/OCSInventory-Server is free software: you can redistribute ## it and/or modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation, either version 2 of the License, ## or (at your option) any later version. ## ## OCSInventory-NG/OCSInventory-Server is distributed in the hope 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 OCSInventory-NG/OCSInventory-ocsreports. if not, write to the ## Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA. ################################################################################ package Apache::Ocsinventory::Server::Useragent; use strict; # This block specify which wrapper will be used ( your module will be compliant with all mod_perl versions ) BEGIN{ if($ENV{'OCS_MODPERL_VERSION'} == 1){ require Apache::Ocsinventory::Server::Modperl1; Apache::Ocsinventory::Server::Modperl1->import(); }elsif($ENV{'OCS_MODPERL_VERSION'} == 2){ require Apache::Ocsinventory::Server::Modperl2; Apache::Ocsinventory::Server::Modperl2->import(); } } require Exporter; our @ISA = qw /Exporter/; our @EXPORT = qw / _get_useragent /; # These are the core modules you must include in addition use Apache::Ocsinventory::Server::System; use Apache::Ocsinventory::Server::Communication; use Apache::Ocsinventory::Server::Constants; # Initialize option push @{$Apache::Ocsinventory::OPTIONS_STRUCTURE},{ 'NAME' => 'USERAGENT', 'HANDLER_PROLOG_READ' => \&useragent_prolog_read, 'HANDLER_PROLOG_RESP' => undef, 'HANDLER_PRE_INVENTORY' => undef, 'HANDLER_POST_INVENTORY' => undef, 'REQUEST_NAME' => undef, 'HANDLER_REQUEST' => undef, 'HANDLER_DUPLICATE' => undef, 'TYPE' => OPTION_TYPE_SYNC, 'XML_PARSER_OPT' => { 'ForceArray' => ['xml_tag'] } }; #Special hash to define allowed agents to content to OCS server my %ocsagents = ( 'OCS-NG_unified_unix_agent' => undef, 'OCS-NG_windows_client' => [4032,4062], 'OCS-NG_WINDOWS_AGENT' => undef, 'OCS-NG_windows_mobile_agent' => undef, 'OCS-NG_iOS_agent' => undef, 'OCS-NG_Android_agent' => undef, ); sub useragent_prolog_read{ my $current_context=shift; my $stop = 1; #We stop PROLOG by default my $srvver = $Apache::Ocsinventory::VERSION; my $useragent= &_get_useragent; if (grep /^($useragent->{'NAME'})$/, keys %ocsagents) { $useragent->{'VERSION'} =~ s/(\d)\.(\d)(.*)/$1\.$2/g; unless ($ocsagents{$useragent->{NAME}}) { #If no version specifed in hash if ($useragent->{'VERSION'} <= $srvver) { $stop=0; } } elsif ($useragent->{'VERSION'} >= $ocsagents{$useragent->{'NAME'}}[0] && $useragent->{'VERSION'} <= $ocsagents{$useragent->{'NAME'}}[1]) { #For old windows agent versions compatibility $stop= 0; } } #If external references file exists if ($ENV{'OCS_OPT_EXT_USERAGENTS_FILE_PATH'} && -f $ENV{'OCS_OPT_EXT_USERAGENTS_FILE_PATH'}) { open(FILE, $ENV{'OCS_OPT_EXT_USERAGENTS_FILE_PATH'}) or die "Cannot open $ENV{'OCS_OPT_EXT_USERAGENTS_FILE_PATH'} file !!"; my @ext_useragents = ; chomp @ext_useragents; close FILE; #Removing comments lines @ext_useragents = grep { !/^\#/ } @ext_useragents; $stop = 0 if (grep(/^$Apache::Ocsinventory::CURRENT_CONTEXT{'USER_AGENT'}$/, @ext_useragents)); } #Does we have to stop PROLOG ? if ($stop) { &_log(400,'useragent','Bad agent or agent version too recent for server !!') if $ENV{'OCS_OPT_LOGLEVEL'}; return BAD_USERAGENT; } else { return PROLOG_CONTINUE; } } sub _get_useragent { my $useragent = {}; $Apache::Ocsinventory::CURRENT_CONTEXT{'USER_AGENT'} =~ m/(.*)_v(.*)$/; $useragent->{'NAME'} = $1; $useragent->{'VERSION'} = $2; return $useragent; } 1; OCSInventory-Server-2.8.1/Api/000077500000000000000000000000001376436473200160605ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/000077500000000000000000000000001376436473200205625ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/000077500000000000000000000000001376436473200221715ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/ApiCommon.pm000077500000000000000000000167731376436473200244320ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::ApiCommon; # For dev purpose only # use lib "/usr/local/share/OCSInventory-Server/"; # use Data::Dumper; # External imports use DBI; use Switch; use Mojo::JSON qw(decode_json encode_json); # Basics use for Common Sub use Apache::Ocsinventory::Map; use Apache::Ocsinventory::Server::Constants; use Apache::Ocsinventory::Interface::Database; use Apache::Ocsinventory::Interface::Internals; # Connect api to ocs database sub api_database_connect{ my $dbHost; my $dbName; my $dbPort; my $dbUser; my $dbPwd; my $dbSslEnabled; my $dbSslClientCert; my $dbSslClientKey; my $dbSslCaCert; my $dbSslMode; # Retrieve env var $dbHost = $ENV{'OCS_DB_HOST'}; $dbName = $ENV{'OCS_DB_NAME'}||'ocsweb'; $dbPort = $ENV{'OCS_DB_PORT'}||'3306'; $dbUser = $ENV{'OCS_DB_USER'}; $dbPwd = $ENV{'OCS_DB_PWD'}; $dbSslEnabled = $ENV{'OCS_DB_SSL_ENABLED'} || 0; $dbSslClientKey = $ENV{'OCS_DB_SSL_CLIENT_KEY'}; $dbSslClientCert = $ENV{'OCS_DB_SSL_CLIENT_CERT'}; $dbSslCaCert = $ENV{'OCS_DB_SSL_CA_CERT'}; $dbSslMode = $ENV{'OCS_DB_SSL_MODE'} || 'SSL_MODE_PREFERRED'; my $sslMode = ''; if( $dbSslEnabled == 1 ) { if( $dbSslMode eq 'SSL_MODE_PREFERRED' ) { $sslMode = ';mysql_ssl=1;mysql_ssl_optional=1'; } elsif( $dbSslMode eq 'SSL_MODE_REQUIRED' ) { $sslMode = ';mysql_ssl=1;mysql_ssl_verify_server_cert=0'; } elsif( $dbSslMode eq 'SSL_MODE_STRICT' ) { $sslMode = ';mysql_ssl=1;mysql_ssl_verify_server_cert=1'; } else { $sslMode = ';mysql_ssl=1;mysql_ssl_optional=1'; } } if( defined( $dbSslClientKey ) and defined( $dbSslClientCert ) and defined( $dbSslCaCert ) ) { $sslMode .= ';mysql_ssl_client_key='.$dbSslClientKey.';mysql_ssl_client_cert='.$dbSslClientCert.';mysql_ssl_ca_file='.$dbSslCaCert; } # Connection... my $dbh = DBI->connect( "DBI:mysql:database=$dbName;host=$dbHost;port=$dbPort".$sslMode, $dbUser, $dbPwd, {RaiseError => 1, mysql_enable_utf8 => 1}) or die $DBI::errstr; return $dbh; } # Depending on input code, return error code sub error_return{ my ($err_code) = @_; # Switch depending on the error code switch ($err_code) { case 001 { print "Arguments missing" } case 002 { print "Arguments not valid" } case 003 { print "Function arguments not valid ..." } case 004 { print "Arguments ..." } else { print "Unknown error" } } } # Generate query based on datamap depending on computer id sub generate_item_datamap_json{ my ($item_type, $computer_id, $json_string, $specific_map, $where, $operator, $values) = @_; my $map_type; my $query_data; # Iterate on datamap while ( ($key, $value) = each %DATA_MAP ) { $map_type = "computer"; my $snmp_check = substr $key, 0, 4; if($snmp_check eq "snmp"){ $map_type = "snmp"; } # IF specific map key provided if($specific_map eq "" || $key eq $specific_map){ if($key ne "hardware" && $key ne "snmp"){ if( $map_type eq "snmp" && $item_type eq "snmp"){ # SNMP query processing $query_data = get_item_table_informations($key, $computer_id, "SNMP_ID"); $$json_string{"$computer_id"}{"$key"} = $query_data; }elsif($map_type eq "computer" && $item_type eq "computer"){ # COMPUTER query processing $query_data = get_item_table_informations($key, $computer_id, "HARDWARE_ID", $where, $operator, $values); $$json_string{"$computer_id"}{"$key"} = $query_data; } } } } return $json_string; } # Generate query based on software depending on computer id sub generate_item_software_json{ my ($item_type, $computer_id, $json_string, $specific_map, $where, $operator, $value) = @_; my $query_data; my $database = api_database_connect(); my @args = (); $query_data = "SELECT *, c.CATEGORY_NAME as CATEGORY, n.NAME, p.PUBLISHER, v.VERSION FROM software s LEFT JOIN software_name n ON s.NAME_ID = n.ID LEFT JOIN software_publisher p ON s.PUBLISHER_ID = p.ID LEFT JOIN software_version v ON s.VERSION_ID = v.ID LEFT JOIN software_categories c ON n.CATEGORY = c.ID WHERE HARDWARE_ID = ?"; @args = ($computer_id); if($where ne "" && $operator ne "" && $value ne "") { if($operator == "like" || $operator == "not like") { $value = "%$value%"; } $query_data .= " AND $where $operator ?"; push @args, $value; } my $items = $database->selectall_arrayref( $query_data, { Slice => {} }, @args ); $$json_string{"$computer_id"}{"softwares"} = $items; return $json_string; } # Return table item data sub get_item_table_informations{ my ($table_name, $condition, $ref_column, $where, $operator, $value) = @_; my $database = api_database_connect(); my $query_data; my @args = (); $query_data = "SELECT * FROM $table_name WHERE $ref_column = ?"; push @args, $condition; if($where ne "" && $operator ne "" && $value ne "") { if($operator == "like" || $operator == "not like") { $value = "%$value%"; } $query_data .= " AND $where $operator ?"; push @args, $value; } my $items = $database->selectall_arrayref( $query_data, { Slice => {} }, @args ); return $items; } # Get computers / snmp base informations sub get_item_main_table_informations{ my ($limit, $start, $item_type) = @_; my $items; my $database = api_database_connect(); if($item_type eq "computer"){ $item_type = "hardware"; }elsif($item_type eq "snmp"){ $item_type = "snmp"; }else{ return error_return(003); } $start =~ s/\D//g; $limit =~ s/\D//g; if($limit > 0 && $start >= 0){ $items = $database->selectall_arrayref( "SELECT * from $item_type LIMIT $limit OFFSET $start", { Slice => {} } ); }else{ # error handling here error_return(001); } return $items; } sub execute_custom_request{ my ($query, $start, $limit, @args) = @_; my $database = api_database_connect(); if($start ne "" && $limit ne ""){ $start =~ s/\D//g; $limit =~ s/\D//g; $query .= "LIMIT $limit OFFSET $start"; } my $sth = $database->prepare($query); if(@args ne ""){ $sth->execute( @args ); }else{ $sth->execute(); } return $sth->fetchall_arrayref(); } # Format search depending on url parmeters # ATM : only on main hardware table sub format_query_for_computer_search{ my (@args_array) = @_; my $query_string = "SELECT ID from hardware WHERE"; my @args; my $start = ""; my $limit = ""; foreach my $hash_ref (@args_array) { foreach (keys %{$hash_ref}) { if(lc($_) eq "limit"){ $limit = ${$hash_ref}{$_}; }elsif (lc($_) eq "start"){ $start = ${$hash_ref}{$_}; }else{ $field_name = $_; $field_name =~ tr/a-zA-Z//dc ; $query_string .= " $field_name = ? AND"; push @args, ${$hash_ref}{$_}; } } } $query_string = substr($query_string, 0, -3); return execute_custom_request($query_string, $start, $limit, @args); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/000077500000000000000000000000001376436473200237675ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/Get/000077500000000000000000000000001376436473200245065ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/Get/ComputerId.pm000066400000000000000000000015161376436473200271220ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Computer::Get::ComputerId; =for comment This function return a computer from his ID =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_computer { my ($id) = @_; my $computers = Api::Ocsinventory::Restapi::ApiCommon::get_item_table_informations("hardware", $id, "id"); my $json_return; foreach my $computer ( @$computers ) { $$json_return{"$computer->{ID}"}{"hardware"} = $computer; $json_return = Api::Ocsinventory::Restapi::ApiCommon::generate_item_datamap_json("computer", $computer->{ID}, $json_return, ""); $json_return = Api::Ocsinventory::Restapi::ApiCommon::generate_item_software_json("computer", $computer->{ID}, $json_return, ""); } return encode_json($json_return); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/Get/ComputerIdField.pm000066400000000000000000000020211376436473200300560ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Computer::Get::ComputerIdField; =for comment This function return a computer field from his ID and field =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_computer_field { my ($id, $field, $where, $operator, $value) = @_; my $computers = Api::Ocsinventory::Restapi::ApiCommon::get_item_table_informations("hardware", $id, "id"); my $json_return; foreach my $computer ( @$computers ) { $$json_return{"$computer->{ID}"}{"hardware"} = $computer; if($field eq "softwares") { $json_return = Api::Ocsinventory::Restapi::ApiCommon::generate_item_software_json("computer", $computer->{ID}, $json_return, $field, $where, $operator, $value); } else { $json_return = Api::Ocsinventory::Restapi::ApiCommon::generate_item_datamap_json("computer", $computer->{ID}, $json_return, $field, $where, $operator, $value); } } return encode_json($json_return); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/Get/Computers.pm000066400000000000000000000013661376436473200270330ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Computer::Get::Computers; =for comment This function return a array of multiple computers Params: start, limit =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_computers { my ($limit, $start) = @_; my $json_return; my $computers = Api::Ocsinventory::Restapi::ApiCommon::get_item_main_table_informations($limit, $start, "computer"); foreach my $computer ( @$computers ) { $$json_return{"$computer->{ID}"}{"hardware"} = $computer; $json_return = Api::Ocsinventory::Restapi::ApiCommon::generate_item_datamap_json("computer", $computer->{ID}, $json_return, ""); } return encode_json($json_return); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/Get/ComputersListId.pm000066400000000000000000000010361376436473200301360ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Computer::Get::ComputersListId; =for comment This function return a array of multiple computers ID Params: start, limit =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_computers_id { my $database = Api::Ocsinventory::Restapi::ApiCommon::api_database_connect(); my $computers = $database->selectall_arrayref( "select ID from hardware", { Slice => {} } ); return encode_json($computers); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Computer/Get/ComputersSearch.pm000066400000000000000000000011211376436473200301460ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Computer::Get::ComputersSearch; =for comment This function return a array of multiple computers ID depending on search params Params: table.fieldname = value =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_computers_search { my $database = Api::Ocsinventory::Restapi::ApiCommon::api_database_connect(); my ($url_params) = @_; my $query = Api::Ocsinventory::Restapi::ApiCommon::format_query_for_computer_search($url_params); return encode_json($query); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Ipdiscover/000077500000000000000000000000001376436473200243005ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Ipdiscover/Get/000077500000000000000000000000001376436473200250175ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Ipdiscover/Get/Ipdiscover.pm000066400000000000000000000010601376436473200274610ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Ipdiscover::Get::Ipdiscover; =for comment This function return a array of multiple IPDiscover network Params: start, limit =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_ipdiscovers{ my ($start, $limit) = @_; my $json_return; my $query = "SELECT NETID FROM `netmap` GROUP BY NETID"; my $netmaps = Api::Ocsinventory::Restapi::ApiCommon::execute_custom_request($query, $start, $limit); return encode_json($netmaps); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Ipdiscover/Get/IpdiscoverNetwork.pm000066400000000000000000000012101376436473200310300ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Ipdiscover::Get::IpdiscoverNetwork; =for comment This function return a IPDiscover object from network =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_ipdiscover_network{ my ($network) = @_; my $json_return; my $database = Api::Ocsinventory::Restapi::ApiCommon::api_database_connect(); my $query = "SELECT * FROM `netmap` WHERE NETID = ? "; my @args = ($network); my $netmaps = Api::Ocsinventory::Restapi::ApiCommon::execute_custom_request($query, "", "", @args); return encode_json($json_return); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Ipdiscover/Get/IpdiscoverTag.pm000066400000000000000000000011331376436473200301160ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Ipdiscover::Get::IpdiscoverTag; =for comment This function return a IPDiscover object from tag =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_ipdiscover_tag{ my ($tag) = @_; my $json_return; my $database = Api::Ocsinventory::Restapi::ApiCommon::api_database_connect(); my $json_return = $database->selectall_arrayref( "SELECT * from netmap WHERE TAG = '$tag'", { Slice => {} } ); return encode_json($json_return); } 1;OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Loader.pm000077500000000000000000000101171376436473200237400ustar00rootroot00000000000000package Api::Ocsinventory::Restapi; # For dev purpose only # use lib "/usr/local/share/OCSInventory-Server/"; # use Data::Dumper; # Framework uses use Mojolicious::Lite; # Common sub for api require Api::Ocsinventory::Restapi::ApiCommon; ## Computer section require Api::Ocsinventory::Restapi::Computer::Get::ComputerId; # Get specific Computer informations require Api::Ocsinventory::Restapi::Computer::Get::ComputerIdField; # Get specific field of Computer require Api::Ocsinventory::Restapi::Computer::Get::Computers; # Get list of Computers require Api::Ocsinventory::Restapi::Computer::Get::ComputersListId; # Get list of Computers ID require Api::Ocsinventory::Restapi::Computer::Get::ComputersSearch; # Get list of ID depending on search ## IPDiscover section require Api::Ocsinventory::Restapi::Ipdiscover::Get::Ipdiscover; require Api::Ocsinventory::Restapi::Ipdiscover::Get::IpdiscoverNetwork; require Api::Ocsinventory::Restapi::Ipdiscover::Get::IpdiscoverTag; ## SNMP section require Api::Ocsinventory::Restapi::Snmp::Get::SnmpId; # Get specific Snmp type informations require Api::Ocsinventory::Restapi::Snmp::Get::SnmpIdField; # Get specific information by id of Snmp type require Api::Ocsinventory::Restapi::Snmp::Get::SnmpListId; # Get list of Snmp Type ## Routes get '/v1/computers/listID' => sub { my $c = shift; $c->render(format => 'json', text => Api::Ocsinventory::Restapi::Computer::Get::ComputersListId::get_computers_id()); }; get '/v1/computer/:id' => sub { my $c = shift; my $id = $c->stash('id'); $c->render(format => 'json', text => Api::Ocsinventory::Restapi::Computer::Get::ComputerId::get_computer($id)); }; get '/v1/computer/:id/:field' => sub { my $c = shift; my $id = $c->stash('id'); my $field = $c->stash('field'); my $where = $c->param('where')|| ""; my $operator = $c->param('operator')|| ""; my $value = $c->param('value')|| ""; $c->render(json => Api::Ocsinventory::Restapi::Computer::Get::ComputerIdField::get_computer_field($id, $field, $where, $operator, $value)); }; get '/v1/computers' => sub { my $c = shift; my $id = $c->stash('id'); my $start = $c->param('start')||0; my $limit = $c->param('limit')||0; $c->render(format => 'json', text => Api::Ocsinventory::Restapi::Computer::Get::Computers::get_computers($limit, $start)); }; get '/v1/computers/search' => sub { my $c = shift; my $params_hash = $c->req->params->to_hash; $c->render(format => 'json', text => Api::Ocsinventory::Restapi::Computer::Get::ComputersSearch::get_computers_search($params_hash)); }; get '/v1/ipdiscover' => sub { my $c = shift; my $start = $c->param('start')||0; my $limit = $c->param('limit')||0; $c->render(format => 'json', text => Api::Ocsinventory::Restapi::Ipdiscover::Get::Ipdiscover::get_ipdiscovers($start, $limit)); }; get '/v1/ipdiscover/tag/:tag' => sub { my $c = shift; my $tag = $c->stash('tag'); $c->render(json => Api::Ocsinventory::Restapi::Ipdiscover::Get::IpdiscoverTag::get_ipdiscover_tag($tag)); }; get '/v1/ipdiscover/network/#network' => sub { my $c = shift; my $network = $c->stash('network'); $c->render(format => 'json', text => Api::Ocsinventory::Restapi::Ipdiscover::Get::IpdiscoverNetwork::get_ipdiscover_network($network)); }; get '/v1/snmps/typeList' => sub { my $c = shift; $c->render(json => Api::Ocsinventory::Restapi::Snmp::Get::SnmpListId::get_snmps_id()); }; get '/v1/snmp/:type' => sub { my $c = shift; my $type = $c->stash('type'); my $start = $c->param('start')||0; my $limit = $c->param('limit')||0; $c->render(json => Api::Ocsinventory::Restapi::Snmp::Get::SnmpId::get_snmp_id($type, $start, $limit)); }; get '/v1/snmp/:type/:id' => sub { my $c = shift; my $type = $c->stash('type'); my $id = $c->stash('id'); $c->render(json => Api::Ocsinventory::Restapi::Snmp::Get::SnmpIdField::get_snmp_field($type, $id)); }; app->start; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/README.md000066400000000000000000000001331376436473200234450ustar00rootroot00000000000000Prerequisites : Apache::DBI Mojo::Json Mojolicious::Lite Swagger Mojolicious Plack Switch OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/References/000077500000000000000000000000001376436473200242525ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/References/api.json000066400000000000000000000033501376436473200257170ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "OCSInventory API", "description": "Get informations about OCSInventory server", "version": "1.0.0" }, "host": "ocsinventory.server", "schemes": [ "https" ], "basePath": "/v1", "produces": [ "application/json" ], "paths": { "/computer/{id}": { "get": { "x-mojo-controller": {"controller": "Computer", "action": "test"}, "summary": "Get One computer information", "description": "Return Computer object with all information\n", "parameters": [ { "name": "id", "in": "path", "description": "ID of Computer", "required": true, "type": "number", "format": "int" } ], "tags": [ "Computers" ], "responses": { "200": { "description": "An Computer object", "schema": { "$ref": "#/definitions/Computer" } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/Error" } } } } } }, "definitions": { "Computer": { "type": "object", "properties": { "id": { "type": "integer", "format": "int", "description": "Computer ID" }, "tag": { "type": "string", "description": "Computer Administrativ TAG" } } }, "Error": { "type": "object", "properties": { "code": { "type": "integer", "format": "int" }, "message": { "type": "string" } } } } }OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Snmp/000077500000000000000000000000001376436473200231065ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Snmp/Get/000077500000000000000000000000001376436473200236255ustar00rootroot00000000000000OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Snmp/Get/SnmpId.pm000066400000000000000000000007631376436473200253630ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Snmp::Get::SnmpId; =for comment This function return a snmp from his ID =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_snmp_id { my ($type, $start, $limit) = @_; my $json_return; my $query = "SELECT * from $type "; my $json_return = Api::Ocsinventory::Restapi::ApiCommon::execute_custom_request($query, $start, $limit); return encode_json($json_return); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Snmp/Get/SnmpIdField.pm000066400000000000000000000010361376436473200263210ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Snmp::Get::SnmpIdField; =for comment This function return a snmp field from his ID and field =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_snmp_field { my ($type, $id) = @_; my $database = Api::Ocsinventory::Restapi::ApiCommon::api_database_connect(); my $snmps = $database->selectall_arrayref( "SELECT * from $type WHERE ID = $id", { Slice => {} } ); return encode_json($snmps); } 1; OCSInventory-Server-2.8.1/Api/Ocsinventory/Restapi/Snmp/Get/SnmpListId.pm000066400000000000000000000010101376436473200262010ustar00rootroot00000000000000package Api::Ocsinventory::Restapi::Snmp::Get::SnmpListId; =for comment This function return a array of multiple snmp Types Params: start, limit =cut # Common sub for api use Api::Ocsinventory::Restapi::ApiCommon; use Mojo::JSON qw(decode_json encode_json); sub get_snmps_id { my $database = Api::Ocsinventory::Restapi::ApiCommon::api_database_connect(); my $snmps = $database->selectall_arrayref( "SELECT * from snmp_types", { Slice => {} } ); return encode_json($snmps); } 1; OCSInventory-Server-2.8.1/INSTALL000066400000000000000000000011401376436473200163740ustar00rootroot00000000000000In order to install OCS 2.4 the following requirement are needed : - Mod_Perl - Make - GCC - mysql-server - apache2 - php - php-mysql - php-gd - php-xml - php-mbstring - php-curl - libxml-simple-perl - libdbi-perl - libdbd-mysql-perl - libapache-dbi-perl - libnet-ip-perl - php-pclzip - libarchive-zip-perl (providing Archive::Zip) - libxml-simple-perl (providing XML:Entities) - libnet-ip-perl (providing NET::IP) - libapache-dbi-perl (providing Apache::DBI) Run "setup.sh" and follow the instructions. If you get a error / warning because of a missing module, install it and retry. OCSInventory-Server-2.8.1/LICENSE000066400000000000000000000431031376436473200163550ustar00rootroot00000000000000 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. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively 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 program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, 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. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. OCSInventory-Server-2.8.1/README.md000066400000000000000000000061271376436473200166340ustar00rootroot00000000000000

Banner

[![Build Status](https://travis-ci.com/OCSInventory-NG/OCSInventory-Server.svg?branch=master)](https://travis-ci.com/OCSInventory-NG/OCSInventory-Server)

OCS Inventory

Some Links:
Ask question | Installation | Website | OCS Professional

OCS (Open Computers and Software Inventory Next Generation) is an assets management and deployment solution. Since 2001, OCS Inventory NG has been looking for making software and hardware more powerful. OCS Inventory NG asks its agents to know the software and hardware composition of every computer or server.

Assets management

Since 2001, OCS Inventory NG has been looking for making software and hardware more powerful. OCS Inventory NG asks its agents to know the software and hardware composition of every computer or server. OCS Inventory also ask to discover network’s elements which can’t receive an agent. Since the version 2.0, OCS Inventory NG take in charge the SNMP scans functionality. This functionality’s main goal is to complete the data retrieved from the IP Discover scan. These SNMP scans will allow you to add a lot more informations from your network devices : printers, scanner, routers, computer without agents, …

Deployment

OCS Inventory NG includes the packet deployment functionality to be sure that all of the softwares environments which are on the network are the same. From the central management server, you can send the packets which will be downloaded with HTTP/HTTPS and launched by the agent on client’s computer. The OCS deployment is configured to make the packets less impactable on the network. OCS is used as a deployment tool on IT stock of more 100 000 devices.


## Requirements For the requirements, please follow the OCS Inventory documentation : http://wiki.ocsinventory-ng.org/01.Prerequisites/Libraries-version/ ## Installation To install OCSInventory server simply run the setup script ```bash sh setup.sh ``` If you want to install webconsole OCS Reports you need to fork OCSInventory-ocsreports as ocsreports ```bash git clone https://github.com/OCSInventory-NG/OCSInventory-ocsreports.git ocsreports ``` For more informations, please follow the OCS Inventory documentation : http://wiki.ocsinventory-ng.org/02.Basic-documentation/Setting-up-a-OCS-Inventory-Server/ ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Add your changes: `git add folder/file1.php` 4. Commit your changes: `git commit -m 'Add some feature'` 5. Push to the branch: `git push origin my-new-feature` 6. Submit a pull request ! ## License OCS Inventory is GPLv2 licensed OCSInventory-Server-2.8.1/binutils/000077500000000000000000000000001376436473200172005ustar00rootroot00000000000000OCSInventory-Server-2.8.1/binutils/create-release-tarball.sh000077500000000000000000000034251376436473200240430ustar00rootroot00000000000000#!/bin/sh set -e # Branch name (first args) BRANCH=$1 # Release name (second args) RELEASE_NAME=$2 # URL to the ocs server git repository SRV_REPO=https://github.com/OCSInventory-NG/OCSInventory-Server.git # URL to the ocs reports git repository WEB_REPO=https://github.com/OCSInventory-NG/OCSInventory-OCSReports.git # Composer path COMPOSER_PATH=/usr/bin/composer # If no branch is supplied exit if [ -z $BRANCH ]; then echo "Please set a source branch (first argument)" exit 1 fi if [ -z $RELEASE_NAME ]; then echo "Please set a release name (second argument)" exit 1 fi echo "$COMPOSER_PATH" # Check if composer bin is available, otherwise exit and display an error if [ ! -f $COMPOSER_PATH ]; then echo "Error retreving composer executable. Please verify if composer is intalled or the COMPOSER_PATH configuration at the begining of the file (Currently used COMPOSER_PATH = $COMPOSER_PATH)" exit 1 fi # Clone server repository and remove git related files git clone $SRV_REPO -b $BRANCH rm -rf OCSInventory-Server/.git rm -rf OCSInventory-Server/.github rm -rf OCSInventory-Server/.gitignore # Clone reports repository and remove git related files cd OCSInventory-Server && git clone $WEB_REPO -b $BRANCH ocsreports rm -rf ocsreports/.git rm -rf ocsreports/.github rm -rf ocsreports/.gitignore # Reset the default settings so install.php will be correctly loaded rm ocsreports/dbconfig.inc.php cd ocsreports/ # Run composer on ocsreports $COMPOSER_PATH install # Go back to the base path cd ../.. # Change name to comply with OCS' naming convention mv OCSInventory-Server OCSNG_UNIX_SERVER-$RELEASE_NAME tar cfz OCSNG_UNIX_SERVER-$RELEASE_NAME.tar.gz OCSNG_UNIX_SERVER-$RELEASE_NAME rm -rf OCSNG_UNIX_SERVER-$RELEASE_NAME # Release created ! echo "Release has been successfully created"OCSInventory-Server-2.8.1/binutils/docker-download.sh000077500000000000000000000015061376436473200226150ustar00rootroot00000000000000#!/bin/sh # Define constant VERSION=$1 # Github base url for download releases ReleaseBaseUrl="https://github.com/OCSInventory-NG/OCSInventory-ocsreports/releases/download/" # Last release tag LastReleaseTag="${VERSION}/" # Archive name LastReleaseArchive="OCSNG_UNIX_SERVER_${VERSION}" # Archive extension ArchiveExtension=".tar.gz" # File destination FileDestination="/tmp/ocs" # Archive link for release FullArchiveUrl=$ReleaseBaseUrl$LastReleaseTag$LastReleaseArchive$ArchiveExtension # Get archive if wget $FullArchiveUrl; then echo $LastReleaseArchive else LastReleaseArchive="OCSNG_UNIX_SERVER-${VERSION}" FullArchiveUrl=$ReleaseBaseUrl$LastReleaseTag$LastReleaseArchive$ArchiveExtension wget $FullArchiveUrl echo $FullArchiveUrl fi tar -xzvf $LastReleaseArchive$ArchiveExtension mv $LastReleaseArchive $FileDestination OCSInventory-Server-2.8.1/binutils/ipdiscover-util.README000066400000000000000000000016221376436473200232020ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Management Server Setup # # Copyleft 2006 OCS Inventory NG Team # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ ipdiscover-util.pl is designed to manage the ipdiscover data stored in the database. Update the connection data elements at the beginning of the script to make it work for you. The GUI ipdiscover feature is improved since this version. If you want more (analyze button (per subnet) and ip querying), put it in ocsreports. The script require Net::IP perl module, nmap and samba. Read documentation for further details. OCSInventory-Server-2.8.1/binutils/ipdiscover-util.pl000077500000000000000000000506341376436473200226720ustar00rootroot00000000000000#!/usr/bin/perl ############################################################################### ##OCSINVENTORY-NG ##Copyleft Pascal DANEK 2005 ##Web : http://www.ocsinventory-ng.org ## ##This code is open source and may be copied and modified as long as the source ##code is always made freely available. ##Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ # # use DBI; use XML::Simple; use Net::IP qw(:PROC); use strict; use Fcntl qw/:flock/; #Command line options : #-analyse : nmap analyse and files for grep, human readable and xml generation #-net : Treat machine for the specified subnet # # ################ #OPTIONS READING ################ # my $option; #Specify a subnet my $net; #Subnet name my $filter; #Analyse and class the computers my $analyse; #Net for a given ip my $iptarget; my $masktarget; #If auto flag, running for all the subnet.csv subnet and generate files my $auto; #Search for problems with computer election my $ipd; my $list; my $xml; my $cache; my $path; #Default values for database connection # my $dbhost = 'localhost'; my $dbuser = 'ocs'; my $dbpwd = 'ocs'; my $db = 'ocsweb'; my $dbp = '3306'; my $dbsocket = ''; # my %xml; my $ipdiscover; #Cleanup the directory &_cleanup(); for $option (@ARGV){ if($option=~/-a$/){ $analyse = 1; }elsif($option=~/-auto$/){ $auto = 1; }elsif($option=~/-cache$/){ $cache = 1; $analyse = 1; $xml = 1; }elsif($option=~/-path=(\S*)$/){ $path = $1; }elsif($option=~/-ipdiscover=(\d+)$/){ $ipdiscover = 1; $ipd = $1; }elsif($option=~/-xml$/){ $xml = 1; }elsif($option=~/-h=(\S+)/){ $dbhost = $1; }elsif($option=~/-d=(\S+)/){ $db = $1; }elsif($option=~/-u=(\S+)/){ $dbuser = $1; }elsif($option=~/-p=(\S+)/){ $dbpwd = $1; }elsif($option=~/-P=(\S+)/){ $dbp = $1; }elsif($option=~/-list$/){ $list = 1; }elsif($option=~/-s=(\S+)/){ $dbsocket = $1; }elsif($option=~/-net=(\S+)/){ die "Invalid subnet. Abort...\n" unless $1=~/^(\d{1,3}(?:\.\d{1,3}){3})$/; $net = 1; $filter = $1; }elsif($option=~/-ip=(\S+)/){ die "Invalid address => [IP/MASK]. Abort...\n" unless $1=~/^(\d{1,3}(?:\.\d{1,3}){3})\/(.+)$/; $iptarget = $1; $masktarget = $2; }else{ print < Looks for the ip in a subnet -net=X.X.X.X -> Specify a network -a -> Launch the analyze -ipdiscover=X -> Show all the subnet with up to XX ipdiscover -xml -> xml output -list=show all the networks present in the database with "connected"/"discovered" computers #DATABASE OPTION -p=xxxx password (default ocs) -P=xxxx port (default 3306) -d=xxxx database name (default ocsweb) -u=xxxx user (default ocs) -h=xxxx host (default localhost) -s=xxxx socket (default from default mysql configuration) EOF die "Invalid options. Abort..\n"; } } if($analyse and !$net){ die "Which subnet do you want to analyse ?\n"; } if($cache or $auto){ unless(-d "$path/ipd"){ mkdir("$path/ipd") or die $!; } } #Date of the day my $date = localtime(); ####################### #Database connection... ######## # my $request; my $row; my $dbparams = {}; $dbparams->{'mysql_socket'} = $dbsocket if $dbsocket; my $dbh = DBI->connect("DBI:mysql:database=$db;host=$dbhost;port=$dbp", $dbuser, $dbpwd, $dbparams) or die $!; ############################# #We get the subnet/name pairs #### # my @subnet; $request = $dbh->prepare("SELECT * FROM subnet"); $request->execute; while($row = $request->fetchrow_hashref){ push @subnet, [ $row->{'NETID'}, $row->{'NAME'}, $row->{'ID'}, $row->{'MASK'} ]; } ########### #PROCESSING ########### # if($auto){ print "\n\n########################\n"; print "Starting scan of subnets\n"; print "########################\n"; my %subnet; for(@subnet){ my $name = $_->[1]; my $netn = $_->[0]; $name=~s/ /_/g; $name=~s/\//\\\//g; $subnet{$name} = $netn; print "Retrieving $name (".$subnet{$name}.")\n"; } my $i; print "\n\n##################\n"; print "PROCESSING SUBNETS \n"; print "##################\n\n"; for(keys(%subnet)){ print "Processing $_ (".$subnet{$_}."). ".(keys(%subnet)-$i)." networks left.\n"; open OUT, ">$path/ipd/".$subnet{$_}.".ipd" or die $!; unless(flock(OUT, LOCK_EX|LOCK_NB)){ if($xml){ print "345"; exit(0); }else{ die "An other analyse is in progress\n"; } } system("./ipdiscover-util.pl -net=".$subnet{$_}.($xml?' -xml':'')." -a > $path/ipd/'".$subnet{$_}.".ipd'"); $i++; } system ("rm -f ipdiscover-analyze.*"); print "Done.\n"; exit(0); } #Host subnet my $network; #Subnet mask in binary format my $binmask; if($ipdiscover){ my @networks; #get the subnets my $result; die "Invalid value\n" if $ipd<0; $request = $dbh->prepare('select distinct(ipsubnet) from networks left outer join devices on tvalue=ipsubnet where tvalue is null'); $request->execute; while($row = $request->fetchrow_hashref){ push @networks, [ $row->{'ipsubnet'}, '0' ]; } $request->finish; #If positive value, it includes other subnet if($ipd){ $request = $dbh->prepare('select count(*) nb,tvalue,name from devices group by tvalue having nb<='.$ipd.' and name="ipdiscover"'); $request->execute; while($row = $request->fetchrow_hashref){ push @networks, [ $row->{'tvalue'}, $row->{'nb'} ]; } $request->finish; } print <[0]; my $nbipd = $network->[1]; next unless $ip =~ /^\d{1,3}(?:\.\d{1,3}){3}$/; my $req = $dbh->prepare('select h.deviceid, h.id, h.name, h.quality,h.fidelity,h.lastcome,h.lastdate,osname, n.ipmask, n.ipaddress from hardware h,networks n where n.hardware_id=h.id and n.ipsubnet='.$dbh->quote($ip).' order by lastdate'); $req->execute; #Get the subnet label unless($xml){ print "#######\n"; my ($nname, $nuid) = &_getnetname($ip, ''); print "SUBNET = ".$ip."-> $nbipd ipdiscover, ".($req->rows?$req->rows:0)." host(s) connected \n[ $nname ($nuid) ]\n"; print "#\n\n"; printf(" %-25s %-9s %-9s %-25s %-15s %-15s %s\n", "","","","","","",""); print "-----------------------------------------------------------------------------------------------------------------------\n"; while($result = $req->fetchrow_hashref){ my $r = $dbh->prepare('select * from devices where hardware_id='.$dbh->quote($result->{'id'}).' and tvalue='.$dbh->quote($ip).' and name="ipdiscover"'); $r->execute; printf("#-> %-25s %-9s %-9s %-25s %-15s %15s %s %s\n",$result->{'name'},$result->{'quality'},$result->{'fidelity'},$result->{'lastdate'},$result->{'ipaddress'}, $result->{'ipmask'},$result->{'osname'} ,$r->rows?'*':''); $r->finish; } print "\n\n\n\n"; }else{ $xml{'SUBNET'}[$i]{'IP'} = [ $ip ]; $xml{'SUBNET'}[$i]{'IPDISCOVER'} = [ $nbipd ]; $xml{'SUBNET'}[$i]{'HOSTS'} = [ $req->rows?$req->rows:0 ]; $j = 0; while($result = $req->fetchrow_hashref){ $xml{'SUBNET'}[$i]{'HOST'}[$j]{'NAME'} = [ $result->{'name'} ]; $xml{'SUBNET'}[$i]{'HOST'}[$j]{'QUALITY'} = [ $result->{'quality'} ]; $xml{'SUBNET'}[$i]{'HOST'}[$j]{'FIDELITY'} = [ $result->{'fidelity'} ]; $xml{'SUBNET'}[$i]{'HOST'}[$j]{'LASTDATE'} = [ $result->{'lastdate'} ]; $xml{'SUBNET'}[$i]{'HOST'}[$j]{'OSNAME'} = [ $result->{'osname'} ]; $xml{'SUBNET'}[$i]{'HOST'}[$j]{'IPMASK'} = [ $result->{'ipmask'} ]; $j++; } $i++; } } if($xml){ $output=XML::Simple::XMLout( \%xml, RootName => 'NET', SuppressEmpty => undef); print $output; } exit(0); } ############# ##IP resolving ############## ## if($iptarget){ my $netname; #If necessary, ascii conversion of a binary format $masktarget = _bintoascii($masktarget) if($masktarget=~/^\d\d$/); die "Invalid netmask. Abort.\n" unless $masktarget=~/^\d{1,3}(\.\d{1,3}){3}$/; $network = _network($iptarget, $masktarget); my $uid; ($netname, $uid)= &_getnetname($network, '-'); my @nmb = `nmblookup -A $iptarget`; #DNS name my $dnsname = &_getdns($iptarget); #Netbios name my $nmbname; my $inv; my $type; for(@nmb){ $nmbname = $1,last if /\s+(\S+).*<00>/; } $request = $dbh->prepare('SELECT * FROM networks WHERE IPADDRESS='.$dbh->quote($iptarget)); $request->execute; if($request->rows){ $inv = 1; $type = 'Computer'; }else{ $request = $dbh->prepare('SELECT IP,TYPE FROM netmap, network_devices WHERE MAC=MACADDR AND IP='.$dbh->quote($iptarget)); $request->execute; if(my $row = $request->fetchrow_hashref){ $inv = 1, $type = $row->{'TYPE'}; } } $request = $dbh->prepare('SELECT MAC FROM netmap WHERE IP='.$dbh->quote($iptarget)); $request->execute; my $exist = 1 if $request->rows; unless($xml){ print < ".($netname).". ($uid) ($network)\n"; print < 'IP', SuppressEmpty => undef); print $output; exit(0); } } # #Searching non-inventoried mac addresses # my %network; my @hosts; my $null; # # Filter out already flagged MAC addresses - drich $request = $dbh->prepare('SELECT IP,MASK,MAC,DATE FROM netmap LEFT JOIN networks ON MACADDR=MAC where MACADDR IS NULL AND MAC NOT IN (SELECT MACADDR FROM network_devices)'); $request->execute; # #Determine the subnets # # my %network_ipd; # while($row = $request->fetchrow_hashref){ my $ip; my $netmask; # if($row->{'MASK'}){ $ip = $row->{'IP'}; $netmask = $row->{'MASK'}; $network = _network($ip, $netmask); $binmask = _binmask($netmask); if($net){ next unless $network eq $filter; } #Hosts count per subnet if($list and !$analyse and !$net){ $network_ipd{$network}++; }else{ $network{$network}++; push @hosts, [ $row->{'MAC'}, $ip , $row->{'DATE'}]; } }else{ $null++; } } my $total = 0; #We want ALL subnets in the database, even those that are not discovered if($list and !$analyse and !$net){ $request = $dbh->prepare('SELECT IPADDRESS,IPMASK FROM networks'); $request->execute; while($row = $request->fetchrow_hashref){ my $ip; my $netmask; # if($row->{'IPMASK'}=~/^\d{1,3}(\.\d{1,3}){3}$/ and $row->{'IPADDRESS'}=~/^\d{1,3}(\.\d{1,3}){3}$/){ $ip = $row->{'IPADDRESS'}; $netmask = $row->{'IPMASK'}; $network = _network($ip, $netmask); $network{$network}++; } #Hosts count per subnet } #We show the part of non-inventoried computers my $netnum; for $netnum (keys(%network)){ $total+=$network{$netnum}; for(keys(%network_ipd)){ $network{$netnum}.= "/".$network_ipd{$_} if($_ eq $netnum); } } } ######## #RESULTS ######## # print <","","",""); print "-------------------------------------------------------------------\n"; } #net UID my $dep; #net name my $lib; # my $line; my $netn; # my $i; my $output; for $netn (keys(%network)){ ($lib, $dep) = &_getnetname($netn,'-'); if($xml and !$analyse){ $xml{'NETWORK'}[$i]{'LABEL'} = [ $lib ]; $xml{'NETWORK'}[$i]{'UID'} = [ $dep ]; $xml{'NETWORK'}[$i]{'NETNAME'} = [ $netn ]; $xml{'NETWORK'}[$i]{'NETNUMBER'} = [ $network{$netn} ]; $i++; }elsif(!$xml){ printf("%-35s %-5s %-20s %-4s\n",$lib,$dep,$netn,$network{$netn}); $total += $network{$netn} unless $list; } } if($xml and !$net){ $output=XML::Simple::XMLout( \%xml, RootName => 'IPDISCOVER', SuppressEmpty => undef); print $output; } if($net){ # my($n, $i); #Host names my @names; # unless($xml){ print "\n---------------------------------------------\n"; print "Unknown host(s) on $filter \n"; print "---------------------------------------------\n\n"; } my $output; for $n (@hosts){ #Trying a DNS resolution push @$n, &_getdns($$n[1]); unless($analyse){ if($xml){ $xml{'HOST'}[$i]{'IP'} = [ $$n[1] ]; $xml{'HOST'}[$i]{'MAC'} = [ $$n[0] ]; $xml{'HOST'}[$i]{'DATE'} = [ $$n[2] ]; $xml{'HOST'}[$i]{'NAME'} = [ $$n[3] ]; $i++; }else{ printf("=> %-20s %-20s %-20s %s\n",$$n[1],$$n[0],$$n[2],$$n[3]); } } } if(!$analyse and $xml){ $output=XML::Simple::XMLout( \%xml, RootName => 'NET', SuppressEmpty => undef); print $output; } } ######## #ANALYZE ######## # # # #windows computers my @PCW; #Linux computers my @PCL; #Mac computers my @PCM; #net peripherals my @PR; #Phantom computers my @PH; #At least one port filtered with one port open or closed my @PF; if($analyse){ #directory creation for analyses file if($cache){ open CACHE, ">$path/ipd/$filter.ipd" or die $!; unless(flock(CACHE, LOCK_EX|LOCK_NB)){ if($xml){ print "346"; exit(0); }else{ die "An other analyse is in progress\n"; } } } unless(@hosts){ print "No unknown hosts of this network. Stop.\n\n" unless $xml; exit(0); } #If it's a global analyze, we don't display the results but just generate the files #Using nmap : # -> Connection on ports 135(msrpc), 80(web), 22(ssh), 23(telnet) # -> files ipdiscover-analyze.* generated (3 formats : .nmap(human), .gnmap(pour grep), .xml(xml) # -> No 'host up' detection # my @ips; push @ips, $$_[1] for(@hosts); #Check that there is no analyses of this network pending open NMAP, "+>$path/$filter.gnmap"; unless(flock(NMAP, LOCK_EX|LOCK_NB)){ if($xml){ print "347"; exit(0); }else{ die "An other analyse is in progress\n"; } } #Analyse system("nmap -R -v @ips -p 135,80,22,23 -oG $path/$filter.gnmap -P0 -O > /dev/null"); # my @gnmap; if($net){ @gnmap = ; close NMAP; unlink "$path/$filter.gnmap"; # ########### # my $ref; my ($h, $w, $j, $r, $f, $l); REF: for $ref (@hosts){ $h = $$ref[1]; for(@gnmap){ next if /^#/; # Skip comments if(/Host: $h\b/){ if (/Status: Down/){ $PH[$j] = $ref; $j++; next REF; }elsif(/Status: /){ # status up is meaningless to us next; } # Try OS detection first if(/OS: .*Windows/){ $PCW[$w] = $ref; $w++; next REF; }elsif(/OS: .*Apple Mac/){ $PCM[$l] = $ref; $l++; next REF; }elsif(/OS: .*Linux/ and !/OS: .*embedded/){ $PCL[$l] = $ref; $l++; next REF; }elsif(/OS: /){ # Something else, call it network $PR[$r] = $ref; $r++; next REF; } if(/135\/o/){ $PCW[$w] = $ref; $w++; next REF; }elsif( (/22\/c.+23\/c.+80\/o.+135\/c/) or (/22\/c.+23\/o.+80\/c.+135\/c/) or (/22\/c.+23\/o.+80\/o.+135\/c/) or (/22\/o.+23\/o/) ){ $PR[$r] = $ref; $r++; next REF; }elsif(/(22\/f.+23\/f.+80\/f.+135\/c|22\/c.+23\/c.+80\/c.+135\/c)/){ $PH[$j] = $ref; $j++; next REF; }elsif(/(22\/f.+23\/f.+80\/f.+135\/f)/){ $PF[$f] = $ref; $f++; next REF; }else{ $PCL[$l] = $ref; $l++; next REF; } } } } #Display results print "\n" if $xml; print CACHE "\n" if $xml; &_print(\@PCW, 'WINDOWS COMPUTERS'); &_print(\@PCL, 'LINUX COMPUTERS'); &_print(\@PCM, 'MAC COMPUTERS'); &_print(\@PR, 'NETWORK DEVICES'); &_print(\@PF, 'FILTERED HOSTS'); &_print(\@PH, 'PHANTOM HOSTS'); print "\n" if $xml; print CACHE "\n" if $xml; } } ################## #DISLAY SUBROUTINE ################## # sub _print{ my $ref = shift; my $lib = shift; if(@$ref){ my $nb; unless($xml){ print "#" for(0..(length($lib)+3)); print "\n"; print "# ".$lib." #"; print "\n"; print "#" for(0..(length($lib)+3)); print "\n"; print "#----------------------------------------------------------------------------\n"; printf("#%-20s %-20s %-25s %s\n", "IP address", "MAC address", "DNS/Netbios", "Date"); print "#----------------------------------------------------------------------------\n#\n"; } $nb = 0; my $output; %xml = undef; for(@$ref){ $$_[3] = &_smbname($$_[1]) if $$_[3] eq "-"; if($xml){ $xml{'IP'} = [ $$_[1] ]; $xml{'MAC'} = [ $$_[0] ]; $xml{'NAME'} = [ $$_[3] ]; $xml{'DATE'} = [ $$_[2] ]; $xml{'TYPE'} = ['WINDOWS'] if $lib =~/windows/i; $xml{'TYPE'} = ['LINUX'] if $lib =~/linux/i; $xml{'TYPE'} = ['MAC'] if $lib =~/mac/i; $xml{'TYPE'} = ['FILTERED'] if $lib =~/filtered/i; $xml{'TYPE'} = ['NETWORK'] if $lib =~/network/i; $xml{'TYPE'} = ['PHANTOM'] if $lib =~/phantom/i; $output=XML::Simple::XMLout( \%xml, RootName => 'HOST', SuppressEmpty => undef); print $output; print CACHE $output if $cache; }else{ printf("#-> %-15s %-20s %-20s %s\n",$$_[1],$$_[0],$$_[3],$$_[2]); $nb++; } } unless($xml){ print "#\n#==========> $nb host(s)\n#\n\n\n"; } } } # ######################################### #ROUTINE DE RECUPERATION DES NOMS NETBIOS ######################################### # sub _smbname{ my $flag = 0; my $name; my $ip = shift; #If no dns name, we try a netbios resolution my @smb = `nmblookup -A $ip`; #On cherche un enregistrment <00> pour l'ip passee en argument for(@smb){ $name = "-"; /Looking\D+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/ unless $flag; if(/<00>/){ /^\s+(\S+)/; $name = $1; return $name; } } return "-"; } ############## #CLEAN *.gnmap ############## # sub _cleanup{ my($name, @files); opendir DIR, $path; while($name = readdir DIR){ push @files, $name if $name=~/\.gnmap$/i; } closedir DIR; for(@files){ open FILE, $_ or next; unlink "$path/$_" if(flock(FILE, LOCK_EX|LOCK_NB)); } } print "|\n|\n---------------------------------------------\n|" unless $xml; if($list){ print "\n|--> TOTAL = $total valid (ips/netmask) in the database\n" unless $xml; exit(0); } unless($xml){ print "\n|--> TOTAL = $total unknown hosts\n"; print "\n|--> WARNING: $null discovered computers without netmask on all discovered machine\n\n" if $null; } #Try to get dns name sub _getdns{ my $ip = shift; my $name; chomp(my @names = `host $ip 2>/dev/null`); for(@names){ return $1 if /.+pointer (.+)/i; return $1 if /Name:\s*(\S+)/i; } return("-"); } #Retrieve the name of the subnet if available sub _getnetname{ my $network = shift; my $r = shift; for(@subnet){ if($_->[0] eq $network){ return ($_->[1], $_->[2]); last; } } return($r, $r); } #To retrieve the net ip sub _network{ my $ip = shift; my $netmask = shift; my $binip = &ip_iptobin($ip, 4); my $binmask = &ip_iptobin($netmask, 4); my $subnet = $binip & $binmask; return(&ip_bintoip($subnet, 4)) or die(Error()); } sub _bintoascii{ my $binmask = shift; my $binstring = "1" x $binmask; $binstring .= "0" for(1..(32 - $binmask)); return(&ip_bintoip($binstring, 4)) or die(Error()); } sub _binmask{ my $ip = shift; return(&ip_iptobin($ip, 4)) or die(Error()); } OCSInventory-Server-2.8.1/binutils/ocs-errors000066400000000000000000000064661376436473200212350ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Management Server Setup # # Copyleft 2008 OCS Inventory NG Team # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ OCS Inventory NG logs format --> GDH;Process ID;Event code;DeviceID;IP address;User agent;Phase;(comment) Codes elements : ERRORS ------ 500--Query forbidden 502--Invalid device ID or hostname 503--Impossible to get a key from the config table 504--Impossible to get the last date inventory 505--Impossible to connect to database 506--Inflation problem 507--XML Parsing error 508--Update message unreadeable 509--Impossible to get the account infos 510--Bad content-type 511--File does not exist 512--Malformed request 513--Bad old deviceid 514--synchronisation problem 515--Script error, rollback transaction. 516--Deviceid locked 517--Cannot handle normal duplicate 518--Cannot retrieve database id 519--A device try to add a new computer whereas it is forbidden by filter inventory rules 520--The request for the group is not valid 521--Invalid database connection mode 522--Inventory Cache handling error (Creation) 523--Inventory Cache handling error (Truncate) 524--No checksum 525--Cannot reuse session 526--Error while checking session 527--Cannot end session (DB Fault) 528--No account infos sent 529--Unknown notify type 530--Cannot update ip address (notify handler) INVENTORY --------- 100--Inventory accepted 101--Inventory succeed 102--Inventory refused 103--New machine(deviceid) 104--Inventory incoming 105--Inventory refused but other task required 106--Prolog stopped by module 107--Inventory stopped by module 108--Cleaning inventory cache 109--Inventory cache handling success 110--Inventory cache out of date 111--Inventory cache already handled (lock fault) 112--Inventory cache updated 113--Inventory section has changed => write it 114--No prolog connection found 115--Inventory refused (no session) MANAGEMENT ---------- 300--Device replaced 301--Device can be duplicated 302--File transmitted (deploy) 304--Deploy off 305--Files transmitted 306--Group out-of-date 307--Revalidate group cache 308--Group is locked by another process 309--Group cache update problem 310--Trusted computer 311--Session started(prolog) 314--Checking expired sessions 315--Checking is already handled by another process (skipping) 316--Found old sessions (according to OCS_OPT_SESSION_CLEAN_TIME) 317--Session validity undefined : check always succeed 318--Session not found 319--Valid session found 320--End of session 321--Compression used is not zlib 322--Notify event 323--Update ipaddress for device (Notify) 324--No such mac address (notify) New iface ? 325--The computer does not exist 326--A old deviceid is present IPDISCOVER ---------- 1001--Ipdiscover enabled 1002--Ipdiscover disabled 1003--Ipdiscover report error 1004--Ipdiscover incoming 1005--Ipdiscover conflict with group exception DOWNLOAD -------- 2500--Impossible to get config 2501--Message refers to an unexisting package 2502--Cannot retrieve package history (db error) 2001--Download agent event incoming OCSInventory-Server-2.8.1/binutils/ocsinventory-injector.README000066400000000000000000000017201376436473200244340ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Management Server Setup # # Copyleft 2008 OCS Inventory NG Team # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ ocsinventory-injector.pl is a script designed to send inventory to an OCS server using .ocs files generated by -local (or /local for windows). Since 1.02 release, you can use the OCS_OPT_GENERATE_OCS_FILES server parameter to automatically generate these files to "inject" it to a higher level server. (in case of multi entity configuration for example). In that case, you can use a cron if the two servers are connected, or put it on the higher level server and run it on loopback. OCSInventory-Server-2.8.1/binutils/ocsinventory-injector.pl000077500000000000000000000101751376436473200241210ustar00rootroot00000000000000#!/usr/bin/perl -w ############################################################################### ##OCS inventory-NG Version 1.02 ##Copyleft Pascal DANEK 2005 ##Copyleft Goneri Le Bouder 2006 ##Web : http://www.ocsinventory-ng.org ## ##This code is open source and may be copied and modified as long as the source ##code is always made freely available. ##Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ #Last modification : $Id: ocsinventory-injector.pl,v 1.3 2008-02-18 07:17:52 hunal Exp $ #Local insertion script use Fcntl qw/:flock/; use LWP::UserAgent; use XML::Simple; use Compress::Zlib; use Getopt::Long; use constant VERSION => 3; use strict; my $help; my $directory; my $file; my $url; my $sslmode; my $cafile; my $useragent; my $remove; my $verbose; my $stdin; my $timeout; sub loadfile { $file = shift; unless ( -r $file ) { print STDERR "Can't read $file\n"; return; } print "Loading $file..." if $verbose; unless ( open( FILE, "$file" ) && flock( FILE, LOCK_EX | LOCK_NB ) ) { print STDERR "Failed to access $file : $!"; return; } local $/; my $content = ; close FILE or die "Can't close file $file: $!"; sendContent($content); } sub loaddirectory { my $directory = shift; unless ( -r $directory ) { print STDERR "Can't read $directory: $!\n"; return; } opendir( DIR, $directory ) || die "can't opendir $directory: $!"; foreach ( readdir(DIR) ) { loadfile("$directory/$_") if (/\.ocs$/); } closedir DIR; } sub loadstdin { my $content; undef $/; $content = ; sendContent($content); } sub sendContent { my $content = shift; my $ua = LWP::UserAgent->new( protocols_allowed => ['http', 'https'], timeout => $timeout, ssl_opts => { verify_hostname => $sslmode, SSL_ca_file => $cafile }, ); $ua->agent($useragent); my $request = HTTP::Request->new( POST => $url ); $request->header( 'Pragma' => 'no-cache', 'Content-type', 'Application/x-compress' ); $request->content("$content"); my $res = $ua->request($request); if($res->is_success){ print "OK\n" if $verbose; print STDERR "Can't remove $file: $!\n" if ($remove && (!unlink $file)); }else{ if($verbose){ print "ERROR: "; print $res->status_line(), "\n"; } } } sub usage { print < \$help, 'd|directory=s' => \$directory, 'f|file=s' => \$file, 'u|url=s' => \$url, 'sslmode=s' => \$sslmode, 'cafile=s' => \$cafile, 'useragent=s' => \$useragent, 'r|remove' => \$remove, 'v|verbose' => \$verbose, 't|timeout' => \$timeout, 'stdin' => \$stdin, ); # Default values $url = 'http://localhost/ocsinventory' unless $url; $useragent = 'OCS-NG_INJECTOR_PL_v'.VERSION unless $useragent; $directory = '.' unless $directory; $sslmode = 0 unless $sslmode; $cafile = "cacert.pem" unless $cafile; $timeout = 10 unless $timeout; ### $|=1; if ($file && -f $file) { loadfile($file); } elsif ($stdin) { loadstdin(); } elsif($help){ usage(); } else{ if ($directory && -d $directory) { loaddirectory($directory); } else{ die("Directory does not exist. Abort."); } } OCSInventory-Server-2.8.1/binutils/ocsinventory-log.README000066400000000000000000000021471376436473200234040ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Management Server Setup # # Copyleft 2008 OCS Inventory NG Team # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ ocsinventory-log.pl is a sample that enables you to see your ocs server's activity. You have to rotate your logs daily at 00:00, using the "compressed" option to have a day level visibility (use the provided logrotate) This kind of scripts may help you to adjust server's settings, especially FREQUENCY and PROLOG_FREQ parameter. Theses are the supported parameters : -f='log file' The log file to read -a=day_before Look for a 'log_file_name.gz' according to logrotate naming system -r Summary per hour of the activity -s General summary for the day -h="hour_num" See a specific hour => -m in minutes => -d group by ten minutes OCSInventory-Server-2.8.1/binutils/ocsinventory-log.pl000077500000000000000000000103661376436473200230670ustar00rootroot00000000000000#!/usr/bin/perl -s $f = $f || '/var/log/ocsinventory-server/activity.log'; unless($a){ $a = 0; @lines = `cat $f`; } else{ @lines = `$f.$a.gz`; } push @heures, sprintf("%02i",$_) for(0..23); push @minutes, sprintf("%02i",$_) for(0..59); @lines = grep { /^[^;]+;[^;]+;[^;]+;[^;]+;[^;]+$v;[^;]+;[^;]+$/i } @lines if defined($v); @prologs = grep { /;(?:102|100);/i } @lines; @accepts = grep { /;100;/i } @lines; @incomings = grep { /;104;/i } @lines; @arrived = grep { /;101;/i } @lines; @errors = grep { /;515;/i } @lines; @agents = grep { /deploy.+transmitted/i } @lines; @new = grep { /;103;/i } @lines; @dup = grep { /;300;/i } @lines; @gr_nv = grep { /;306;/i } @lines; @gr_rv = grep { /;307;/i } @lines; print "\n\nSynthese - ",scalar(localtime())," - $a jours\n\n", "Prologs: ", scalar(@prologs),"\n", "Accepted: ", scalar(@accepts),"\n", "New: ", scalar(@new),"\n", "Incomings: ", scalar(@incomings),"\n", "Auto duplicates: ", scalar(@dup),"\n", "Transmitted: ", scalar(@arrived),"\n", "Errors: ", scalar(@errors),"\n", "Groups out-of-date: ",scalar(@gr_nv),"\n", "Groups revalidated: ",scalar(@gr_nv),"\n", "Déploiement: ", scalar(@agents),"\n\n" if $s; per_hour() if $r; if(defined($h)){ per_deca("$h") if $d; per_minutes("$h") if $m; } sub per_hour { print "\n\nRecapitulatif par heure - ",scalar(localtime())," - $a jours\n\n"; print "\t\t\tPrologs\t\tAccepted\tIncomings\tNew\t\tDuplicates\tTransmitted\tErrors\tgr:ood\t:gr:reval\t\tDeployed\n"; for $heure (@heures){ print "$heure heures :\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @prologs),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @accepts),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @incomings),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @new),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @dup),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @arrived),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @errors),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @gr_nv),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @gr_rv),"\t"; print "\t",scalar(grep { /$heure(?::\d\d){2}/ } @agents),"\n"; } } sub per_minutes { $heure = shift; $heure = sprintf("%02i",$heure); print scalar(localtime()),"\n\n"; print "\n\nRecapitulatif minute par minute pour $heure heures - ",scalar(localtime())," - $ai jours\n\n"; print "\t\t\t\tPrologs\t\tAccepted\tIncomings\tNew\t\tDuplicates\tTransmitted\tErrors\tgr:ood\t:gr:reval\t\tDeployed\n"; for $minute (@minutes){ print "$heure heure $minute minutes :\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @prologs),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @accepts),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @incomings),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @new),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @dup),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @arrived),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @errors),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @gr_nv),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @gr_rv),"\t"; print "\t",scalar(grep { /$heure:$minute:\d\d/ } @agents),"\n"; } } sub per_deca { $heure = shift; @deca = (0..5); print scalar(localtime()),"\n\n"; print "\n\nRecapitulatif par dix minutes pour $heure heures - ",scalar(localtime())," - $a jours\n\n"; print "\t\t\t\tPrologs\t\tAccepted\tIncomings\tNew\t\tDuplicates\tTransmitted\tErrors\tgr:ood\t:gr:reval\t\tDeployed\n"; for $minute (@deca){ print "$heure heure ($minute*10) :\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @prologs),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @accepts),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @incomings),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @new),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @dup),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @arrived),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @errors),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @gr_nv),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @gr_rv),"\t"; print "\t",scalar(grep { /$heure:$minute\d:\d\d/ } @agents),"\n"; } } OCSInventory-Server-2.8.1/binutils/ocsinventory-powershell-injector.ps1000066400000000000000000000125741376436473200263750ustar00rootroot00000000000000<# Copyright 2005-2020 OCSInventory-NG/OCSInventory-server contributors. See the Contributors file for more details about them. This file is part of OCSInventory-NG/OCSInventory-server. OCSInventory-NG/OCSInventory-server is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. OCSInventory-NG/OCSInventory-server is distributed in the hope 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 OCSInventory-NG/OCSInventory-server. if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #> param ( [switch]$help = $false, [string]$directory, [string]$file, [string]$url, [string]$user, [string]$pass, [switch]$ssl = $false, [switch]$remove = $false, [switch]$info = $false ) <# .SYNOPSIS Display help .DESCRIPTION If -help is set in the command line, return the helper and quit #> function Get-InjectorHelper { Write-Output " DESCRIPTION: A command line tools to import .ocs files. USAGE: -help : this menu -directory : load every .ocs files from a directory -file : load a speficic file -url : ocsinventory backend URL -ssl : enable SSL inventory injection -user : Basic auth username -pass : User password -remove : remove successfully injected files -info : verbose mode " } <# .SYNOPSIS Display debug log .DESCRIPTION Display debug log only if -info is sent #> function Write-InfoLog($str) { if($info.IsPresent){ $currentTime = Get-Date -Format "MM/dd/yyyy HH:mm:ss" Write-Output "[OCSInject] $currentTime : $str" } } <# .SYNOPSIS Send file to OCS Server .DESCRIPTION Take the file, retrieve its content and send it to the OCS Inventory server #> function Send-File{ Param( [parameter(Mandatory=$true)] [string] $filePath, [parameter(Mandatory=$true)] [hashtable] $headers ) $fileContent = Get-Content($filePath) $fileName = Split-Path $filePath -leaf if($ssl.IsPresent -eq $true){ add-type " using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } " [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12 $webRequestStatus = Invoke-WebRequest ` -Uri $url ` -ContentType "application/xml" ` -Method POST ` -Body $fileContent ` -UserAgent "OCS_POWERSHELL_INJECTOR_V2.8" ` -Headers $headers }else{ $webRequestStatus = Invoke-WebRequest ` -Uri $url ` -ContentType "application/xml" ` -Method POST ` -Body $fileContent ` -UserAgent "OCS_POWERSHELL_INJECTOR_V2.8" ` -Headers $headers } if($webRequestStatus.StatusCode -eq 200){ Write-InfoLog("Injecting file $fileName => OK") }else{ Write-InfoLog("Injecting file $fileName => ERROR " + $webRequestStatus.StatusCode) } } Write-InfoLog("Starting injector") #### Help trigger #### if($help.IsPresent){ Get-InjectorHelper Exit } #### Test for basic parameters #### if($url.isPresent -eq $false){ Write-InfoLog("URL Missing, please provide one !") Exit } # Manage Auth if(-not ([string]::IsNullOrEmpty($user)) -And -not ([string]::IsNullOrEmpty($pass))){ Write-InfoLog("Auth required, setting headers...") $pair = "$($user):$($pass)" $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair)) $basicAuthValue = "Basic $encodedCreds" Write-InfoLog("Auth basic : $encodedCreds") $headers = @{ "Authorization" = $basicAuthValue; "Cache-Control" = "no-cache" } }else{ $headers = @{ "Cache-Control" = "no-cache" } } $pathOk = $false # File inject management if($file -And (Test-Path -Path $file) -eq $true){ $pathOk = $true Send-File $file $headers Exit } # Directory inject management if ($directory -And (Test-Path -Path $directory) -eq $true) { Write-InfoLog("Injecting files present in the directory=> $directory") Get-ChildItem $directory -Filter *.ocs | Foreach-Object { Send-File $_.FullName $headers } $pathOk = $true Exit } # Path not working if($pathOk -eq $false){ Write-InfoLog("File or Directory provided is wrong or not accessible, please check your arguments") Exit } OCSInventory-Server-2.8.1/binutils/soap-client.README000066400000000000000000000137361376436473200223070ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Management Server Setup # # Copyleft 2008 OCS Inventory NG Team # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ soap-client is a sample that enable you to discover the ocs web service. By default, it calls get_computer_V1 method that takes XML as argument. You can configure this XML using script parameters. To use other methods, (see Apache::Ocsinventory::Interface) , call it with -f=method_name and -params='comma separated args' # Parameters # -s='' : server to query # -u='' : user to authenticate # -pw='' : user's password # -params='...,...,...,...' : Method's args # -proto='http|https' : Transport protocol # # get_computers V1 secific parameters (enable you to easily modify XML values) # -o='' : offset value (to iterate if whome result is upper than OCS_OPT_WEB_SERVICE_RESULTS_LIMIT (see ocsinventory-server.conf) # -c='' : checksum to compare with # -w='' : same principle than checksum but for other sections (dico_soft and accountinfos for the moment) # -t='' : type (META || INVENTORY)) See web service documentation In addition to CHECKSUM (&), you can also request on : => userid list => tag list => database id list. You can use these criteria in only one request, and you can put few values for each. For example: FIRST <= The name of the search engine (only this one is implemented for the moment) INVENTORY <= We want inventory date (opposite to META DATA) 1 <= We want only hardware section (if it changed since our last reset_checksum) See below. 3 <= We want the third page of the result 2 <= We want to use the software dictionary and the accountinfos foo <= We want the computers on those foo logged in bar <= ...where bar logged in room109 <= We want the computer which have the "room109 tag" room110 <= ...or the "room110" tag spare <= ...or th "spare" tag 35 <= Only the DATABASE ID 35 36 <= ...or 36 LASTDATE <= We want to sort by LASTDATE (defaults to ID), allowed values: ID,LASTDATE,LASTCOME DESC <= We want to sort DESC (defaults to ASC), allowed values: ASC,DESC SOAP methods available : Name : get_computers_V1 Args : XML string Returns : XML Description : Main function to deal with ocsinventory computer's data (see above) Name : reset_checksum_V1 Args : a checksum, a list of Databases IDs Returns : undef on system error, "0E0" if no computers matched or the number of computers on success Description : The checksum is a bitmap used to know which inventory section has changed since last come. See Apache::Ocsinventory::Map to know the different values. For example, "hardware" section is the first bit (1). if 1 & checksum are true, you know that hardware changed since the last check. Name : ocs_config_V1 Args : option name, value Returns : value (if ok, ==value arg) or XML error (LABEL) Description : Configure ocs with an external tool Name : ocs_config_V2 Args : option name, integer value, string value Returns : XML. In case of success : , in case of error, the same as above. Description : Handle the new ocs config system (see Apache::Ocsinventory::Server::System::Config) Name : get_dico_soft_element_V1 Args : a word to look for Returns : The "formatted" name (also known as category) Description : Get the ditionnary entry of an extracted software name Name : get_history_V1 Args : page number Returns : XML. AAAA-MM-DD HH:MM:SSDEVICEIDDEVICEID ordered by date. Description : useful to know which computers has been deleted or merges (duplicates). If a "DELETED" has no "EQUIVALENT", it is a deletion. # Clear computer's history Name : clear_history_V1 Args : A number of events (the former) Returns : The number of events deleted Description : Clear computer's history Name : get_ipdiscover_devices_V1 Args : Date, Page, ninv flag Returns : XML. On error : LABEL, on success AAAA-MM-DD HH:MM:SSIPADDRESSMACADDRESSIPMASKhostname...... Description : Enable you to query ipdiscover results. The nInv flags ask to the method to only send the uninventories devices Name : ipdiscover_tag_V1 Args : macaddress, description, type, user Returns : XML Description : Register a macaddress as you can do in GUI. The type and the user must be valid in ocs database. Name : ipdiscover_untag_V1 Args : macaddress Returns : XML Description : Unregister a device Name : ipdiscover_remove_V1 Args : macaddress Returns : XML Description : Delete a device from ipdiscover results Name : ipdiscover_create_type_V1 Args : type name Returns : XML Description : Enable you to create a type remotely Name : ipdiscover_delete_type_V1 Args : type name Returns : XML Description : Remove a type For further details, see http://www.ocsinventory-ng.org/index.php?mact=News,cntnt01,detail,0&cntnt01articleid=98&cntnt01returnid=80 OCSInventory-Server-2.8.1/binutils/soap-client.pl000077500000000000000000000043121376436473200217560ustar00rootroot00000000000000#!/usr/bin/perl -s use SOAP::Lite; use XML::Entities; # Parameters # -s='' : server to query # -u='' : user to authenticate # -pw='' : user's password # -params='...,...,...,...' : Method's args # -proto='http|https' : Transport protocol # # get_computers V1 secific parameters (enable you to easily modify XML values) # -o='' : offset value (to iterate if whome result is upper than OCS_OPT_WEB_SERVICE_RESULTS_LIMIT (see ocsinventory-server.conf) # -c='' : checksum to compare with # -w='' : same principle than checksum but for other sections (dico_soft and accountinfos for the moment) # -t='' : type (META || INVENTORY)) See web service documentation # # Checksum decimal values #'hardware' => 1, #'bios' => 2, #'memories' => 4, #'slots' => 8, #'registry' => 16, #'controllers' => 32, #'monitors' => 64, #'ports' => 128, #'storages' => 256, #'drives' => 512, #'inputs' => 1024, #'modems' => 2048, #'networks' => 4096, #'printers' => 8192, #'sounds' => 16384, #'videos' => 32768, #'softwares' => 65536 $s = $s||'localhost'; $u = $u||''; $pw = $pw||''; $proto = $proto||'http'; @params = split ',', $params; $f = $f||get_computers_V1; # You can modify some XML tags $c = $c||131071; $t=$t||"META"; $o=$o||0; $w=defined $w?$w:131071; if( !defined(@params) && $f eq 'get_computers_V1' ){ @params=(< FIRST $t $c $o $w EOF } print "Launching soap request to proxy:\n"; print "$proto://$u".($u?':':'').($u?"$pw\@":'')."$s/ocsinterface\n"; print "Function: <$f>\n"; $i++, print "Function Arg $i: `$_'\n" for @params; print "\nIn progress... \n\n"; $lite = SOAP::Lite ->uri("$proto://$s/Apache/Ocsinventory/Interface") ->proxy("$proto://$u".($u?':':'').($u?"$pw\@":'')."$s/ocsinterface\n") ->$f(@params); if($lite->fault){ print "ERROR:\n\n",XML::Entities::decode( 'all', $lite->fault->{faultstring} ),"\nEND\n\n"; } else{ my $i = 0; for( $lite->paramsall ){ print "===== RESULT $i ===== \n".XML::Entities::decode( 'all', $_ )."\n"; $i++; } } OCSInventory-Server-2.8.1/cpanfile000066400000000000000000000006601376436473200170550ustar00rootroot00000000000000#requires 'mod_perl2', '> 2.0'; requires 'XML::Simple', '>= 2.12'; requires 'Compress::Zlib', '>= 1.33'; requires 'Apache::DBI', '>= 1.10'; #requires 'DBD::mysql', '>= 4.050'; requires 'Net::IP', '>= 1.20'; requires 'Mojolicious', '>= 8'; requires 'Plack', '>= 1.0047'; requires 'Archive::Zip', '>= 1.4'; requires 'Switch', '>= 2.0'; requires 'YAML', '>= 1.0';OCSInventory-Server-2.8.1/dtd/000077500000000000000000000000001376436473200161225ustar00rootroot00000000000000OCSInventory-Server-2.8.1/dtd/Interface/000077500000000000000000000000001376436473200200225ustar00rootroot00000000000000OCSInventory-Server-2.8.1/dtd/Interface/get_computers_V1-request.dtd000066400000000000000000000003041376436473200254300ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/download_request.dtd000066400000000000000000000003121376436473200221720ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/file_request.dtd000066400000000000000000000003041376436473200213030ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/inventory_reply.dtd000066400000000000000000000003261376436473200220700ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/inventory_request.dtd000066400000000000000000000127451376436473200224350ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/prolog_reply.dtd000066400000000000000000000015211376436473200213330ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/prolog_request.dtd000066400000000000000000000002101376436473200216620ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/snmp_request.dtd000066400000000000000000000063411376436473200213500ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/update_reply.dtd000066400000000000000000000002371376436473200213160ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/dtd/update_request.dtd000066400000000000000000000002771376436473200216570ustar00rootroot00000000000000 OCSInventory-Server-2.8.1/etc/000077500000000000000000000000001376436473200161225ustar00rootroot00000000000000OCSInventory-Server-2.8.1/etc/logrotate.d/000077500000000000000000000000001376436473200203445ustar00rootroot00000000000000OCSInventory-Server-2.8.1/etc/logrotate.d/ocsinventory-server000066400000000000000000000002711376436473200243350ustar00rootroot00000000000000# Rotate OCS Inventory NG Communication server logs daily # Save 7 days old logs in compressed mode PATH_TO_LOG_DIRECTORY/*.log { daily rotate 7 compress delaycompress missingok } OCSInventory-Server-2.8.1/etc/ocsinventory/000077500000000000000000000000001376436473200206645ustar00rootroot00000000000000OCSInventory-Server-2.8.1/etc/ocsinventory/ocsinventory-reports.conf000066400000000000000000000077471376436473200260100ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Administration Server # # Copyleft 2008 OCS Inventory NG Team # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ # # ANY CHANGE ON THIS FILE REQUIRES APACHE RESTART TO TAKE EFFECT # ################################################################################ # Administration console public pages # # Alias used to put Administration Server static page (typically PHP) outside # Apache document root directory # Alias OCSREPORTS_ALIAS PATH_TO_OCSREPORTS_DIR # By default, users can use console from everywhere # Apache 2.4 Require all granted Order deny,allow Allow from all Options Indexes FollowSymLinks DirectoryIndex index.php AllowOverride Options AuthConfig # Uncomment following to force use of HTTPS in Administration Server #SSLRequireSSL # PHP tuning (not working on all distribution, use php.ini instead) AddType application/x-httpd-php .php php_flag file_uploads on # Some PHP tuning for deployment feature up to 8 MB # post_max_size must be greater than upload_max_filesize # because of HTTP headers php_value post_max_size 101m php_value upload_max_filesize 100m # You may have to uncomment following on errors #php_value max_execution_time -1 #php_value max_input_time -1 # Uncomment following if you need to specify a mysql socket #php_value mysql.default_socket "path/to/mysql/unix/socket" #!! Mandatory !! : set magic_quotes_gpc to off (to make ocsreports works correctly) php_flag magic_quotes_gpc off # Duplicate for php7 compatibility AddType application/x-httpd-php .php php_flag file_uploads on # Some PHP tuning for deployment feature up to 8 MB # post_max_size must be greater than upload_max_filesize # because of HTTP headers php_value post_max_size 101m php_value upload_max_filesize 100m # You may have to uncomment following on errors #php_value max_execution_time -1 #php_value max_input_time -1 # Uncomment following if you need to specify a mysql socket #php_value mysql.default_socket "path/to/mysql/unix/socket" #!! Mandatory !! : set magic_quotes_gpc to off (to make ocsreports works correctly) php_flag magic_quotes_gpc off # Uncomment following to allow HTTP body request up to 4 MB # instead default 512 KB #LimitRequestBody 4194304 ################################################################################ # Deployment packages download area # # Alias to put Deployment package files outside Apache document root directory # # Apache 2.4 Require all granted Order deny,allow Allow from all Alias PACKAGES_ALIAS PATH_TO_PACKAGES_DIR ################################################################################ # Snmp communities area # # Alias to put Snmp custom Mibs files outside Apache document root directory # # Apache 2.4 Require all granted Order deny,allow Allow from all Alias SNMP_ALIAS PATH_TO_SNMP_DIR OCSInventory-Server-2.8.1/etc/ocsinventory/ocsinventory-restapi.conf000066400000000000000000000011711376436473200257420ustar00rootroot00000000000000PerlOptions +Parent $ENV{PLACK_ENV} = 'production'; $ENV{MOJO_HOME} = 'REST_API_PATH'; $ENV{MOJO_MODE} = 'deployment'; $ENV{OCS_DB_HOST} = 'localhost'; $ENV{OCS_DB_PORT} = '3306'; $ENV{OCS_DB_LOCAL} = 'ocsweb'; $ENV{OCS_DB_USER} = 'ocs'; $ENV{OCS_DB_PWD} = 'ocs'; $ENV{OCS_DB_SSL_ENABLED} = 0; # $ENV{OCS_DB_SSL_CLIENT_KEY} = ''; # $ENV{OCS_DB_SSL_CLIENT_CERT} = ''; # $ENV{OCS_DB_SSL_CA_CERT} = ''; $ENV{OCS_DB_SSL_MODE} = 'SSL_MODE_PREFERRED'; SetHandler perl-script PerlResponseHandler Plack::Handler::Apache2 PerlSetVar psgi_app 'REST_API_LOADER_PATH' OCSInventory-Server-2.8.1/etc/ocsinventory/ocsinventory-server.conf000066400000000000000000000336441376436473200256130ustar00rootroot00000000000000################################################################################ # # OCS Inventory NG Communication Server Perl Module Setup # # Copyleft 2006 Pascal DANEK # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ # Which version of mod_perl we are using # For mod_perl <= 1.999_21, replace VERSION_MP by 1 # For mod_perl > 1.999_21, replace VERSION_MP by 2 PerlSetEnv OCS_MODPERL_VERSION VERSION_MP # Master Database settings # Replace DATABASE_SERVER by hostname or ip of MySQL server for WRITE PerlSetEnv OCS_DB_HOST DATABASE_SERVER # Replace DATABASE_PORT by port where running MySQL server, generally 3306 PerlSetEnv OCS_DB_PORT DATABASE_PORT # Name of database PerlSetEnv OCS_DB_NAME ocsweb PerlSetEnv OCS_DB_LOCAL ocsweb # User allowed to connect to database PerlSetEnv OCS_DB_USER ocs # Password for user PerlSetVar OCS_DB_PWD ocs # SSL Configuration # 0 to disable the SSL support for MySQL/MariaDB # 1 to enable the SSL support for MySQL/MariaDB PerlSetEnv OCS_DB_SSL_ENABLED 0 # PerlSetEnv OCS_DB_SSL_CLIENT_KEY /etc/ssl/private/client.key # PerlSetEnv OCS_DB_SSL_CLIENT_CERT /etc/ssl/certs/client.crt # PerlSetEnv OCS_DB_SSL_CA_CERT /etc/ssl/certs/ca.crt # SSL Mode # - SSL_MODE_PREFERRED (SSL enabled but optional) # - SSL_MODE_REQUIRED (SSL enabled, mandatory but don't verify server certificate. Ex self signed cert) # - SSL_MODE_STRICT (SSL enabled, mandatory and server cert must be trusted) PerlSetEnv OCS_DB_SSL_MODE SSL_MODE_PREFERRED # Slave Database settings # Replace DATABASE_SERVER by hostname or ip of MySQL server for READ # Useful if you handle mysql slave databases # PerlSetEnv OCS_DB_SL_HOST DATABASE_SERVER # Replace DATABASE_PORT by port where running MySQL server, generally 3306 # PerlSetEnv OCS_DB_SL_PORT_SLAVE DATABASE_PORT # User allowed to connect to database # PerlSetEnv OCS_DB_SL_USER ocs # Name of the database # PerlSetEnv OCS_DB_SL_NAME ocsweb # Password for user # PerlSetVar OCS_DB_SL_PWD ocs # SSL Configuration for Slave database # 0 to disable the SSL support for MySQL/MariaDB # 1 to enable the SSL support for MySQL/MariaDB # PerlSetEnv OCS_DB_SL_SSL_ENABLED 0 # PerlSetEnv OCS_DB_SL_SSL_CLIENT_KEY /etc/ssl/private/client.key # PerlSetEnv OCS_DB_SL_SSL_CLIENT_CERT /etc/ssl/certs/client.crt # PerlSetEnv OCS_DB_SL_SSL_CA_CERT /etc/ssl/certs/ca.crt # SSL Mode # - SSL_MODE_PREFERRED (SSL enabled but optional) # - SSL_MODE_REQUIRED (SSL enabled, mandatory but don't verify server certificate. Ex self signed cert) # - SSL_MODE_STRICT (SSL enabled, mandatory and server cert must be trusted) # PerlSetEnv OCS_DB_SL_SSL_MODE SSL_MODE_PREFERRED # Path to log directory (must be writeable) PerlSetEnv OCS_OPT_LOGPATH "PATH_TO_LOG_DIRECTORY" # If you need to specify a mysql socket that the client's built-in #PerlSetEnv OCS_OPT_DBI_MYSQL_SOCKET "path/to/mysql/unix/socket" # DBI verbosity PerlSetEnv OCS_OPT_DBI_PRINT_ERROR 0 # Unicode support PerlSetEnv OCS_OPT_UNICODE_SUPPORT 1 # If you are using a multi server architecture, # Put the ip addresses of the slaves on the master # (This is read as perl regular expressions) PerlAddVar OCS_OPT_TRUSTED_IP 127.0.0.1 #PerlAddVar OCS_OPT_TRUSTED_IP XXX.XXX.XXX.XXX # Be careful: you must restart apache to make settings taking effects # Configure engine to use the settings from this file PerlSetEnv OCS_OPT_OPTIONS_NOT_OVERLOADED 0 # Try to use other compress algorithm than raw zlib # GUNZIP and clear XML are supported PerlSetEnv OCS_OPT_COMPRESS_TRY_OTHERS 1 ############################################################## # ===== OPTIONS BELOW ARE OVERLOADED IF YOU USE OCS GUI =====# ############################################################## # NOTE: IF YOU WANT TO USE THIS CONFIG FILE INSTEAD, set OCS_OPT_OPTIONS_NOT_OVERLOADED to '1' # ===== MAIN SETTINGS ===== # Enable engine logs (see LOGPATH setting) PerlSetEnv OCS_OPT_LOGLEVEL 0 # Specify agent's prolog frequency PerlSetEnv OCS_OPT_PROLOG_FREQ 12 # Specify if agent take contact on service startup PerlSetEnv OCS_OPT_INVENTORY_ON_STARTUP 0 # Configure the duplicates detection system PerlSetEnv OCS_OPT_AUTO_DUPLICATE_LVL 15 # Futur security improvements PerlSetEnv OCS_OPT_SECURITY_LEVEL 0 # Validity of a computer's lock PerlSetEnv OCS_OPT_LOCK_REUSE_TIME 600 # Enable the history tracking system (useful for external data synchronisation PerlSetEnv OCS_OPT_TRACE_DELETED 0 # ===== INVENTORY SETTINGS ===== # Specify the validity of inventory data PerlSetEnv OCS_OPT_FREQUENCY 0 # Configure engine to update inventory regarding to CHECKSUM agent value (lower DB backend load) PerlSetEnv OCS_OPT_INVENTORY_DIFF 1 # Make engine consider an inventory as a transaction (lower concurency, better disk usage) PerlSetEnv OCS_OPT_INVENTORY_TRANSACTION 1 # Configure engine to make a differential update of inventory sections (row level). Lower DB backend load, higher frontend load PerlSetEnv OCS_OPT_INVENTORY_WRITE_DIFF 1 # Enable some stuff to improve DB queries, especially for GUI multicriteria searching system PerlSetEnv OCS_OPT_INVENTORY_CACHE_ENABLED 1 # Specify when the engine will clean the inventory cache structures PerlSetEnv OCS_OPT_INVENTORY_CACHE_REVALIDATE 7 # Enable you to keep trace of every elements encountered in db life PerlSetEnv OCS_OPT_INVENTORY_CACHE_KEEP 1 # ===== SOFTWARES DEPLOYMENT SETTINGS ===== # Enable this feature PerlSetEnv OCS_OPT_DOWNLOAD 0 # Package which have a priority superior than this value will not be downloaded PerlSetEnv OCS_OPT_DOWNLOAD_PERIOD_LENGTH 10 # Time between two download cycles (bandwidth control) PerlSetEnv OCS_OPT_DOWNLOAD_CYCLE_LATENCY 60 # Time between two fragment downloads (bandwidth control) PerlSetEnv OCS_OPT_DOWNLOAD_FRAG_LATENCY 60 # Specify if you want to track packages affected to a group on computer's level PerlSetEnv OCS_OPT_DOWNLOAD_GROUPS_TRACE_EVENTS 1 # Time between two download periods (bandwidth control) PerlSetEnv OCS_OPT_DOWNLOAD_PERIOD_LATENCY 60 # Agents will send ERR_TIMEOUT event and clean the package it is older than this setting PerlSetEnv OCS_OPT_DOWNLOAD_TIMEOUT 7 # Agents will send an error event and clean the package if package command does not respond during this setting PerlSetEnv OCS_OPT_DOWNLOAD_EXECUTION_TIMEOUT 120 # Enable ocs engine to deliver agent's files (deprecated) PerlSetEnv OCS_OPT_DEPLOY 0 # Enable the softwares deployment capacity (bandwidth control) # ===== GROUPS SETTINGS ===== # Enable the computer\s groups feature PerlSetEnv OCS_OPT_ENABLE_GROUPS 1 # Random number computed in the defined range. Designed to avoid computing many groups in the same process PerlSetEnv OCS_OPT_GROUPS_CACHE_OFFSET 43200 # Specify the validity of computer's groups (default: compute it once a day - see offset) PerlSetEnv OCS_OPT_GROUPS_CACHE_REVALIDATE 43200 # ===== IPDISCOVER SETTINGS ===== # Specify how much agent per LAN will discovered connected peripherals (0 to disable) PerlSetEnv OCS_OPT_IPDISCOVER 2 # Specify the minimal difference to replace an ipdiscover agent PerlSetEnv OCS_OPT_IPDISCOVER_BETTER_THRESHOLD 1 # Time between 2 arp requests (mini: 10 ms) PerlSetEnv OCS_OPT_IPDISCOVER_LATENCY 100 # Specify when to remove a computer when it has not come until this period PerlSetEnv OCS_OPT_IPDISCOVER_MAX_ALIVE 14 # Disable the time before a first election (not recommended) PerlSetEnv OCS_OPT_IPDISCOVER_NO_POSTPONE 0 # Enable groups for ipdiscover (for example, you might want to prevent some groups to be ipdiscover agents) PerlSetEnv OCS_OPT_IPDISCOVER_USE_GROUPS 1 # ===== INVENTORY FILES MAPPING SETTINGS ===== # Use with ocsinventory-injector, enable the multi entities feature PerlSetEnv OCS_OPT_GENERATE_OCS_FILES 0 # Generate either compressed file or clear XML text PerlSetEnv OCS_OPT_OCS_FILES_FORMAT OCS # Specify if you want to keep trace of all inventory between to synchronisation with the higher level server PerlSetEnv OCS_OPT_OCS_FILES_OVERWRITE 0 # Path to ocs files directory (must be writeable) PerlSetEnv OCS_OPT_OCS_FILES_PATH /tmp # ===== FILTER SETTINGS ===== # Enable prolog filter stack PerlSetEnv OCS_OPT_PROLOG_FILTER_ON 0 # Enable core filter system to modify some things "on the fly" PerlSetEnv OCS_OPT_INVENTORY_FILTER_ENABLED 0 # Enable inventory flooding filter. A dedicated ipaddress ia allowed to send a new computer only once in this period PerlSetEnv OCS_OPT_INVENTORY_FILTER_FLOOD_IP 0 # Period definition for INVENTORY_FILTER_FLOOD_IP PerlSetEnv OCS_OPT_INVENTORY_FILTER_FLOOD_IP_CACHE_TIME 300 # Enable inventory filter stack PerlSetEnv OCS_OPT_INVENTORY_FILTER_ON 0 # ===== DATA FILTER ===== #Enable the dat filtering capacity PerlSetEnv OCS_OPT_DATA_FILTER 0 # Set the table names and the field associated you want to filter #PerlAddVar OCS_OPT_DATA_TO_FILTER HARDWARE #PerlAddVar OCS_OPT_DATA_TO_FILTER USERID # ===== REGISTRY SETTINGS ===== # Enable the registry capacity PerlSetEnv OCS_OPT_REGISTRY 1 # ===== SNMP SETTINGS ===== # Enable the SNMP capacity PerlSetEnv OCS_OPT_SNMP 0 # Configure engine to update snmp inventory regarding to snmp_laststate table (lower DB backend load) PerlSetEnv OCS_OPT_SNMP_INVENTORY_DIFF 1 # Display error message about agent https communication in logfile PerlSetEnv OCS_OPT_SNMP_PRINT_HTTPS_ERROR 1 # ===== SESSION SETTINGS ===== # Not yet in GUI # Validity of a session (prolog=>postinventory) PerlSetEnv OCS_OPT_SESSION_VALIDITY_TIME 600 # Consider a session obsolete if it is older thant this value PerlSetEnv OCS_OPT_SESSION_CLEAN_TIME 86400 # Accept an inventory only if required by server #( Refuse "forced" inventory) PerlSetEnv OCS_OPT_INVENTORY_SESSION_ONLY 0 # ===== TAG ===== # The default behavior of the server is to ignore TAG changes from the # agent. PerlSetEnv OCS_OPT_ACCEPT_TAG_UPDATE_FROM_CLIENT 0 # ===== EXTERNAL USERAGENTS ===== #Path for external useragents reference file #!! WARNING !! : external agents may not be supported by OCS NG Community ! #PerlSetEnv OCS_OPT_EXT_USERAGENTS_FILE_PATH /tmp/yourfile.txt # ===== PLUGINS ===== PerlSetEnv OCS_PLUGINS_PERL_DIR "PATH_TO_PLUGINS_PERL_DIRECTORY" PerlSetEnv OCS_PLUGINS_CONF_DIR "PATH_TO_PLUGINS_CONFIG_DIRECTORY" # ===== DEPRECATED ===== # Set the proxy cache validity in http headers when sending a file PerlSetEnv OCS_OPT_PROXY_REVALIDATE_DELAY 3600 # Deprecated PerlSetEnv OCS_OPT_UPDATE 0 ############ DO NOT MODIFY BELOW ! ####################### # External modules PerlModule Apache::DBI PerlModule Compress::Zlib PerlModule XML::Simple # Ocs plugins PerlModule Apache::Ocsinventory::Plugins # Ocs PerlModule Apache::Ocsinventory PerlModule Apache::Ocsinventory::Server::Constants PerlModule Apache::Ocsinventory::Server::System PerlModule Apache::Ocsinventory::Server::Communication PerlModule Apache::Ocsinventory::Server::Inventory PerlModule Apache::Ocsinventory::Server::Duplicate # Capacities PerlModule Apache::Ocsinventory::Server::Capacities::Registry PerlModule Apache::Ocsinventory::Server::Capacities::Update PerlModule Apache::Ocsinventory::Server::Capacities::Ipdiscover PerlModule Apache::Ocsinventory::Server::Capacities::Download PerlModule Apache::Ocsinventory::Server::Capacities::Notify PerlModule Apache::Ocsinventory::Server::Capacities::Snmp # This module guides you through the module creation # PerlModule Apache::Ocsinventory::Server::Capacities::Example # This module adds some rules to filter some request sent to ocs server in the prolog and inventory stages # PerlModule Apache::Ocsinventory::Server::Capacities::Filter # This module add availibity to filter data from HARDWARE section (data filtered won't be stored in database) # PerlModule Apache::Ocsinventory::Server::Capacities::Datafilter # PerlTaintCheck On # SSL apache settings #SSLEngine "SSL_ENABLE" #SSLCertificateFile "SSL_CERTIFICATE_FILE" #SSLCertificateKeyFile "SSL_CERTIFICATE_KEY_FILE" #SSLCACertificateFile "SSL_CERTIFICATE_FILE" #SSLCACertificatePath "SSL_CERTIFICATE_PATH" #SSLVerifyClient "SSL_VALIDATE_CLIENT" # Engine apache settings # "Virtual" directory for handling OCS Inventory NG agents communications # Be careful, do not create such directory into your web server root document ! # Apache 2.4 Require all granted # Apache 2.2 order deny,allow allow from all # If you protect this area you have to deal with http_auth_* agent's parameters # AuthType Basic # AuthName "OCS Inventory agent area" # AuthUserFile "APACHE_AUTH_USER_FILE" # require valid-user SetHandler perl-script PerlHandler Apache::Ocsinventory # Web service apache settings PerlModule Apache::Ocsinventory::SOAP SetHandler perl-script PerlHandler "Apache::Ocsinventory::SOAP" # By default, you can query web service from everywhere with a valid user # Apache 2.4 Require all granted Order deny,allow Allow from all AuthType Basic AuthName "OCS Inventory SOAP Area" # Use htpasswd to create/update soap-user (or another granted user) AuthUserFile "APACHE_AUTH_USER_FILE" # Apache 2.4 Require user "SOAP_USER" require "SOAP_USER" OCSInventory-Server-2.8.1/setup.sh000077500000000000000000002102561376436473200170540ustar00rootroot00000000000000#!/bin/sh ################################################################################ # # OCS Inventory NG Management Server Setup # # Copyleft 2006 Didier LIROULET # Web: http://www.ocsinventory-ng.org # # This code is open source and may be copied and modified as long as the source # code is always made freely available. # Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt ################################################################################ # # Which host run database server DB_SERVER_HOST="localhost" # On which port run database server DB_SERVER_PORT="3306" # Database server credentials DB_SERVER_USER="ocs" DB_SERVER_PWD="ocs" # Where is Apache daemon binary (if empty, will try to find it) APACHE_BIN="" # Where is Apache configuration file (if empty, will try to find it) APACHE_CONFIG_FILE="" # Where is Apache includes configuration directory (if emty, will try to find it) APACHE_CONFIG_DIRECTORY="" # Which user is running Apache web server (if empty, will try to find it) APACHE_USER="" # Which group is running Apache web server (if empty, will try to find it) APACHE_GROUP="" # Where is Apache document root directory (if empty, will try to find it) APACHE_ROOT_DOCUMENT="" # Which version of mod_perl is apache using, 1 for <= 1.999_21 and 2 for >= 1.999_22 (if empty, user will be asked for) APACHE_MOD_PERL_VERSION="" # Where are located OCS Communication server log files OCS_COM_SRV_LOG="/var/log/ocsinventory-server" # Where are located OCS Communication server plugins configuration files OCS_COM_SRV_PLUGINS_CONFIG_DIR="/etc/ocsinventory-server/plugins" # Where are located OCS Communication server plugins perl files OCS_COM_SRV_PLUGINS_PERL_DIR="/etc/ocsinventory-server/perl" # Where is located perl interpreter PERL_BIN=`which perl 2>/dev/null` # Where is located make utility MAKE=`which make 2>/dev/null` # Where is located logrotate configuration directory LOGROTATE_CONF_DIR="/etc/logrotate.d" # Where is located newsyslog.conf NEWSYSLOG_CONF_FILE="/etc/newsyslog.conf" # Where to store setup logs SETUP_LOG=`pwd`/ocs_server_setup.log # Communication Server Apache configuration file COM_SERVER_APACHE_CONF_FILE="ocsinventory-server.conf" # Rest API configuration file API_REST_APACHE_CONF_FILE="ocsinventory-restapi.conf" # Communication Server logrotate configuration file COM_SERVER_LOGROTATE_CONF_FILE="ocsinventory-server" # Administration Console Apache configuration file ADM_SERVER_APACHE_CONF_FILE="ocsinventory-reports.conf" # Administration console read only files directory ADM_SERVER_STATIC_DIR="/usr/share/ocsinventory-reports" ADM_SERVER_STATIC_REPORTS_DIR="ocsreports" ADM_SERVER_REPORTS_ALIAS="/ocsreports" # Administration console read/write files dir ADM_SERVER_VAR_DIR="/var/lib/ocsinventory-reports" # Administration default packages directory and Apache alias ADM_SERVER_VAR_PACKAGES_DIR="download" ADM_SERVER_PACKAGES_ALIAS="/download" # Administration default snmp directory and Apache alias ADM_SERVER_VAR_SNMP_DIR="snmp" ADM_SERVER_SNMP_ALIAS="/snmp" # Administration console log files dir ADM_SERVER_VAR_LOGS_DIR="logs" # Administration console scripts log files dir ADM_SERVER_VAR_SCRIPTS_LOGS_DIR="scripts" # Administration console default ipdsicover-util.pl cache dir ADM_SERVER_VAR_IPD_DIR="ipd" # OS or linux distribution from automatic detection UNIX_DISTRIBUTION="" # Default install directory for rest api REST_API_DIRECTORY="" ###################### DO NOT MODIFY BELOW ####################### # Check for Apache web server binaries echo echo "+----------------------------------------------------------+" echo "| |" echo "| Welcome to OCS Inventory NG Management server setup ! |" echo "| |" echo "+----------------------------------------------------------+" echo # Check for OS or linux distribution echo "Trying to determine which OS or Linux distribution you use" if [ -f /etc/redhat-release ] then UNIX_DISTRIBUTION="redhat" elif [ -f /etc/debian_version ] then UNIX_DISTRIBUTION="debian" elif [ -f /etc/SuSE-release ] then UNIX_DISTRIBUTION="suse" fi # Check for Apache web server binaries echo "+----------------------------------------------------------+" echo "| Checking for Apache web server binaries ! |" echo "+----------------------------------------------------------+" echo echo "CAUTION: If upgrading Communication server from OCS Inventory NG 1.0 RC2 and" echo "previous, please remove any Apache configuration for Communication Server!" echo echo -n "Do you wish to continue ([y]/n)?" read ligne if [ -z "$ligne" ] || [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo "Assuming Communication server 1.0 RC2 or previous is not installed" echo "on this computer." echo else echo "Installation aborted !" echo exit 1 fi echo > $SETUP_LOG OCS_LOCAL_DATE=`date +%Y-%m-%d-%H-%M-%S` echo "Starting OCS Inventory NG Management server setup on $OCS_LOCAL_DATE" >> $SETUP_LOG echo -n "from folder " >> $SETUP_LOG pwd >> $SETUP_LOG echo -n "Starting OCS Inventory NG Management server setup from folder " pwd echo "Storing log in file $SETUP_LOG" >> $SETUP_LOG echo "Storing log in file $SETUP_LOG" echo >> $SETUP_LOG echo "============================================================" >> $SETUP_LOG echo "Checking OCS Inventory NG Management Server requirements..." >> $SETUP_LOG echo "============================================================" >> $SETUP_LOG echo echo "+----------------------------------------------------------+" echo "| Checking for database server properties... |" echo "+----------------------------------------------------------+" echo # Check mysql client distribution version echo "Checking for database server properties" >> $SETUP_LOG DB_CLIENT_MAJOR_VERSION=`eval mysql -V | cut -d' ' -f6 | cut -d'.' -f1` >> $SETUP_LOG 2>&1 DB_CLIENT_MINOR_VERSION=`eval mysql -V | cut -d' ' -f6 | cut -d'.' -f2` >> $SETUP_LOG 2>&1 if [ "$DB_CLIENT_MAJOR_VERSION" = "Linux" ] then DB_CLIENT_MAJOR_VERSION=`eval mysql -V | cut -d' ' -f4 | cut -d'.' -f1` >> $SETUP_LOG 2>&1 DB_CLIENT_MINOR_VERSION=`eval mysql -V | cut -d' ' -f4 | cut -d'.' -f2` >> $SETUP_LOG 2>&1 fi echo "Your MySQL client seems to be part of MySQL version $DB_CLIENT_MAJOR_VERSION.$DB_CLIENT_MINOR_VERSION." echo "MySQL client distribution version $DB_CLIENT_MAJOR_VERSION.$DB_CLIENT_MINOR_VERSION." >> $SETUP_LOG # Ensure mysql distribution is 4.1 or higher if [ $DB_CLIENT_MAJOR_VERSION -gt 4 ] then res=1 else if [ $DB_CLIENT_MAJOR_VERSION -eq 4 ] then if [ $DB_CLIENT_MINOR_VERSION -eq 1 ] then res=1 else res=0 fi else res=0 fi fi if [ $res -eq 0 ] then # Not 4.1 or higher, ask user to contnue ? echo "Your computer does not seem to be compliant with MySQL 4.1 or higher." echo -n "Do you wish to continue (y/[n])?" read ligne if [ "$ligne" = "y" ] then echo "Ensure your database server is running MySQL 4.1 or higher !" echo "Ensure also this computer is able to connect to your MySQL server !" else echo "Installation aborted !" exit 1 fi else echo "Your computer seems to be running MySQL 4.1 or higher, good ;-)" echo "Computer seems to be running MySQL 4.1 or higher" >> $SETUP_LOG fi echo # Ask user for database server host res=0 while [ $res -eq 0 ] do echo -n "Which host is running database server [$DB_SERVER_HOST] ?" read ligne if [ -z "$ligne" ] then res=1 else DB_SERVER_HOST="$ligne" res=1 fi done echo "OK, database server is running on host $DB_SERVER_HOST ;-)" echo "Database server is running on host $DB_SERVER_HOST" >> $SETUP_LOG echo # Ask user for database server port res=0 while [ $res -eq 0 ] do echo -n "On which port is running database server [$DB_SERVER_PORT] ?" read ligne if [ -z "$ligne" ] then res=1 else DB_SERVER_PORT="$ligne" res=1 fi done echo "OK, database server is running on port $DB_SERVER_PORT ;-)" echo "Database server is running on port $DB_SERVER_PORT" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for Apache web server daemon... |" echo "+----------------------------------------------------------+" echo echo "Checking for Apache web server daemon" >> $SETUP_LOG # Try to find Apache daemon if [ -z "$APACHE_BIN" ] then APACHE_BIN_FOUND=`which httpd 2>/dev/null` if [ -z "$APACHE_BIN_FOUND" ] then APACHE_BIN_FOUND=`which apache2ctl 2>/dev/null` if [ -z "$APACHE_BIN_FOUND" ] then APACHE_BIN_FOUND=`which apachectl 2>/dev/null` if [ -z "$APACHE_BIN_FOUND" ] then APACHE_BIN_FOUND=`which httpd2 2>/dev/null` fi fi fi fi echo "Found Apache daemon $APACHE_BIN_FOUND" >> $SETUP_LOG # Ask user's confirmation res=0 while [ $res -eq 0 ] do echo -n "Where is Apache daemon binary [$APACHE_BIN_FOUND] ?" read ligne if [ -z "$ligne" ] then APACHE_BIN=$APACHE_BIN_FOUND else APACHE_BIN="$ligne" fi # Ensure file exists and is executable if [ -x $APACHE_BIN ] then res=1 else echo "*** ERROR: $APACHE_BIN is not executable !" res=0 fi # Ensure file is not a directory if [ -d $APACHE_BIN ] then echo "*** ERROR: $APACHE_BIN is a directory !" res=0 fi done echo "OK, using Apache daemon $APACHE_BIN ;-)" echo "Using Apache daemon $APACHE_BIN" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for Apache main configuration file... |" echo "+----------------------------------------------------------+" echo # Try to find Apache main configuration file echo "Checking for Apache main configuration file" >> $SETUP_LOG if [ -z "$APACHE_CONFIG_FILE" ] then APACHE_ROOT=`eval $APACHE_BIN -V | grep "HTTPD_ROOT" | cut -d'=' -f2 | tr -d '"'` echo "Found Apache HTTPD_ROOT $APACHE_ROOT" >> $SETUP_LOG APACHE_CONFIG=`eval $APACHE_BIN -V | grep "SERVER_CONFIG_FILE" | cut -d'=' -f2 | tr -d '"'` echo "Found Apache SERVER_CONFIG_FILE $APACHE_CONFIG" >> $SETUP_LOG if [ -e $APACHE_CONFIG ] then APACHE_CONFIG_FILE_FOUND="$APACHE_CONFIG" else APACHE_CONFIG_FILE_FOUND="$APACHE_ROOT/$APACHE_CONFIG" fi fi echo "Found Apache main configuration file $APACHE_CONFIG_FILE_FOUND" >> $SETUP_LOG # Ask user's confirmation res=0 while [ $res -eq 0 ] do echo -n "Where is Apache main configuration file [$APACHE_CONFIG_FILE_FOUND] ?" read ligne if [ -z "$ligne" ] then APACHE_CONFIG_FILE=$APACHE_CONFIG_FILE_FOUND else APACHE_CONFIG_FILE="$ligne" fi # Ensure file is not a directory if [ -d $APACHE_CONFIG_FILE ] then echo "*** ERROR: $APACHE_CONFIG_FILE is a directory !" res=0 fi # Ensure file exists and is readable if [ -r $APACHE_CONFIG_FILE ] then res=1 else echo "*** ERROR: $APACHE_CONFIG_FILE is not readable !" res=0 fi done echo "OK, using Apache main configuration file $APACHE_CONFIG_FILE ;-)" echo "Using Apache main configuration file $APACHE_CONFIG_FILE" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for Apache user account... |" echo "+----------------------------------------------------------+" echo # Try to find Apache main configuration file echo "Checking for Apache user account" >> $SETUP_LOG if [ -z "$APACHE_USER" ] then case $UNIX_DISTRIBUTION in "debian") if [ -f /etc/apache2/envvars ] then . /etc/apache2/envvars fi APACHE_USER_FOUND=$APACHE_RUN_USER ;; "suse") if [ -f /etc/apache2/uid.conf ] then APACHE_USER_FOUND=`cat /etc/apache2/uid.conf | grep "User" | tail -1 | cut -d' ' -f2` fi ;; "redhat") APACHE_USER_FOUND=`cat $APACHE_CONFIG_FILE | grep "User " | tail -1 | cut -d' ' -f2` ;; esac fi echo "Found Apache user account $APACHE_USER_FOUND" >> $SETUP_LOG # Ask user's confirmation res=0 while [ $res -eq 0 ] do echo -n "Which user account is running Apache web server [$APACHE_USER_FOUND] ?" read ligne if [ -z "$ligne" ] then APACHE_USER=$APACHE_USER_FOUND else APACHE_USER="$ligne" fi # Ensure group exist in /etc/passwd if [ `cat /etc/passwd | grep $APACHE_USER | wc -l` -eq 0 ] then echo "*** ERROR: account $APACHE_USER not found in system table /etc/passwd !" else res=1 fi done echo "OK, Apache is running under user account $APACHE_USER ;-)" echo "Using Apache user account $APACHE_USER" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for Apache group... |" echo "+----------------------------------------------------------+" echo # Try to find Apache main configuration file echo "Checking for Apache group" >> $SETUP_LOG if [ -z "$APACHE_GROUP" ] then case $UNIX_DISTRIBUTION in "debian") if [ -f /etc/apache2/envvars ] then . /etc/apache2/envvars fi APACHE_GROUP_FOUND=$APACHE_RUN_USER ;; "suse") if [ -f /etc/apache2/uid.conf ] then APACHE_GROUP_FOUND=`cat /etc/apache2/uid.conf | grep "Group" | tail -1 | cut -d' ' -f2` fi ;; "redhat") APACHE_GROUP_FOUND=`cat $APACHE_CONFIG_FILE | grep "Group " | tail -1 | cut -d' ' -f2` ;; esac if [ -z "$APACHE_GROUP_FOUND" ] then # No group found, assume group name is the same as account echo "No Apache user group found, assuming group name is the same as user account" >> $SETUP_LOG APACHE_GROUP_FOUND=$APACHE_USER fi fi echo "Found Apache user group $APACHE_GROUP_FOUND" >> $SETUP_LOG # Ask user's confirmation res=0 while [ $res -eq 0 ] do echo -n "Which user group is running Apache web server [$APACHE_GROUP_FOUND] ?" read ligne if [ -z "$ligne" ] then APACHE_GROUP=$APACHE_GROUP_FOUND else APACHE_GROUP="$ligne" fi # Ensure group exist in /etc/group if [ `cat /etc/group | grep $APACHE_GROUP | wc -l` -eq 0 ] then echo "*** ERROR: group $APACHE_GROUP not found in system table /etc/group !" else res=1 fi done echo "OK, Apache is running under users group $APACHE_GROUP ;-)" echo "Using Apache user group $APACHE_GROUP" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for Apache Include configuration directory... |" echo "+----------------------------------------------------------+" echo # Try to find Apache includes configuration directory echo "Checking for Apache Include configuration directory" >> $SETUP_LOG if [ -z "$APACHE_CONFIG_DIRECTORY" ] then if [ -d "$APACHE_ROOT/conf.d" ] then APACHE_CONFIG_DIRECTORY_FOUND="$APACHE_ROOT/conf.d" elif [ -d "$APACHE_ROOT/conf-available" ] then APACHE_CONFIG_DIRECTORY_FOUND="$APACHE_ROOT/conf-available" else APACHE_CONFIG_DIRECTORY_FOUND="" fi if [ -d "$APACHE_CONFIG_DIRECTORY_FOUND" ] then echo "Found Apache Include configuration directory $APACHE_CONFIG_DIRECTORY_FOUND" >> $SETUP_LOG fi fi # Ask user's confirmation echo "Setup found Apache Include configuration directory in" echo "$APACHE_CONFIG_DIRECTORY_FOUND." echo "Setup will put OCS Inventory NG Apache configuration in this directory." res=0 while [ $res -eq 0 ] do echo -n "Where is Apache Include configuration directory [$APACHE_CONFIG_DIRECTORY_FOUND] ?" read ligne if [ -z "$ligne" ] then APACHE_CONFIG_DIRECTORY=$APACHE_CONFIG_DIRECTORY_FOUND else APACHE_CONFIG_DIRECTORY="$ligne" fi # Ensure file is a directory if [ -d $APACHE_CONFIG_DIRECTORY ] then res=1 else echo "*** ERROR: $APACHE_CONFIG_DIRECTORY is not a directory !" res=0 fi # Ensure directory exists and is writable if [ -w $APACHE_CONFIG_DIRECTORY ] then res=1 else echo "*** ERROR: $APACHE_CONFIG_DIRECTORY is not writable !" res=0 fi done echo "OK, Apache Include configuration directory $APACHE_CONFIG_DIRECTORY found ;-)" echo "Using Apache Include configuration directory $APACHE_CONFIG_DIRECTORY" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for PERL Interpreter... |" echo "+----------------------------------------------------------+" echo echo "Checking for PERL Interpreter" >> $SETUP_LOG if [ -z "$PERL_BIN" ] then echo "PERL Interpreter not found !" echo "PERL Interpreter not found" >> $SETUP_LOG echo "OCS Inventory NG is not able to work without PERL Interpreter." echo "Setup manually PERL first." echo "Installation aborted !" echo "installation aborted" >> $SETUP_LOG exit 1 else echo "Found PERL interpreter at <$PERL_BIN> ;-)" echo "Found PERL interpreter at <$PERL_BIN>" >> $SETUP_LOG fi # Ask user's confirmation res=0 while [ $res -eq 0 ] do echo -n "Where is PERL interpreter binary [$PERL_BIN] ?" read ligne if [ -n "$ligne" ] then PERL_BIN="$ligne" fi # Ensure file exists and is executable if [ -x $PERL_BIN ] then res=1 else echo "*** ERROR: $PERL_BIN is not executable !" res=0 fi # Ensure file is not a directory if [ -d $PERL_BIN ] then echo "*** ERROR: $PERL_BIN is a directory !" res=0 fi done echo "OK, using PERL interpreter $PERL_BIN ;-)" echo "Using PERL interpreter $PERL_BIN" >> $SETUP_LOG echo echo echo -n "Do you wish to setup Communication server on this computer ([y]/n)?" read ligne if [ -z "$ligne" ] || [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then # Setting up Communication server echo >> $SETUP_LOG echo "============================================================" >> $SETUP_LOG echo "Installing Communication server" >> $SETUP_LOG echo "============================================================" >> $SETUP_LOG echo echo echo "+----------------------------------------------------------+" echo "| Checking for Make utility... |" echo "+----------------------------------------------------------+" echo echo "Checking for Make utility" >> $SETUP_LOG if [ -z "$MAKE" ] then echo "Make utility not found !" echo "Make utility not found" >> $SETUP_LOG echo "Setup is not able to build OCS Inventory NG Perl module." echo "Unable to build OCS Inventory NG Perl module !" >> $SETUP_LOG exit 1 else echo "OK, Make utility found at <$MAKE> ;-)" echo "Make utility found at <$MAKE>" >> $SETUP_LOG fi echo echo "+----------------------------------------------------------+" echo "| Checking for Apache mod_perl version... |" echo "+----------------------------------------------------------+" echo echo "Checking for Apache mod_perl version 1.99_22 or higher" echo "Checking for Apache mod_perl version 1.99_22 or higher" >> $SETUP_LOG $PERL_BIN -mmod_perl2 -e 'print "mod_perl 1.99_22 or higher is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then # mod_perl 2 not found ! echo "Checking for Apache mod_perl version 1.99_21 or previous" echo "Checking for Apache mod_perl version 1.99_21 or previous" >> $SETUP_LOG $PERL_BIN -mmod_perl -e 'print "mod_perl 1.99_21 or previous is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then # mod_perl 1 not found => Ask user res=0 while [ $res -eq 0 ] do echo "Setup is unable to determine your Apache mod_perl version." echo "Apache must have module mod_perl enabled. As configuration differs from" echo "mod_perl 1.99_21 or previous AND mod_perl 1.99_22 or higher, Setup must" echo "know which release Apache is using." echo "You can find which release you are using by running the following command" echo " - On RPM enabled OS, rpm -q mod_perl" echo " - On DPKG enabled OS, dpkg -l libapache*-mod-perl*" echo "Enter 1 for mod_perl 1.99_21 or previous." echo "Enter 2 for mod_perl 1.99_22 and higher." echo -n "Which version of Apache mod_perl the computer is running ([1]/2) ?" read ligne if [ -z "$ligne" ] then APACHE_MOD_PERL_VERSION=1 else APACHE_MOD_PERL_VERSION=$ligne fi res=1 done else echo "Found that mod_perl version 1.99_21 or previous is available." APACHE_MOD_PERL_VERSION=1 fi else echo "Found that mod_perl version 1.99_22 or higher is available." APACHE_MOD_PERL_VERSION=2 fi if [ $APACHE_MOD_PERL_VERSION -eq 1 ] then echo "OK, Apache is using mod_perl version 1.99_21 or previous ;-)" echo "Using mod_perl version 1.99_21 or previous" >> $SETUP_LOG else echo "OK, Apache is using mod_perl version 1.99_22 or higher ;-)" echo "Using mod_perl version 1.99_22 or higher" >> $SETUP_LOG fi echo echo "+----------------------------------------------------------+" echo "| Checking for Communication server log directory... |" echo "+----------------------------------------------------------+" echo echo "Checking for Communication server log directory" >> $SETUP_LOG # Ask user res=0 while [ $res -eq 0 ] do echo "Communication server can create detailed logs. This logs can be enabled" echo "by setting integer value of LOGLEVEL to 1 in Administration console" echo "menu Configuration." echo -n "Where to put Communication server log directory [$OCS_COM_SRV_LOG] ?" read ligne if [ -n "$ligne" ] then OCS_COM_SRV_LOG=$ligne fi res=1 done echo "OK, Communication server will put logs into directory $OCS_COM_SRV_LOG ;-)" echo "Using $OCS_COM_SRV_LOG as Communication server log directory" >> $SETUP_LOG echo echo "+----------------------------------------------------------------------------+" echo "| Checking for Communication server plugins configuration directory... |" echo "+----------------------------------------------------------------------------+" echo echo "Checking for Communication server plugins configuration directory" >> $SETUP_LOG # Ask user res=0 while [ $res -eq 0 ] do echo "Communication server need a directory for plugins configuration files. " echo -n "Where to put Communication server plugins configuration files [$OCS_COM_SRV_PLUGINS_CONFIG_DIR] ?" read ligne if [ -n "$ligne" ] then OCS_COM_SRV_PLUGINS_CONFIG_DIR=$ligne fi res=1 done echo "OK, Communication server will put plugins configuration files into directory $OCS_COM_SRV_PLUGINS_CONFIG_DIR ;-)" echo "Using $OCS_COM_SRV_PLUGINS_CONFIG_DIR as Communication server plugins configuration directory" >> $SETUP_LOG echo echo "+-------------------------------------------------------------------+" echo "| Checking for Communication server plugins perl directory... |" echo "+-------------------------------------------------------------------+" echo echo "Checking for Communication server perl directory" >> $SETUP_LOG # Ask user res=0 while [ $res -eq 0 ] do echo "Communication server need a directory for plugins Perl modules files." echo -n "Where to put Communication server plugins Perl modules files [$OCS_COM_SRV_PLUGINS_PERL_DIR] ?" read ligne if [ -n "$ligne" ] then OCS_COM_SRV_PLUGINS_PERL_DIR=$ligne fi res=1 done echo "OK, Communication server will put plugins Perl modules files into directory $OCS_COM_SRV_PLUGINS_PERL_DIR ;-)" echo "Using $OCS_COM_SRV_PLUGINS_PERL_DIR as Communication server plugins perl directory" >> $SETUP_LOG echo # jump to communication server directory echo "Entering Apache sub directory" >> $SETUP_LOG # Check for required Perl Modules (if missing, please install before) # - DBI 1.40 or higher # - Apache::DBI 0.93 or higher # - DBD::mysql 2.9004 or higher # - Compress::Zlib 1.33 or higher # - XML::Simple 2.12 or higher # - Net::IP 1.21 or higher # - Archive::Zip echo echo "+----------------------------------------------------------+" echo "| Checking for required Perl Modules... |" echo "+----------------------------------------------------------+" echo REQUIRED_PERL_MODULE_MISSING=0 DBI=0 APACHE_DBI=0 DBD_MYSQL=0 COMPRESS_ZLIB=0 XML_SIMPLE=0 NET_IP=0 ARCHIVE_ZIP=0 echo "Checking for DBI PERL module..." echo "Checking for DBI PERL module" >> $SETUP_LOG $PERL_BIN -mDBI -e 'print "PERL module DBI is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module DBI is not installed !" REQUIRED_PERL_MODULE_MISSING=1 DBI=1 else echo "Found that PERL module DBI is available." fi echo "Checking for Apache::DBI PERL module..." echo "Checking for Apache::DBI PERL module" >> $SETUP_LOG $PERL_BIN -mApache::DBI -e 'print "PERL module Apache::DBI is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Apache::DBI is not installed !" REQUIRED_PERL_MODULE_MISSING=1 APACHE_DBI=1 else echo "Found that PERL module Apache::DBI is available." fi echo "Checking for DBD::mysql PERL module..." echo "Checking for DBD::mysql PERL module" >> $SETUP_LOG $PERL_BIN -mDBD::mysql -e 'print "PERL module DBD::mysql is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module DBD::mysql is not installed !" REQUIRED_PERL_MODULE_MISSING=1 DBD_MYSQL=1 else echo "Found that PERL module DBD::mysql is available." fi echo "Checking for Compress::Zlib PERL module..." echo "Checking for Compress::Zlib PERL module" >> $SETUP_LOG $PERL_BIN -mCompress::Zlib -e 'print "PERL module Compress::Zlib is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Compress::Zlib is not installed !" REQUIRED_PERL_MODULE_MISSING=1 COMPRESS_ZLIB=1 else echo "Found that PERL module Compress::Zlib is available." fi echo "Checking for XML::Simple PERL module..." echo "Checking for XML::Simple PERL module" >> $SETUP_LOG $PERL_BIN -mXML::Simple -e 'print "PERL module XML::Simple is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module XML::Simple is not installed !" REQUIRED_PERL_MODULE_MISSING=1 XML_SIMPLE=1 else echo "Found that PERL module XML::Simple is available." fi echo "Checking for Net::IP PERL module..." echo "Checking for Net::IP PERL module" >> $SETUP_LOG $PERL_BIN -mNet::IP -e 'print "PERL module Net::IP is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Net::IP is not installed !" REQUIRED_PERL_MODULE_MISSING=1 NET_IP=1 else echo "Found that PERL module Net::IP is available." fi # Check for Zip::Archive echo "Checking for Archive::Zip Perl module..." echo "Checking for Archive::Zip Perl module" >> $SETUP_LOG $PERL_BIN -mArchive::Zip -e 'print "PERL module Archive::Zip is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Archive::Zip is not installed !" REQUIRED_PERL_MODULE_MISSING=1 ARCHIVE_ZIP=1 else echo "Found that PERL module Archive::Zip is available." fi if [ $REQUIRED_PERL_MODULE_MISSING -ne 0 ] then echo "*** ERROR: There is one or more required PERL modules missing on your computer !" echo "Please, install missing PERL modules first." echo " " echo "OCS setup.sh can install perl module from packages for you" echo "The script will use the native package from your operating system like apt or rpm" echo -n "Do you wish to continue (y/[n])?" read ligne if [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then case $UNIX_DISTRIBUTION in "redhat") echo "RedHat based automatic installation" if [ $DBI -eq 1 ] then PACKAGE="$PACKAGE perl-DBI" fi if [ $APACHE_DBI -eq 1 ] then PACKAGE="$PACKAGE perl-Apache-DBI" fi if [ $DBD_MYSQL -eq 1 ] then PACKAGE="$PACKAGE perl-DBD-MySQL" fi if [ $COMPRESS_ZLIB -eq 1 ] then PACKAGE="$PACKAGE perl-Compress-Zlib" fi if [ $XML_SIMPLE -eq 1 ] then PACKAGE="$PACKAGE perl-XML-Simple" fi if [ $NET_IP -eq 1 ] then PACKAGE="$PACKAGE perl-Net-IP" fi if [ $ARCHIVE_ZIP -eq 1 ] then PACKAGE="$PACKAGE perl-Archive-Zip" fi yum install $PACKAGE if [ $? != 0 ] then echo "Installation aborted !" echo "Installation script encounter problems to install packages !" echo "One or more required PERL modules missing !" >> $SETUP_LOG echo "Installation aborted" >> $SETUP_LOG exit 1 fi echo "All packages have been installed on this computer" ;; "debian") echo "Debian based automatic installation" if [ $DBI -eq 1 ] then PACKAGE="$PACKAGE libdbi-perl" fi if [ $APACHE_DBI -eq 1 ] then PACKAGE="$PACKAGE libapache-dbi-perl" fi if [ $DBD_MYSQL -eq 1 ] then PACKAGE="$PACKAGE libdbd-mysql-perl" fi if [ $COMPRESS_ZLIB -eq 1 ] then PACKAGE="$PACKAGE libcompress-zlib-perl" fi if [ $XML_SIMPLE -eq 1 ] then PACKAGE="$PACKAGE libxml-simple-perl" fi if [ $NET_IP -eq 1 ] then PACKAGE="$PACKAGE libnet-ip-perl" fi if [ $ARCHIVE_ZIP -eq 1 ] then PACKAGE="$PACKAGE libarchive-zip-perl" fi apt-get update apt-get install $PACKAGE if [ $? -ne 0 ] then echo "Installation aborted !" echo "Installation script encounter problems to install packages !" echo "One or more required PERL modules missing !" >> $SETUP_LOG echo "Installation aborted" >> $SETUP_LOG exit 1 fi echo "All packages have been installed on this computer" ;; *) echo "Installation aborted !" echo "Installation script cannot find missing packages for your distribution" echo "One or more required PERL modules missing !" >> $SETUP_LOG echo "Installation aborted" >> $SETUP_LOG exit 1 ;; esac else echo "Installation aborted !" echo "Please, install missing PERL modules first." echo "One or more required PERL modules missing !" >> $SETUP_LOG echo "Installation aborted" >> $SETUP_LOG exit 1 fi fi echo echo echo -n "Do you wish to setup Rest API server on this computer ([y]/n)?" read ligne if [ -z "$ligne" ] || [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo echo "+----------------------------------------------------------+" echo "| Checking for REST API Dependencies ... |" echo "+----------------------------------------------------------+" echo # Dependencies : # => Mojolicious::Lite # => Plack # => Switch $PERL_BIN -mMojolicious::Lite -e 'print "PERL module Mojolicious::Lite is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Mojolicious::Lite is not installed !" echo -n "Do you wish to continue (y/[n])?" read ligne if [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo "User choose to continue setup without PERL module Mojolicious::Lite" >> $SETUP_LOG else echo echo "Installation aborted !" echo "User choose to abort installation !" >> $SETUP_LOG exit 1 fi else echo "Found that PERL module Mojolicious::Lite is available." fi $PERL_BIN -mSwitch -e 'print "PERL module Switch is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Switch is not installed !" echo -n "Do you wish to continue (y/[n])?" read ligne if [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo "User choose to continue setup without PERL module Switch" >> $SETUP_LOG else echo echo "Installation aborted !" echo "User choose to abort installation !" >> $SETUP_LOG exit 1 fi else echo "Found that PERL module Switch is available." fi $PERL_BIN -mPlack::Handler -e 'print "PERL module Plack::Handler is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Plack::Handler is not installed !" echo -n "Do you wish to continue (y/[n])?" read ligne if [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo "User choose to continue setup without PERL module Plack::Handler" >> $SETUP_LOG else echo echo "Installation aborted !" echo "User choose to abort installation !" >> $SETUP_LOG exit 1 fi else echo "Found that PERL module Plack::Handler is available." fi echo echo "+----------------------------------------------------------+" echo "| Configuring REST API Server files ... |" echo "+----------------------------------------------------------+" echo # Get first INC path to determine a valid path REST_API_DIRECTORY=$($PERL_BIN -e "print \"@INC[2]\"") echo -n "Where do you want the API code to be store [$REST_API_DIRECTORY] ?" read ligne if [ -z "$ligne" ] then REST_API_DIRECTORY=$REST_API_DIRECTORY else REST_API_DIRECTORY="$ligne" fi echo "Copying files to $REST_API_DIRECTORY" echo "Copying files to $REST_API_DIRECTORY" >> $SETUP_LOG echo echo "+----------------------------------------------------------+" echo "| Configuring REST API Server configuration files ... |" echo "+----------------------------------------------------------+" echo echo "Configuring Rest API server (file $API_REST_APACHE_CONF_FILE)" >> $SETUP_LOG cp etc/ocsinventory/$API_REST_APACHE_CONF_FILE $API_REST_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#'REST_API_PATH'#'$REST_API_DIRECTORY'#g" $API_REST_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#'REST_API_LOADER_PATH'#'$REST_API_DIRECTORY/Api/Ocsinventory/Restapi/Loader.pm'#g" $API_REST_APACHE_CONF_FILE.local echo "Writing Rest API configuration to file $APACHE_CONFIG_DIRECTORY/$API_REST_APACHE_CONF_FILE" >> $SETUP_LOG cp -f $API_REST_APACHE_CONF_FILE.local $APACHE_CONFIG_DIRECTORY/zz-$API_REST_APACHE_CONF_FILE >> $SETUP_LOG 2>&1 cp -r Api/ $REST_API_DIRECTORY fi echo echo "+----------------------------------------------------------+" echo "| OK, looks good ;-) |" echo "| |" echo "| Configuring Communication server Perl modules... |" echo "+----------------------------------------------------------+" echo echo "Configuring Communication server (perl Makefile.PL)" >> $SETUP_LOG cd "Apache" $PERL_BIN Makefile.PL if [ $? -ne 0 ] then echo -n "Warning: Prerequisites too old ! Do you wish to continue (y/[n])?" read ligne if [ "$ligne" = "y" ] then echo "Maybe Communication server will encounter problems. Continuing anyway." echo "Warning: Prerequisites too old ! Continuing anyway" >> $SETUP_LOG else echo "Installation aborted !" exit 1 fi fi echo echo "+----------------------------------------------------------+" echo "| OK, looks good ;-) |" echo "| |" echo "| Preparing Communication server Perl modules... |" echo "+----------------------------------------------------------+" echo echo "Preparing Communication server Perl modules (make)" >> $SETUP_LOG $MAKE >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Prepare failed, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo echo "+----------------------------------------------------------+" echo "| OK, prepare finshed ;-) |" echo "| |" echo "| Installing Communication server Perl modules... |" echo "+----------------------------------------------------------+" echo echo "Installing Communication server Perl modules (make install)" >> $SETUP_LOG $MAKE install >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Install of Perl modules failed, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi cd ".." echo echo "+----------------------------------------------------------+" echo "| OK, Communication server Perl modules install finished;-)|" echo "| |" echo "| Creating Communication server log directory... |" echo "+----------------------------------------------------------+" echo echo "Creating Communication server log directory $OCS_COM_SRV_LOG." echo "Creating Communication server log directory $OCS_COM_SRV_LOG" >> $SETUP_LOG mkdir -p $OCS_COM_SRV_LOG >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to create log directory, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo echo "Fixing Communication server log directory files permissions." echo "Fixing Communication server log directory permissions" >> $SETUP_LOG chown -R $APACHE_USER:$APACHE_GROUP $OCS_COM_SRV_LOG >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set log directory permissions, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi chmod -R gu+rwx $OCS_COM_SRV_LOG >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set log directory permissions, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi chmod -R o-w $OCS_COM_SRV_LOG >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set log directory permissions, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Log rotation, BSD style if [ -f $NEWSYSLOG_CONF_FILE ] then echo "*** WARNING Please configure log rotation for files in $OCS_COM_SRV_LOG" fi # Log rotation, Linux flavor if [ -d $LOGROTATE_CONF_DIR ] then echo "Configuring logrotate for Communication server." echo "Configuring logrotate (ed logrotate.ocsinventory-NG)" >> $SETUP_LOG cp etc/logrotate.d/$COM_SERVER_LOGROTATE_CONF_FILE logrotate.$COM_SERVER_LOGROTATE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_LOG_DIRECTORY#$OCS_COM_SRV_LOG#g" logrotate.$COM_SERVER_LOGROTATE_CONF_FILE.local echo "******** Begin updated logrotate.$COM_SERVER_LOGROTATE_CONF_FILE.local ***********" >> $SETUP_LOG cat logrotate.$COM_SERVER_LOGROTATE_CONF_FILE.local >> $SETUP_LOG echo "******** End updated logrotate.COM_SERVER_LOGROTATE_CONF_FILE.local ***********" >> $SETUP_LOG echo "Removing old communication server logrotate file $LOGROTATE_CONF_DIR/ocsinventory-NG" echo "Removing old communication server logrotate file $LOGROTATE_CONF_DIR/ocsinventory-NG" >> $SETUP_LOG rm -f "$LOGROTATE_CONF_DIR/ocsinventory-NG" echo "Writing communication server logrotate to file $LOGROTATE_CONF_DIR/$COM_SERVER_LOGROTATE_CONF_FILE" echo "Writing communication server logrotate to file $LOGROTATE_CONF_DIR/$COM_SERVER_LOGROTATE_CONF_FILE" >> $SETUP_LOG cp -f logrotate.$COM_SERVER_LOGROTATE_CONF_FILE.local $LOGROTATE_CONF_DIR/$COM_SERVER_LOGROTATE_CONF_FILE >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to configure log rotation, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi fi echo echo echo "+----------------------------------------------------------------------+" echo "| OK, Communication server log directory created ;-) |" echo "| |" echo "| Creating Communication server plugins configuration directory... |" echo "+----------------------------------------------------------------------+" echo echo "Creating Communication server plugins configuration directory $OCS_COM_SRV_PLUGINS_CONFIG_DIR." echo "Creating Communication server plugins configuration directory $OCS_COM_SRV_PLUGINS_CONFIG_DIR" >> $SETUP_LOG mkdir -p $OCS_COM_SRV_PLUGINS_CONFIG_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to create plugins confguration directory, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo echo echo "+----------------------------------------------------------------------+" echo "| OK, Communication server plugins configuration directory created ;-) |" echo "| |" echo "| Creating Communication server plugins Perl directory... |" echo "+----------------------------------------------------------------------+" echo echo "Creating Communication server plugins Perl directory $OCS_COM_SRV_PLUGINS_PERL_DIR." echo "Creating Communication server plugins Perl directory $OCS_COM_SRV_PLUGINS_PERL_DIR" >> $SETUP_LOG mkdir -p "$OCS_COM_SRV_PLUGINS_PERL_DIR/Apache/Ocsinventory/Plugins" >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to create plugins Perl directory, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo #Fix permissions on server side for plugin engine (perl / plugins) dir usually in etc/ocsinventory-server.. # Where are located OCS Communication server plugins configuration files chown -R $APACHE_USER:$APACHE_GROUPE $OCS_COM_SRV_PLUGINS_CONFIG_DIR # Where are located OCS Communication server plugins perl files chown -R $APACHE_USER:$APACHE_GROUPE $OCS_COM_SRV_PLUGINS_PERL_DIR echo echo "+----------------------------------------------------------------------+" echo "| OK, Communication server plugins Perl directory created ;-) |" echo "| |" echo "| Now configuring Apache web server... |" echo "+----------------------------------------------------------------------+" echo echo "To ensure Apache loads mod_perl before OCS Inventory NG Communication Server," echo "Setup can name Communication Server Apache configuration file" echo "'z-$COM_SERVER_APACHE_CONF_FILE' instead of '$COM_SERVER_APACHE_CONF_FILE'." echo "Do you allow Setup renaming Communication Server Apache configuration file" echo -n "to 'z-$COM_SERVER_APACHE_CONF_FILE' ([y]/n) ?" read ligne if [ -z $ligne ] || [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo "OK, using 'z-$COM_SERVER_APACHE_CONF_FILE' as Communication Server Apache configuration file" echo "OK, using 'z-$COM_SERVER_APACHE_CONF_FILE' as Communication Server Apache configuration file" >> $SETUP_LOG FORCE_LOAD_AFTER_PERL_CONF=1 else echo "OK, using '$COM_SERVER_APACHE_CONF_FILE' as Communication Server Apache configuration file" echo "OK, using '$COM_SERVER_APACHE_CONF_FILE' as Communication Server Apache configuration file" >> $SETUP_LOG FORCE_LOAD_AFTER_PERL_CONF=0 fi echo "Configuring Apache web server (file $COM_SERVER_APACHE_CONF_FILE)" >> $SETUP_LOG cp etc/ocsinventory/$COM_SERVER_APACHE_CONF_FILE $COM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#DATABASE_SERVER#$DB_SERVER_HOST#g" $COM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#DATABASE_PORT#$DB_SERVER_PORT#g" $COM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#VERSION_MP#$APACHE_MOD_PERL_VERSION#g" $COM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_LOG_DIRECTORY#$OCS_COM_SRV_LOG#g" $COM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_PLUGINS_CONFIG_DIRECTORY#$OCS_COM_SRV_PLUGINS_CONFIG_DIR#g" $COM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_PLUGINS_PERL_DIRECTORY#$OCS_COM_SRV_PLUGINS_PERL_DIR#g" $COM_SERVER_APACHE_CONF_FILE.local echo "******** Begin updated $COM_SERVER_APACHE_CONF_FILE.local ***********" >> $SETUP_LOG cat $COM_SERVER_APACHE_CONF_FILE.local >> $SETUP_LOG echo "******** End updated $COM_SERVER_APACHE_CONF_FILE.local ***********" >> $SETUP_LOG echo "Removing old communication server configuration to file $APACHE_CONFIG_DIRECTORY/ocsinventory.conf" echo "Removing old communication server configuration to file $APACHE_CONFIG_DIRECTORY/ocsinventory.conf" >> $SETUP_LOG rm -f "$APACHE_CONFIG_DIRECTORY/ocsinventory.conf" if [ $FORCE_LOAD_AFTER_PERL_CONF -eq 1 ] then rm -f "$APACHE_CONFIG_DIRECTORY/$COM_SERVER_APACHE_CONF_FILE" echo "Writing communication server configuration to file $APACHE_CONFIG_DIRECTORY/z-$COM_SERVER_APACHE_CONF_FILE" echo "Writing communication server configuration to file $APACHE_CONFIG_DIRECTORY/z-$COM_SERVER_APACHE_CONF_FILE" >> $SETUP_LOG cp -f $COM_SERVER_APACHE_CONF_FILE.local $APACHE_CONFIG_DIRECTORY/z-$COM_SERVER_APACHE_CONF_FILE >> $SETUP_LOG 2>&1 res=$? COM_SERVER_APACHE_CONF_FILE="z-$COM_SERVER_APACHE_CONF_FILE" else echo "Writing communication server configuration to file $APACHE_CONFIG_DIRECTORY/$COM_SERVER_APACHE_CONF_FILE" echo "Writing communication server configuration to file $APACHE_CONFIG_DIRECTORY/$COM_SERVER_APACHE_CONF_FILE" >> $SETUP_LOG cp -f $COM_SERVER_APACHE_CONF_FILE.local $APACHE_CONFIG_DIRECTORY/$COM_SERVER_APACHE_CONF_FILE >> $SETUP_LOG 2>&1 res=$? fi if [ $res -ne 0 ] then echo "*** ERROR: Unable to write $APACHE_CONFIG_DIRECTORY/$COM_SERVER_APACHE_CONF_FILE, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo echo "+----------------------------------------------------------------------+" echo "| OK, Communication server setup successfully finished ;-) |" echo "| |" echo "| Please, review $APACHE_CONFIG_DIRECTORY/$COM_SERVER_APACHE_CONF_FILE |" echo "| to ensure all is good. Then restart Apache daemon. |" echo "+----------------------------------------------------------------------+" echo echo "Leaving Apache directory" >> $SETUP_LOG echo "Communication server installation successful" >> $SETUP_LOG fi echo echo "Do you wish to setup Administration Server (Web Administration Console)" echo -n "on this computer ([y]/n)?" read ligne if [ -z "$ligne" ] || [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then # Install Administration server echo >> $SETUP_LOG echo "============================================================" >> $SETUP_LOG echo "Installing Administration server" >> $SETUP_LOG echo "============================================================" >> $SETUP_LOG echo echo "+----------------------------------------------------------+" echo "| Checking for Administration Server directories... |" echo "+----------------------------------------------------------+" echo echo "CAUTION: Setup now install files in accordance with Filesystem Hierarchy" echo "Standard. So, no file is installed under Apache root document directory" echo "(Refer to Apache configuration files to locate it)." echo "If you're upgrading from OCS Inventory NG Server 1.01 and previous, YOU" echo "MUST REMOVE (or move) directories 'ocsreports' and 'download' from Apache" echo "root document directory." echo "If you choose to move directory, YOU MUST MOVE 'download' directory to" echo "Administration Server writable/cache directory (by default" echo "$ADM_SERVER_VAR_DIR), especially if you use deployment feature." echo echo -n "Do you wish to continue ([y]/n)?" read ligne if [ -z "$ligne" ] || [ "$ligne" = "y" ] || [ "$ligne" = "Y" ] then echo "Assuming directories 'ocsreports' and 'download' removed from" echo "Apache root document directory." echo else echo "Installation aborted !" echo exit 1 fi echo "Checking for Administration Server directories..." >> $SETUP_LOG echo "Where to copy Administration Server static files for PHP Web Console" echo -n "[$ADM_SERVER_STATIC_DIR] ?" read ligne if test -z $ligne then ADM_SERVER_STATIC_DIR=$ADM_SERVER_STATIC_DIR else ADM_SERVER_STATIC_DIR="$ligne" fi echo "OK, using directory $ADM_SERVER_STATIC_DIR to install static files ;-)" echo "Using directory $ADM_SERVER_STATIC_DIR for static files" >> $SETUP_LOG echo echo "Where to create writable/cache directories for deployment packages," echo -n "administration console logs, IPDiscover and SNMP [$ADM_SERVER_VAR_DIR] ?" read ligne if test -z $ligne then ADM_SERVER_VAR_DIR=$ADM_SERVER_VAR_DIR else ADM_SERVER_VAR_DIR="$ligne" fi echo "OK, writable/cache directory is $ADM_SERVER_VAR_DIR ;-)" echo "Using $ADM_SERVER_VAR_DIR as writable/cache directory" >> $SETUP_LOG echo # Check for required Perl Modules (if missing, please install before) # - DBI 1.40 or higher # - DBD::mysql 2.9004 or higher # - XML::Simple 2.12 or higher # - Net::IP 1.21 or higher # echo echo "+----------------------------------------------------------+" echo "| Checking for required Perl Modules... |" echo "+----------------------------------------------------------+" echo REQUIRED_PERL_MODULE_MISSING=0 echo "Checking for DBI PERL module..." echo "Checking for DBI PERL module" >> $SETUP_LOG $PERL_BIN -mDBI -e 'print "PERL module DBI is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module DBI is not installed !" REQUIRED_PERL_MODULE_MISSING=1 else echo "Found that PERL module DBI is available." fi echo "Checking for DBD::mysql PERL module..." echo "Checking for DBD::mysql PERL module" >> $SETUP_LOG $PERL_BIN -mDBD::mysql -e 'print "PERL module DBD::mysql is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module DBD::mysql is not installed !" REQUIRED_PERL_MODULE_MISSING=1 else echo "Found that PERL module DBD::mysql is available." fi echo "Checking for XML::Simple PERL module..." echo "Checking for XML::Simple PERL module" >> $SETUP_LOG $PERL_BIN -mXML::Simple -e 'print "PERL module XML::Simple is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module XML::Simple is not installed !" REQUIRED_PERL_MODULE_MISSING=1 else echo "Found that PERL module XML::Simple is available." fi echo "Checking for Net::IP PERL module..." echo "Checking for Net::IP PERL module" >> $SETUP_LOG $PERL_BIN -mNet::IP -e 'print "PERL module Net::IP is available\n"' >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: PERL module Net::IP is not installed !" REQUIRED_PERL_MODULE_MISSING=1 else echo "Found that PERL module Net::IP is available." fi if [ $REQUIRED_PERL_MODULE_MISSING -ne 0 ] then echo "*** ERROR: There is one or more required PERL modules missing on your computer !" echo "Please, install missing PERL modules first." echo "Installation aborted !" echo "One or more required PERL modules missing !" >> $SETUP_LOG echo "Installation aborted" >> $SETUP_LOG exit 1 fi echo echo "+----------------------------------------------------------+" echo "| Installing files for Administration server... |" echo "+----------------------------------------------------------+" echo echo "Creating PHP directory $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR." echo "Creating PHP directory $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR" >> $SETUP_LOG mkdir -p $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR >> $SETUP_LOG 2>&1 if [ $? != 0 ] then echo "*** ERROR: Unable to create $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Copying PHP files to $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR." echo "Copying PHP files to $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR" >> $SETUP_LOG cp -Rf ocsreports/* $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/ >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to copy files in $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on directory $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR." echo "Fixing permissions on directory $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR" >> $SETUP_LOG # Set PHP pages directory owned by root, group Apache chown -R root:$APACHE_GROUP $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR >> $SETUP_LOG 2>&1 # Set "download/" "upload/" "plugins/main_section" "plugins/computer_detail" "plugins/language" "config/" own to apache chown -R $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/config >> $SETUP_LOG 2>&1 chown -R $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/plugins/computer_detail >> $SETUP_LOG 2>&1 chown -R $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/plugins/main_sections >> $SETUP_LOG 2>&1 chown -R $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/plugins/language >> $SETUP_LOG 2>&1 chown -R $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/download >> $SETUP_LOG 2>&1 chown -R $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/upload >> $SETUP_LOG 2>&1 chown $APACHE_USER:$APACHE_GROUPE $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set PHP pages writable by root only chmod -R go-w $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set database configuration file dbconfig.inc.php writable by Apache echo "Creating database configuration file $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php." echo "Creating database configuration file $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php" >> $SETUP_LOG rm -f $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo "> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo -n '$_SESSION["SERVEUR_SQL"]="' >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo -n "$DB_SERVER_HOST" >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo '";' >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo -n '$_SESSION["COMPTE_BASE"]="' >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo -n "$DB_SERVER_USER" >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo '";' >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo -n '$_SESSION["PSWD_BASE"]="' >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo -n "$DB_SERVER_PWD" >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo '";' >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php echo "?>" >> $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php chown root:$APACHE_GROUP $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php chmod g+w $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/dbconfig.inc.php, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Creating IPDiscover directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR." echo "Creating IPDiscover directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR" >> $SETUP_LOG mkdir -p $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR >> $SETUP_LOG 2>&1 if [ $? != 0 ] then echo "*** ERROR: Unable to create $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR." echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR" >> $SETUP_LOG # Set IPD area owned by root, group Apache chown -R root:$APACHE_GROUP $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set IPD area writable by root only chmod -R go-w $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set IPD area writable by Apache group chmod g+w $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi #Create packages directory echo "Creating packages directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR." echo "Creating packages directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR" >> $SETUP_LOG mkdir -p $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR >> $SETUP_LOG 2>&1 if [ $? != 0 ] then echo "*** ERROR: Unable to create $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR." echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR" >> $SETUP_LOG # Set package area owned by root, group Apache chown -R root:$APACHE_GROUP $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set package area writable by root and Apache group only chmod -R g+w,o-w $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Create snmp custom mibs directory echo "Creating snmp mibs directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR." echo "Creating snmp mibs directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR" >> $SETUP_LOG mkdir -p $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR >> $SETUP_LOG 2>&1 if [ $? != 0 ] then echo "*** ERROR: Unable to create $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR." echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR" >> $SETUP_LOG # Set snmp area owned by root, group Apache chown -R root:$APACHE_GROUP $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set snmp area writable by root and Apache group only chmod -R g+w,o-w $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Create logs directory echo "Creating Administration server log files directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR." echo "Creating Administration server log files directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR" >> $SETUP_LOG mkdir -p $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR >> $SETUP_LOG 2>&1 if [ $? != 0 ] then echo "*** ERROR: Unable to create $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR." echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR" >> $SETUP_LOG # Set log files area owned by root, group Apache chown -R root:$APACHE_GROUP $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set log files area writable by root and Apache group only chmod -R g+w,o-w $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_LOGS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Creating Administration server scripts log files directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR." echo "Creating Administration server scripts log files directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR" >> $SETUP_LOG mkdir -p $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR >> $SETUP_LOG 2>&1 if [ $? != 0 ] then echo "*** ERROR: Unable to create $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR." echo "Fixing permissions on directory $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR" >> $SETUP_LOG # Set scripts log files area owned by root, group Apache chown -R root:$APACHE_GROUP $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi # Set scripts log files area writable by root and Apache group only chmod -R g+w,o-w $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SCRIPTS_LOGS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Configuring IPDISCOVER-UTIL Perl script." echo "Configuring IPDISCOVER-UTIL Perl script (ed ipdiscover-util.pl)" >> $SETUP_LOG cp binutils/ipdiscover-util.pl ipdiscover-util.pl.local >> $SETUP_LOG 2>&1 $PERL_BIN -pi -e "s#localhost#$DB_SERVER_HOST#g" ipdiscover-util.pl.local $PERL_BIN -pi -e "s#3306#$DB_SERVER_PORT#g" ipdiscover-util.pl.local # echo "******** Begin updated ipdiscover-util.pl.local script ***********" >> $SETUP_LOG # cat ipdiscover-util.pl.local >> $SETUP_LOG # echo "******** End updated ipdiscover-util.pl.local script ***********" >> $SETUP_LOG echo "Installing IPDISCOVER-UTIL Perl script." echo "Installing IPDISCOVER-UTIL Perl script" >> $SETUP_LOG cp ipdiscover-util.pl.local $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/ipdiscover-util.pl >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to copy files in $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Fixing permissions on IPDISCOVER-UTIL Perl script." echo "Fixing permissions on IPDISCOVER-UTIL Perl script" >> $SETUP_LOG chown root:$APACHE_GROUP $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/ipdiscover-util.pl >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi chmod gou+x $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR/ipdiscover-util.pl >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to set permissions on $ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo "Configuring Apache web server (file $ADM_SERVER_APACHE_CONF_FILE)" >> $SETUP_LOG cp etc/ocsinventory/$ADM_SERVER_APACHE_CONF_FILE $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#OCSREPORTS_ALIAS#$ADM_SERVER_REPORTS_ALIAS#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_OCSREPORTS_DIR#$ADM_SERVER_STATIC_DIR/$ADM_SERVER_STATIC_REPORTS_DIR#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#IPD_ALIAS#$ADM_SERVER_IPD_ALIAS#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_IPD_DIR#$ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_IPD_DIR#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PACKAGES_ALIAS#$ADM_SERVER_PACKAGES_ALIAS#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_PACKAGES_DIR#$ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_PACKAGES_DIR#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#SNMP_ALIAS#$ADM_SERVER_SNMP_ALIAS#g" $ADM_SERVER_APACHE_CONF_FILE.local $PERL_BIN -pi -e "s#PATH_TO_SNMP_DIR#$ADM_SERVER_VAR_DIR/$ADM_SERVER_VAR_SNMP_DIR#g" $ADM_SERVER_APACHE_CONF_FILE.local echo "******** Begin updated $ADM_SERVER_APACHE_CONF_FILE.local ***********" >> $SETUP_LOG cat $ADM_SERVER_APACHE_CONF_FILE.local >> $SETUP_LOG echo "******** End updated $ADM_SERVER_APACHE_CONF_FILE.local ***********" >> $SETUP_LOG echo "Writing Administration server configuration to file $APACHE_CONFIG_DIRECTORY/$ADM_SERVER_APACHE_CONF_FILE" echo "Writing communication server configuration to file $APACHE_CONFIG_DIRECTORY/$ADM_SERVER_APACHE_CONF_FILE" >> $SETUP_LOG cp -f $ADM_SERVER_APACHE_CONF_FILE.local $APACHE_CONFIG_DIRECTORY/$ADM_SERVER_APACHE_CONF_FILE >> $SETUP_LOG 2>&1 if [ $? -ne 0 ] then echo "*** ERROR: Unable to write $APACHE_CONFIG_DIRECTORY/$ADM_SERVER_APACHE_CONF_FILE, please look at error in $SETUP_LOG and fix !" echo echo "Installation aborted !" exit 1 fi echo echo "+----------------------------------------------------------------------+" echo "| OK, Administration server installation finished ;-) |" echo "| |" echo "| Please, review $APACHE_CONFIG_DIRECTORY/$ADM_SERVER_APACHE_CONF_FILE" echo "| to ensure all is good and restart Apache daemon. |" echo "| |" echo "| Then, point your browser to http://server/$ADM_SERVER_REPORTS_ALIAS" echo "| to configure database server and create/update schema. |" echo "+----------------------------------------------------------------------+" echo echo "Administration server installation successful" >> $SETUP_LOG fi echo echo "Setup has created a log file $SETUP_LOG. Please, save this file." echo "If you encounter error while running OCS Inventory NG Management server," echo "we can ask you to show us its content !" echo echo "DON'T FORGET TO RESTART APACHE DAEMON !" echo echo "Enjoy OCS Inventory NG ;-)" echo exit 0