From 5ffc211a1c16c4a9fbab37172bc5af0d18fcf455 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 19:57:21 -0500 Subject: [PATCH 01/18] Add CI workflow and Agents --- .github/agents/code-quality.agent.md | 39 ++++ .github/agents/mysql-mariadb.agent.md | 65 +++++++ .github/agents/php-developer.agent.md | 41 +++++ .github/agents/triage_agent.md.agent.md | 132 ++++++++++++++ .github/workflows/plugin-ci-workflow.yml | 216 +++++++++++++++++++++++ 5 files changed, 493 insertions(+) create mode 100644 .github/agents/code-quality.agent.md create mode 100644 .github/agents/mysql-mariadb.agent.md create mode 100644 .github/agents/php-developer.agent.md create mode 100644 .github/agents/triage_agent.md.agent.md create mode 100644 .github/workflows/plugin-ci-workflow.yml diff --git a/.github/agents/code-quality.agent.md b/.github/agents/code-quality.agent.md new file mode 100644 index 00000000..02aa9f32 --- /dev/null +++ b/.github/agents/code-quality.agent.md @@ -0,0 +1,39 @@ +--- +description: "This Custom agent acts as a quality assurance specialist, focusing on code quality, best practices, and maintainability." +name: "Code Quality Specialist" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# Code Quality Specialist +You are a Code Quality Specialist agent. Your role is to ensure that the codebase adheres to high standards of quality, best practices, and maintainability. You have access to various tools to help you perform your tasks effectively . + +The technology stack you will work with is a lamp stack (Linux, Apache, MySQL, PHP) along with JavaScript for frontend development. + + +## Capabilities +- **Code Review:** Analyze code for adherence to coding standards, best practices, and design patterns. +- **Refactoring:** Suggest and implement code refactoring to improve readability, maintainability, and performance. +- **Testing:** Ensure that code is well-tested, with appropriate unit tests, integration tests, and end-to-end tests. +- **Documentation:** Verify that code is well-documented, with clear comments and comprehensive documentation. +- **Performance Optimization:** Identify and address performance bottlenecks in the codebase. +- **Security Best Practices:** Ensure that code follows security best practices to prevent vulnerabilities. +- **Continuous Integration/Continuous Deployment (CI/CD):** Review and improve CI/CD pipelines to ensure smooth and reliable deployments. +- **Code Metrics:** Utilize code metrics to assess code quality and identify areas for improvement. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in code quality assurance. +- **web:** Access the web for additional resources, documentation, or best practices. + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be code quality experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that code quality issues have been resolved or improvements have been successfully implemented. diff --git a/.github/agents/mysql-mariadb.agent.md b/.github/agents/mysql-mariadb.agent.md new file mode 100644 index 00000000..ee4a6025 --- /dev/null +++ b/.github/agents/mysql-mariadb.agent.md @@ -0,0 +1,65 @@ +--- +description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." +name: "MySQL/ MariaDB Database Administrator" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# MySQL/ MariaDB Database Administrator + +You are a MySQL and MariaDB Database Administrator agent. Your role is to assist with enhancements, troubleshooting, and management of MySQL and MariaDB databases. You have access to various tools to help you perform your tasks effectively. + +## Capabilities +- **Database Management:** Assist with database creation, configuration, optimization, and maintenance tasks. +- **Query Optimization:** Analyze and optimize SQL queries for better performance. +- **Troubleshooting:** Diagnose and resolve database-related issues, including connection problems, performance bottlenecks, and data integrity concerns. +- **Backup and Recovery:** Provide guidance on backup strategies and recovery procedures. +- **Security:** Advise on best practices for securing MySQL and MariaDB databases. +- **Version Upgrades:** Assist with planning and executing database version upgrades. +- **Monitoring:** Recommend tools and techniques for monitoring database performance and health. +- **Scripting:** Help with writing and optimizing scripts for database automation tasks. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit configuration files, scripts, or code as needed. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in managing databases. +- **web:** Access the web for additional resources, documentation, or troubleshooting guides. + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the database environment, configurations, and any existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. + + +## Sample design patternsHere are some common design patterns and best practices for MySQL and MariaDB database management: +- **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. +- **Indexing:** Use appropriate indexing strategies to enhance query performance. +- **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance + + + +## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: +## you can find the included file in the cacti project here: +- [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) +- `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. +- `db_fetch_assoc($result)`: Fetches a single row from the result set as an associative array. +- `db_query($query)`: Executes a SQL query and returns the result set. +- `db_insert($table, $data)`: Inserts a new record into the specified table. +- `db_update($table, $data, $where)`: Updates records in the specified table based on the given conditions. +- `db_delete($table, $where)`: Deletes records from the specified table based on the given conditions. +- `db_escape_string($string)`: Escapes special characters in a string for use in a SQL query. +- `db_num_rows($result)`: Returns the number of rows in the result set. +- `db_last_insert_id()`: Retrieves the ID of the last inserted record. + + +##web documentation +For additional information and best practices, refer to the official MySQL and MariaDB documentation: +- [MySQL Documentation](https://dev.mysql.com/doc/) +- [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) + +Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. \ No newline at end of file diff --git a/.github/agents/php-developer.agent.md b/.github/agents/php-developer.agent.md new file mode 100644 index 00000000..4153ea3d --- /dev/null +++ b/.github/agents/php-developer.agent.md @@ -0,0 +1,41 @@ +--- +description: "This custom agent acts as a PHP developer, assisting with PHP code development, debugging, and optimization." +name: "PHP Developer" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# PHP Developer +You are a PHP Developer agent. Your role is to assist with PHP code development, debugging, and optimization. You have access to various tools to help you perform your tasks effectively. +You are to focus on PHP PSR-12 coding standards and best practices supporting modern PHP versions (PHP 8.1 and above). +Your other roles include: +- **Code Review:** Analyze PHP code for adherence to coding standards, best practices, and design patterns. +- **Debugging:** Identify and resolve bugs or issues in PHP code. +- **Performance Optimization:** Suggest and implement optimizations to improve the performance of PHP applications. +- **Testing:** Ensure that PHP code is well-tested, with appropriate unit tests and integration tests. +- **Documentation:** Verify that PHP code is well-documented, with clear comments and comprehensive documentation. +- **Security Best Practices:** Ensure that PHP code follows security best practices to prevent vulnerabilities. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit PHP code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in PHP development. +- **web:** Access the web for additional resources, documentation, or best practices. + + + +## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: +- [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) +- [Cacti Documentation](https://www.github.com/Cacti/documentation) + + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the PHP codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be PHP experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that PHP code issues have been resolved or improvements have been successfully implemented. diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.md.agent.md new file mode 100644 index 00000000..b46af245 --- /dev/null +++ b/.github/agents/triage_agent.md.agent.md @@ -0,0 +1,132 @@ +--- +description: 'This Agent will Receiving the initial task and call on other agents based on the task' +tools: ['execute', 'read', 'search', 'web', 'agent'] +--- +Define what this custom agent accomplishes for the user, when to use it, and the edges it won't cross. Specify its ideal inputs/outputs, the tools it may call, and how it reports progress or asks for help. + +This is a Triage Agent designed to receive an initial task or request from the user and determine the appropriate course of action by delegating specific tasks to specialized agents. The Triage Agent evaluates the nature of the request, identifies the relevant agents needed to address the task, and coordinates their efforts to ensure efficient and effective resolution. + +## Capabilities +- **Task Evaluation:** Analyze the user's request to understand its requirements and scope. +- **Agent Delegation:** Identify and delegate tasks to specialized agents based on their expertise. +- **Progress Reporting:** Monitor the progress of delegated tasks and provide updates to the user. +- **Issue Escalation:** Recognize when a task requires additional resources or expertise and escalate accordingly. +- **Feedback Integration:** Collect feedback from specialized agents and integrate their outputs into a cohesive response for the user. + +## Tools +- **execute:** Run commands or scripts as needed to gather information or perform actions. +- **read:** Access relevant files or data sources to inform decision-making. +- **search:** Look for information within the codebase or documentation to support task resolution. +- **web:** Access external resources or documentation to supplement knowledge. +- **agent:** Communicate with other specialized agents to delegate tasks and gather results. + +## Instructions +When receiving a task from the user, follow these guidelines: +1. **Understand the Request:** Carefully analyze the user's input to determine the nature of the task. +2. **Identify Relevant Agents:** Based on the task requirements, identify which specialized agents are best suited to handle specific aspects of the request. +3. **Delegate Tasks:** Communicate with the identified agents, providing them with clear instructions and context for their assigned tasks. +4. **Monitor Progress:** Keep track of the status of delegated tasks and ensure timely completion. +5. **Compile Results:** Gather outputs from specialized agents and integrate them into a comprehensive response for the user. +6. **Communicate with the User:** Provide regular updates to the user on the progress of their request and deliver the final results once all tasks are completed. +7. **Gain Clarification:** If the task is unclear or requires additional information, ask the user for clarification before proceeding. by either responding directly or responding to the ticket. + +## Ideal Inputs/Outputs +- **Inputs:** Clear and concise task descriptions from the user, including any relevant context or constraints. +- **Outputs:** A well-coordinated response that addresses the user's request, incorporating contributions from specialized agents as needed. + +## Edges +- The Triage Agent will not perform specialized tasks itself but will always delegate to the appropriate agents +- It will not make decisions without sufficient information and will seek clarification from the user if needed +- It will not handle tasks outside its scope of delegation and will inform the user if a request cannot be fulfilled. +- It will not perform any technical tasks without first consulting the relevant specialized agents. + +## Reporting Progress +- The Triage Agent will provide regular updates to the user on the status of their request, +including any delays or issues encountered during the delegation process. +- It will summarize the contributions of specialized agents in the final response to ensure clarity and completeness. +- If the Triage Agent encounters a task that requires additional expertise, it will escalate the issue to the user and suggest alternative approaches or resources. + + +## Asking for Help- If the Triage Agent is unable to identify suitable specialized agents for a task, it will notify the user and request guidance on how to proceed. +- It will also seek assistance from other agents if necessary to ensure the successful completion of the user's request. + + +## Example Workflow1. User submits a request: "I need help with optimizing my code for better performance." +2. Triage Agent analyzes the request and identifies that it requires code analysis and optimization. +3. Triage Agent delegates the code analysis task to a Code Analysis Agent and the optimization task to a Performance Optimization Agent. +4. Triage Agent monitors the progress of both agents and collects their outputs. +5. Triage Agent compiles the results and provides a comprehensive response to the user, including recommendations for code improvements and performance enhancements. +6. Triage Agent updates the user on the progress throughout the process and addresses any questions or concerns they may have. +This structured approach ensures that the Triage Agent effectively manages user requests by leveraging the expertise of specialized agents, leading to efficient and satisfactory outcomes. + + +## Delegating to Other Agents +When delegating tasks to other agents, the Triage Agent should: +1. Clearly define the task and its objectives to ensure the specialized agent understands the requirements. +2. Provide any necessary context or background information that may assist the specialized agent in completing the task. +3. Set expectations regarding deadlines or milestones for task completion. +4. Maintain open communication channels to address any questions or issues that may arise during task execution. +5. Review the outputs from specialized agents to ensure they meet the user's needs before compiling the final response. + +## Routing Rules (explicit) +- Purpose: ensure requests are delegated to the correct specialized agent using deterministic matching. +- Strategy: match request text against ordered rules (regex/keyword sets). First matching rule with highest priority wins. If multiple matches tie, use highest-priority agent or ask for clarification. +- Implementation guidance: + - Tokenize and lowercase user text. + - Run rules in priority order. + - Use exact agent names (e.g., "mysql" or "postgres") in the mapping. + - Log the matched rule, confidence score, and chosen agent for auditing. + +### Sample Rule Set (order = priority) +1. Database — MySQL + - Patterns: \b(mysql|mariadb|innoDB|sql schema|sql query)\b + - Agent: mysql_agent + - Example: "MySQL query slow" -> mysql_agent +2. Database — PostgreSQL + - Patterns: \b(postgres|postgresql|pg_|psql)\b + - Agent: postgres_agent +3. SQL (generic) + - Patterns: \b(sql|select|insert|update|delete|join|where)\b + - Agent: mysql_agent (preferred) OR ask clarification if 'postgres' or 'sqlite' also present +4. Code quality / linting + - Patterns: \b(lint|static analysis|code smell|cyclomatic complexity|code quality)\b + - Agent: code_quality_agent +5. Configuration / DevOps + - Patterns: \b(docker|kubernetes|ci/cd|ansible|terraform)\b + - Agent: devops_agent +6. Fallback + - If no rule matches or confidence low: ask user a clarifying question ("Is this a SQL/database question or a code-quality issue?") or route to a human/triage_admin_agent. + +### Decision algorithm (pseudo) +- Normalize input +- For each rule in priority order: + - if regex matches: + - compute confidence (e.g., number of matched tokens / rule token count) + - if confidence >= threshold => select agent and stop + - else collect low-confidence matches and continue +- If multiple high-confidence matches -> choose the one with higher priority or ask user +- If none -> ask clarification or use fallback agent + +## Delegation payload template +When calling other agents via the 'agent' tool, pass a structured payload: +{ + "task": "", + "context": "", + "expected_output": "", + "deadline": "" +} + +## Examples (for tests) +- Input: "MySQL slow select with missing index" -> Route to mysql_agent +- Input: "Code smells in function foo() — reduce complexity" -> Route to code_quality_agent +- Input: "SELECT JOIN performance" -> Route to mysql_agent (or ask if Postgres present) +- Input: "Error: unknown column in SQL" -> Route to mysql_agent + +## Logging & Monitoring +- Always log: input, matched rule id, matched tokens, chosen agent, timestamp +- Expose a debug mode that returns which rule matched and why +- report what agent was chosen and confidence level back to user + +## Testing +- Create unit tests for the rule set covering edge cases where both 'sql' and 'lint' appear. +- Add tests that assert SQL-specific keywords route to mysql_agent, not code_quality_agent. \ No newline at end of file diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml new file mode 100644 index 00000000..728eee21 --- /dev/null +++ b/.github/workflows/plugin-ci-workflow.yml @@ -0,0 +1,216 @@ +# +-------------------------------------------------------------------------+ +# | Copyright (C) 2004-2025 The Cacti Group | +# | | +# | 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. | +# +-------------------------------------------------------------------------+ +# | Cacti: The Complete RRDtool-based Graphing Solution | +# +-------------------------------------------------------------------------+ +# | This code is designed, written, and maintained by the Cacti Group. See | +# | about.php and/or the AUTHORS file for specific developer information. | +# +-------------------------------------------------------------------------+ +# | http://www.cacti.net/ | +# +-------------------------------------------------------------------------+ + +name: Plugin Integration Tests + +on: + push: + branches: + - main + - develop + pull_request: + branches: + - main + - develop + +jobs: + integration-test: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + php: ['8.1', '8.2', '8.3', '8.4'] + os: [ubuntu-latest] + + services: + mariadb: + image: mariadb:10.6 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + name: PHP ${{ matrix.php }} Integration Test on ${{ matrix.os }} + + steps: + - name: Checkout Cacti + uses: actions/checkout@v4 + with: + repository: Cacti/cacti + path: cacti + + - name: Checkout mactrack Plugin + uses: actions/checkout@v4 + with: + path: cacti/plugins/mactrack + + - name: Install PHP ${{ matrix.php }} + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: intl, mysql, gd, ldap, gmp, xml, curl, json, mbstring + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + + - name: Check PHP version + run: php -v + + - name: Run apt-get update + run: sudo apt-get update + + - name: Install System Dependencies + run: sudo apt-get install -y apache2 snmp snmpd rrdtool fping libapache2-mod-php${{ matrix.php }} + + - name: Start SNMPD Agent and Test + run: | + sudo systemctl start snmpd + sudo snmpwalk -c public -v2c -On localhost .1.3.6.1.2.1.1 + + - name: Setup Permissions + run: | + sudo chown -R www-data:runner ${{ github.workspace }}/cacti + sudo find ${{ github.workspace }}/cacti -type d -exec chmod 775 {} \; + sudo find ${{ github.workspace }}/cacti -type f -exec chmod 664 {} \; + sudo chmod +x ${{ github.workspace }}/cacti/cmd.php + sudo chmod +x ${{ github.workspace }}/cacti/poller.php + + - name: Create MySQL Config + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + cat ~/.my.cnf + + - name: Initialize Cacti Database + env: + MYSQL_AUTH_USR: '--defaults-file=~/.my.cnf' + run: | + mysql $MYSQL_AUTH_USR -e 'CREATE DATABASE IF NOT EXISTS cacti;' + mysql $MYSQL_AUTH_USR -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" + mysql $MYSQL_AUTH_USR -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "FLUSH PRIVILEGES;" + mysql $MYSQL_AUTH_USR cacti < ${{ github.workspace }}/cacti/cacti.sql + mysql $MYSQL_AUTH_USR -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti + + - name: Validate composer files + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + composer validate --strict || true + fi + + - name: Install Composer Dependencies + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + sudo composer install --dev --no-progress + fi + + - name: Create Cacti config.php + run: | + cat ${{ github.workspace }}/cacti/include/config.php.dist | \ + sed -r "s/localhost/127.0.0.1/g" | \ + sed -r "s/'cacti'/'cacti'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" > ${{ github.workspace }}/cacti/include/config.php + sudo chmod 664 ${{ github.workspace }}/cacti/include/config.php + + - name: Configure Apache + run: | + cat << 'EOF' | sed 's#GITHUB_WORKSPACE#${{ github.workspace }}#g' > /tmp/cacti.conf + + ServerAdmin webmaster@localhost + DocumentRoot GITHUB_WORKSPACE/cacti + + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + + + ErrorLog ${APACHE_LOG_DIR}/error.log + CustomLog ${APACHE_LOG_DIR}/access.log combined + + EOF + sudo cp /tmp/cacti.conf /etc/apache2/sites-available/000-default.conf + sudo systemctl restart apache2 + + - name: Install Cacti via CLI + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/install_cacti.php --accept-eula --install --force + + - name: Install mactrack Plugin + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/plugin_manage.php --plugin=mactrack --install --enable + + - name: Check PHP Syntax for Plugin + run: | + cd ${{ github.workspace }}/cacti/plugins/mactrack + if find . -name '*.php' -exec php -l {} 2>&1 \; | grep -iv 'no syntax errors detected'; then + echo "Syntax errors found!" + exit 1 + fi + + - name: Remove the plugins directory exclusion from the .phpstan.neon + run: sed '/plugins/d' -i .phpstan.neon + working-directory: ${{ github.workspace }}/cacti + + - name: Mark composer scripts executable + run: sudo chmod +x ${{ github.workspace }}/cacti/include/vendor/bin/* + + - name: Run Linter on base code + run: composer run-script lint ${{ github.workspace }}/cacti/plugins/mactrack + working-directory: ${{ github.workspace }}/cacti + + - name: Checking coding standards on base code + run: composer run-script phpcsfixer ${{ github.workspace }}/cacti/plugins/mactrack + working-directory: ${{ github.workspace }}/cacti + +# - name: Run PHPStan at Level 6 on base code outside of Composer due to technical issues +# run: ./include/vendor/bin/phpstan analyze --level 6 ${{ github.workspace }}/cacti/plugins/mactrack +# working-directory: ${{ github.workspace }}/cacti + + - name: Run Cacti Poller + run: | + cd ${{ github.workspace }}/cacti + sudo php poller.php --poller=1 --force --debug + if ! grep -q "SYSTEM STATS" log/cacti.log; then + echo "Cacti poller did not finish successfully" + cat log/cacti.log + exit 1 + fi + + - name: View Cacti Logs + if: always() + run: | + if [ -f ${{ github.workspace }}/cacti/log/cacti.log ]; then + echo "=== Cacti Log ===" + sudo cat ${{ github.workspace }}/cacti/log/cacti.log + fi From d68d979c69dc297d7321739f0904b352bf24ba7f Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 19:59:54 -0500 Subject: [PATCH 02/18] add instructions file --- .github/copilot-instructions.md | 114 ++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 .github/copilot-instructions.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..0b06df48 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,114 @@ +# GitHub Copilot Instructions for MacTrack plugin + +Priority: produce code that strictly follows patterns and versions already present in this repository. Do not introduce newer language features, new frameworks, or different architectural styles. + +--- + +## Quick summary of repository facts (observed) + +- Primary language: PHP (procedural plugin code). See [setup.php](setup.php#L1-L20) and many `*.php` files in repository. +- CI indicates supported PHP versions: `8.1`, `8.2`, `8.3`, `8.4`. See [.github/workflows/plugin-ci-workflow.yml](.github/workflows/plugin-ci-workflow.yml#L41-L81). +- This project is a Cacti plugin that requires Cacti >= 1.2.14. See [README.md](README.md#L1-L20). +- JavaScript is used for UI behavior (example files: `mactrack.js`, `mactrack_snmp.js`) and CSS themes are present. See [mactrack.js](mactrack.js) and [mactrack_snmp.js](mactrack_snmp.js). + +All guidance below is derived from these observed patterns. If a Copilot suggestion would conflict with any item below, prefer repository consistency. + +--- + +## Priority Guidelines for generated code + +1. Version compatibility: Do not use PHP language features beyond PHP 8.1–8.4 compatibility unless you detect additional project files that indicate support for newer versions. +2. Project style: Match the repository's procedural PHP style (functions, global usage, `include`/`include_once`) rather than introducing classes, namespaces, or frameworks unless the existing code already uses them. +3. Localization and escaping: Use the repository's localization and escaping patterns (`__()`, `__esc()` and `htmlspecialchars`) when producing UI text and output. +4. Database access: Use the project DB helper functions and patterns (e.g., `db_execute`, `db_fetch_assoc`, `db_fetch_cell`) rather than inventing new DB layers. Keep SQL usage consistent with existing code. +5. Output: Follow existing HTML output patterns (inline printing with `print`/`echo`) and the same markup structure and CSS classes (e.g., `ui-button`, Font Awesome usage). + +--- + +## Technology / Version detection steps Copilot should follow before suggesting code + +1. Inspect `.github/workflows/plugin-ci-workflow.yml` for explicit supported PHP versions and CI checks. Use those versions as the target language compatibility. See [.github/workflows/plugin-ci-workflow.yml](.github/workflows/plugin-ci-workflow.yml#L41-L81). +2. Inspect `README.md` (project requirements) for Cacti version constraints. See [README.md](README.md#L1-L20). +3. Look for `composer.json`, `composer.lock`, or other metadata; this repository conditionally checks for `composer.json` in CI but does not require it. If present, respect its constraints. + +Never propose code that requires newer PHP features, build tooling, or frameworks than what the repository explicitly supports. + +--- + +## Coding patterns and conventions observed (and required) + +- Procedural style: functions are top-level (for example `plugin_mactrack_install()` in [setup.php](setup.php#L1-L40)). Favor adding functions and using existing global variables (e.g., `$config`, `$tabs`) when extending behavior. +- Includes: code uses `include` / `include_once` with relative plugin paths. Follow the same pattern for loading helpers and libraries. +- Globals: code frequently accesses globals such as `$config` and `$tabs`. Use the same approach where needed to match surrounding code. +- Arrays: uses PHP array syntax `array(...)` across the codebase. Maintain the same array style unless files in the same area already use short array syntax `[...]`. +- DB helpers: use `db_fetch_assoc`, `db_fetch_row`, `db_fetch_cell`, `db_execute`, and other project wrappers rather than raw PDO/mysqli usage. +- Output escaping: use `__esc()` or `htmlspecialchars()` when printing user-supplied content. See examples in [mactrack_view_sites.php](mactrack_view_sites.php#L290-L306). +- Translation: use `__('text', 'mactrack')` for strings that appear in UI; follow existing message domain usage. +- JS and CSS: include JavaScript and CSS the same way the repo does (see [setup.php](setup.php#L1-L40) where scripts/styles are added in `mactrack_page_head()`). Keep class names and UI patterns (e.g., `ui-button`, `pic`, Font Awesome `fas` classes). + +--- + +## Security and input handling (per existing patterns) + +- Follow the repository's established sanitization and escaping patterns: use the `__esc()` wrapper and `htmlspecialchars()` when emitting values into HTML. Mirror existing checks rather than arbitrarily switching to new escaping utilities. +- For database interactions, follow the existing project wrapper functions and patterns. If you must add SQL, match the style used in nearby code (string concatenation or helper function usage as present). + +--- + +## Testing and CI expectations + +- Ensure any PHP created parses cleanly with `php -l` (CI runs `php -l` checks across `*.php`). See [.github/workflows/plugin-ci-workflow.yml](.github/workflows/plugin-ci-workflow.yml#L170-L180). +- If adding PHP code that uses dependencies managed by Composer, only do so if `composer.json` exists and CI would install dependencies; the CI workflow checks for `composer.json` before running Composer. + +--- + +## Documentation and headers + +- Follow the existing file header pattern (GPL notice and author lines) when creating new top-level files. See [setup.php](setup.php#L1-L20) for the header example. +- Use the same inline documentation style (brief blocks and inline comments) matching nearby files. + +--- + +## Examples (copy/adapt these repository-consistent snippets) + +- Function signature and register-hook pattern (from [setup.php](setup.php#L1-L40)): + +```php +function plugin_mactrack_example() { + api_plugin_register_hook('mactrack', 'page_head', 'mactrack_page_head', 'setup.php'); +} +``` + +- Output with escaping (pattern from [mactrack_view_sites.php](mactrack_view_sites.php#L290-L306)): + +```php +$actions = "..."; +``` + +- Adding scripts/styles to page head (pattern from [setup.php](setup.php#L1-L40)): + +```php +print "\n"; +``` + +--- + +## When patterns conflict + +1. Prefer the style in the most recently modified files in the same directory. +2. Prefer patterns present in core integration points such as `setup.php`, view pages (`mactrack_view_*.php`), and the CI workflow. + +--- + +## Where to place guidance files for Copilot + +This file is intentionally placed at repository root `.github/copilot-instructions.md` so it is easy to find for maintainers and Copilot consumers. If additional local rules are required for specific directories, add small, targeted instruction files next to those directories and reference this canonical guidance. + +--- + +## Next steps (optional suggestions) + +- Run `php -l` across `*.php` files to ensure new code parses. +- Add small linter or style config only if it mirrors CI setup. + +End of file. From 1fbe1834a20c4842baf2f2060e6e5ab7e9dd8183 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:06:33 -0500 Subject: [PATCH 03/18] Update .github/agents/mysql-mariadb.agent.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/agents/mysql-mariadb.agent.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/agents/mysql-mariadb.agent.md b/.github/agents/mysql-mariadb.agent.md index ee4a6025..4fb01ee2 100644 --- a/.github/agents/mysql-mariadb.agent.md +++ b/.github/agents/mysql-mariadb.agent.md @@ -43,7 +43,8 @@ When assisting with tasks, follow these guidelines: -## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: +## Built in Cacti DB functions +Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: ## you can find the included file in the cacti project here: - [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) - `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. From 41970cdc1846dfec9f78d697d937c3b7889f85b1 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:06:41 -0500 Subject: [PATCH 04/18] Update .github/agents/triage_agent.md.agent.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/agents/triage_agent.md.agent.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.md.agent.md index b46af245..66c4db06 100644 --- a/.github/agents/triage_agent.md.agent.md +++ b/.github/agents/triage_agent.md.agent.md @@ -51,9 +51,9 @@ including any delays or issues encountered during the delegation process. - It will also seek assistance from other agents if necessary to ensure the successful completion of the user's request. -## Example Workflow1. User submits a request: "I need help with optimizing my code for better performance." +## Example Workflow +1. User submits a request: "I need help with optimizing my code for better performance." 2. Triage Agent analyzes the request and identifies that it requires code analysis and optimization. -3. Triage Agent delegates the code analysis task to a Code Analysis Agent and the optimization task to a Performance Optimization Agent. 4. Triage Agent monitors the progress of both agents and collects their outputs. 5. Triage Agent compiles the results and provides a comprehensive response to the user, including recommendations for code improvements and performance enhancements. 6. Triage Agent updates the user on the progress throughout the process and addresses any questions or concerns they may have. From b3a5aa1bf166746b1a1cfe4992e62df63439ffee Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:06:48 -0500 Subject: [PATCH 05/18] Update .github/agents/mysql-mariadb.agent.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/agents/mysql-mariadb.agent.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/agents/mysql-mariadb.agent.md b/.github/agents/mysql-mariadb.agent.md index 4fb01ee2..072e2aaf 100644 --- a/.github/agents/mysql-mariadb.agent.md +++ b/.github/agents/mysql-mariadb.agent.md @@ -1,5 +1,5 @@ --- -description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." +description: "This custom agent assists with enhancements, troubleshooting, and management of MySQL and MariaDB databases." name: "MySQL/ MariaDB Database Administrator" tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] model: "Claude Sonnet 4.5" From 694ff31f8ef31e6e39fcb94be5b15fa153dbfbed Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:07:56 -0500 Subject: [PATCH 06/18] Update .github/workflows/plugin-ci-workflow.yml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/workflows/plugin-ci-workflow.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 728eee21..1476b54e 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -182,9 +182,6 @@ jobs: run: sed '/plugins/d' -i .phpstan.neon working-directory: ${{ github.workspace }}/cacti - - name: Mark composer scripts executable - run: sudo chmod +x ${{ github.workspace }}/cacti/include/vendor/bin/* - - name: Run Linter on base code run: composer run-script lint ${{ github.workspace }}/cacti/plugins/mactrack working-directory: ${{ github.workspace }}/cacti From f53e457c26e90a7042c2dd303475e94ef4e21e6d Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:08:21 -0500 Subject: [PATCH 07/18] Update .github/workflows/plugin-ci-workflow.yml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/workflows/plugin-ci-workflow.yml | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 1476b54e..4295bcfd 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -106,16 +106,14 @@ jobs: cat ~/.my.cnf - name: Initialize Cacti Database - env: - MYSQL_AUTH_USR: '--defaults-file=~/.my.cnf' run: | - mysql $MYSQL_AUTH_USR -e 'CREATE DATABASE IF NOT EXISTS cacti;' - mysql $MYSQL_AUTH_USR -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" - mysql $MYSQL_AUTH_USR -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" - mysql $MYSQL_AUTH_USR -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" - mysql $MYSQL_AUTH_USR -e "FLUSH PRIVILEGES;" - mysql $MYSQL_AUTH_USR cacti < ${{ github.workspace }}/cacti/cacti.sql - mysql $MYSQL_AUTH_USR -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti + mysql --defaults-file="$HOME/.my.cnf" -e 'CREATE DATABASE IF NOT EXISTS cacti;' + mysql --defaults-file="$HOME/.my.cnf" -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" + mysql --defaults-file="$HOME/.my.cnf" -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" + mysql --defaults-file="$HOME/.my.cnf" -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" + mysql --defaults-file="$HOME/.my.cnf" -e "FLUSH PRIVILEGES;" + mysql --defaults-file="$HOME/.my.cnf" cacti < ${{ github.workspace }}/cacti/cacti.sql + mysql --defaults-file="$HOME/.my.cnf" -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti - name: Validate composer files run: | From 517a3b5af1fc7c7d94d915e3103fc791a07f6c0d Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:08:39 -0500 Subject: [PATCH 08/18] Update .github/agents/triage_agent.md.agent.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/agents/triage_agent.md.agent.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.md.agent.md index 66c4db06..1575ef5b 100644 --- a/.github/agents/triage_agent.md.agent.md +++ b/.github/agents/triage_agent.md.agent.md @@ -1,5 +1,5 @@ --- -description: 'This Agent will Receiving the initial task and call on other agents based on the task' +description: 'This agent receives the initial task and calls on other agents based on the task' tools: ['execute', 'read', 'search', 'web', 'agent'] --- Define what this custom agent accomplishes for the user, when to use it, and the edges it won't cross. Specify its ideal inputs/outputs, the tools it may call, and how it reports progress or asks for help. From 968dc87da2e97797ea00e893bacd5516fc023b1b Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:12:56 -0500 Subject: [PATCH 09/18] Apply cs fixer --- .gitignore | 3 + .php-cs-fixer.cache | 1 + .php-cs-fixer.dist.php | 29 + Net/DNS2.php | 2559 +++++++------- Net/DNS2/BitMap.php | 344 +- Net/DNS2/Cache.php | 444 ++- Net/DNS2/Cache/File.php | 190 +- Net/DNS2/Cache/Shm.php | 271 +- Net/DNS2/Exception.php | 40 +- Net/DNS2/Header.php | 182 +- Net/DNS2/Lookups.php | 912 +++-- Net/DNS2/Notifier.php | 372 +- Net/DNS2/Packet.php | 205 +- Net/DNS2/Packet/Request.php | 70 +- Net/DNS2/Packet/Response.php | 66 +- Net/DNS2/PrivateKey.php | 668 ++-- Net/DNS2/Question.php | 84 +- Net/DNS2/RR.php | 1063 +++--- Net/DNS2/RR/A.php | 52 +- Net/DNS2/RR/AAAA.php | 167 +- Net/DNS2/RR/AFSDB.php | 61 +- Net/DNS2/RR/AMTRELAY.php | 445 ++- Net/DNS2/RR/ANY.php | 35 +- Net/DNS2/RR/APL.php | 524 ++- Net/DNS2/RR/ATMA.php | 83 +- Net/DNS2/RR/AVC.php | 13 +- Net/DNS2/RR/CAA.php | 75 +- Net/DNS2/RR/CDNSKEY.php | 13 +- Net/DNS2/RR/CDS.php | 13 +- Net/DNS2/RR/CERT.php | 134 +- Net/DNS2/RR/CNAME.php | 46 +- Net/DNS2/RR/CSYNC.php | 67 +- Net/DNS2/RR/DHCID.php | 77 +- Net/DNS2/RR/DLV.php | 15 +- Net/DNS2/RR/DNAME.php | 46 +- Net/DNS2/RR/DNSKEY.php | 81 +- Net/DNS2/RR/DS.php | 73 +- Net/DNS2/RR/EID.php | 35 +- Net/DNS2/RR/EUI48.php | 207 +- Net/DNS2/RR/EUI64.php | 212 +- Net/DNS2/RR/HINFO.php | 180 +- Net/DNS2/RR/HIP.php | 364 +- Net/DNS2/RR/IPSECKEY.php | 613 ++-- Net/DNS2/RR/ISDN.php | 210 +- Net/DNS2/RR/KEY.php | 13 +- Net/DNS2/RR/KX.php | 67 +- Net/DNS2/RR/L32.php | 55 +- Net/DNS2/RR/L64.php | 77 +- Net/DNS2/RR/LOC.php | 245 +- Net/DNS2/RR/LP.php | 54 +- Net/DNS2/RR/MX.php | 54 +- Net/DNS2/RR/NAPTR.php | 272 +- Net/DNS2/RR/NID.php | 67 +- Net/DNS2/RR/NIMLOC.php | 35 +- Net/DNS2/RR/NS.php | 48 +- Net/DNS2/RR/NSAP.php | 119 +- Net/DNS2/RR/NSEC.php | 58 +- Net/DNS2/RR/NSEC3.php | 135 +- Net/DNS2/RR/NSEC3PARAM.php | 94 +- Net/DNS2/RR/OPENPGPKEY.php | 45 +- Net/DNS2/RR/OPT.php | 132 +- Net/DNS2/RR/PTR.php | 46 +- Net/DNS2/RR/PX.php | 67 +- Net/DNS2/RR/RP.php | 63 +- Net/DNS2/RR/RRSIG.php | 149 +- Net/DNS2/RR/RT.php | 59 +- Net/DNS2/RR/SIG.php | 657 ++-- Net/DNS2/RR/SMIMEA.php | 13 +- Net/DNS2/RR/SOA.php | 111 +- Net/DNS2/RR/SPF.php | 13 +- Net/DNS2/RR/SRV.php | 75 +- Net/DNS2/RR/SSHFP.php | 134 +- Net/DNS2/RR/TA.php | 13 +- Net/DNS2/RR/TALINK.php | 63 +- Net/DNS2/RR/TKEY.php | 137 +- Net/DNS2/RR/TLSA.php | 82 +- Net/DNS2/RR/TSIG.php | 800 ++--- Net/DNS2/RR/TXT.php | 192 +- Net/DNS2/RR/TYPE65534.php | 46 +- Net/DNS2/RR/URI.php | 63 +- Net/DNS2/RR/WKS.php | 74 +- Net/DNS2/RR/X25.php | 140 +- Net/DNS2/Resolver.php | 511 ++- Net/DNS2/Socket.php | 309 +- Net/DNS2/Socket/Sockets.php | 179 +- Net/DNS2/Socket/Streams.php | 246 +- Net/DNS2/Updater.php | 1129 +++--- composer.json | 14 + images/index.php | 3 +- includes/database.php | 2276 ++++++------ index.php | 2 +- lib/index.php | 2 +- lib/mactrack_3com.php | 445 +-- lib/mactrack_aruba_oscx.php | 872 ++--- lib/mactrack_cabletron.php | 611 ++-- lib/mactrack_cisco.php | 1602 +++++---- lib/mactrack_dell.php | 457 +-- lib/mactrack_dlink.php | 608 ++-- lib/mactrack_enterasys.php | 263 +- lib/mactrack_enterasys_N7.php | 884 ++--- lib/mactrack_extreme.php | 536 +-- lib/mactrack_foundry.php | 360 +- lib/mactrack_functions.php | 6221 ++++++++++++++++++--------------- lib/mactrack_h3c_3com.php | 856 ++--- lib/mactrack_hp.php | 221 +- lib/mactrack_hp_ng.php | 207 +- lib/mactrack_hp_ngi.php | 352 +- lib/mactrack_juniper.php | 290 +- lib/mactrack_linux.php | 407 +-- lib/mactrack_norbay.php | 480 +-- lib/mactrack_norbay_ng.php | 205 +- lib/mactrack_tplink.php | 330 +- lib/mactrack_trendnet.php | 445 +-- lib/mactrack_vendors.php | 60 +- locales/LC_MESSAGES/index.php | 2 +- locales/index.php | 2 +- locales/po/index.php | 2 +- mactrack_actions.php | 646 ++-- mactrack_ajax.php | 18 +- mactrack_ajax_admin.php | 42 +- mactrack_convert.php | 323 +- mactrack_device_types.php | 1876 +++++----- mactrack_devices.php | 2066 +++++------ mactrack_import_ouidb.php | 120 +- mactrack_macauth.php | 560 +-- mactrack_macwatch.php | 621 ++-- mactrack_resolver.php | 382 +- mactrack_scanner.php | 378 +- mactrack_sites.php | 935 ++--- mactrack_snmp.php | 946 ++--- mactrack_utilities.php | 778 +++-- mactrack_vendormacs.php | 285 +- mactrack_view_arp.php | 821 +++-- mactrack_view_devices.php | 827 ++--- mactrack_view_dot1x.php | 1006 +++--- mactrack_view_graphs.php | 259 +- mactrack_view_interfaces.php | 967 ++--- mactrack_view_ips.php | 454 +-- mactrack_view_macs.php | 2022 ++++++----- mactrack_view_sites.php | 724 ++-- poller_mactrack.php | 1825 +++++----- setup.php | 3356 +++++++++--------- 142 files changed, 29886 insertions(+), 29651 deletions(-) create mode 100644 .php-cs-fixer.cache create mode 100644 .php-cs-fixer.dist.php create mode 100644 composer.json diff --git a/.gitignore b/.gitignore index eb716067..c1dee42d 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,6 @@ # +-------------------------------------------------------------------------+ locales/po/*.mo +vendor/ +composer.lock +composer.phar \ No newline at end of file diff --git a/.php-cs-fixer.cache b/.php-cs-fixer.cache new file mode 100644 index 00000000..0610e7a5 --- /dev/null +++ b/.php-cs-fixer.cache @@ -0,0 +1 @@ +{"php":"8.3.6","version":"3.94.0:v3.94.0#883b20fb38c7866de9844ab6d0a205c423bde2d4","indent":" ","lineEnding":"\n","rules":{"nullable_type_declaration":true,"operator_linebreak":true,"ordered_types":{"null_adjustment":"always_last"},"single_class_element_per_statement":true,"types_spaces":true,"array_indentation":true,"array_syntax":true,"attribute_block_no_spaces":true,"cast_spaces":true,"concat_space":true,"function_declaration":{"closure_fn_spacing":"one"},"method_argument_space":{"after_heredoc":true,"on_multiline":"ensure_fully_multiline"},"new_with_parentheses":{"anonymous_class":false},"single_line_empty_body":true,"single_space_around_construct":true,"trailing_comma_in_multiline":{"after_heredoc":true,"elements":["array_destructuring","arrays"]},"binary_operator_spaces":true,"blank_line_after_opening_tag":true,"blank_line_between_import_groups":true,"blank_lines_before_namespace":true,"braces_position":{"allow_single_line_anonymous_functions":true,"allow_single_line_empty_anonymous_classes":true},"class_definition":{"single_line":true},"compact_nullable_type_declaration":true,"declare_equal_normalize":true,"lowercase_cast":true,"lowercase_static_reference":true,"modifier_keywords":true,"no_blank_lines_after_class_opening":true,"no_extra_blank_lines":{"tokens":["attribute","break","case","continue","curly_brace_block","default","extra","parenthesis_brace_block","return","square_brace_block","switch","throw","use"]},"no_leading_import_slash":true,"no_whitespace_in_blank_line":true,"ordered_class_elements":true,"ordered_imports":{"imports_order":["class","function","const"],"sort_algorithm":"alpha"},"return_type_declaration":true,"short_scalar_cast":true,"single_import_per_statement":true,"single_trait_insert_per_statement":true,"ternary_operator_spaces":true,"unary_operator_spaces":true,"blank_line_after_namespace":true,"constant_case":true,"control_structure_braces":true,"control_structure_continuation_position":true,"elseif":true,"indentation_type":true,"line_ending":true,"lowercase_keywords":true,"no_break_comment":true,"no_closing_tag":true,"no_multiple_statements_per_line":true,"no_space_around_double_colon":true,"no_spaces_after_function_name":true,"no_trailing_whitespace":true,"no_trailing_whitespace_in_comment":true,"single_blank_line_at_eof":true,"single_line_after_imports":true,"spaces_inside_parentheses":true,"statement_indentation":{"stick_comment_to_next_continuous_control_statement":true},"switch_case_semicolon_to_colon":true,"switch_case_space":true,"encoding":true,"full_opening_tag":true,"blank_line_before_statement":{"statements":["break","case","continue","declare","default","exit","goto","include","include_once","phpdoc","require","require_once","return","switch","throw","try","yield","yield_from"]},"combine_consecutive_issets":true,"combine_consecutive_unsets":true,"empty_loop_body":true,"explicit_indirect_variable":true,"explicit_string_variable":true,"fully_qualified_strict_types":{"import_symbols":true},"heredoc_to_nowdoc":true,"method_chaining_indentation":true,"multiline_comment_opening_closing":true,"multiline_whitespace_before_semicolons":{"strategy":"new_line_for_chained_calls"},"no_superfluous_elseif":true,"no_superfluous_phpdoc_tags":{"allow_hidden_params":true,"allow_mixed":true,"remove_inheritdoc":true},"php_unit_data_provider_method_order":true,"php_unit_internal_class":true,"php_unit_test_class_requires_covers":true,"phpdoc_add_missing_param_annotation":true,"phpdoc_no_empty_return":true,"phpdoc_order_by_value":true,"phpdoc_types_no_duplicates":true,"phpdoc_types_order":true,"return_assignment":true,"self_static_accessor":true,"single_line_comment_style":true,"string_implicit_backslashes":true,"whitespace_after_comma_in_array":{"ensure_single_space":true},"align_multiline_comment":true,"backtick_to_shell_exec":true,"class_attributes_separation":{"elements":{"method":"one"}},"class_reference_name_casing":true,"clean_namespace":true,"declare_parentheses":true,"echo_tag_syntax":true,"empty_loop_condition":true,"general_phpdoc_tag_rename":{"replacements":{"inheritDocs":"inheritDoc"}},"global_namespace_import":{"import_classes":false,"import_constants":false,"import_functions":false},"include":true,"increment_style":true,"integer_literal_case":true,"lambda_not_used_import":true,"linebreak_after_opening_tag":true,"magic_constant_casing":true,"magic_method_casing":true,"native_function_casing":true,"native_type_declaration_casing":true,"no_alias_language_construct_call":true,"no_alternative_syntax":true,"no_binary_string":true,"no_blank_lines_after_phpdoc":true,"no_empty_comment":true,"no_empty_phpdoc":true,"no_empty_statement":true,"no_leading_namespace_whitespace":true,"no_mixed_echo_print":true,"no_multiline_whitespace_around_double_arrow":true,"no_null_property_initialization":true,"no_short_bool_cast":true,"no_singleline_whitespace_before_semicolons":true,"no_spaces_around_offset":true,"no_trailing_comma_in_singleline":true,"no_unneeded_braces":{"namespaces":true},"no_unneeded_control_parentheses":{"statements":["break","clone","continue","echo_print","negative_instanceof","others","return","switch_case","yield","yield_from"]},"no_unneeded_import_alias":true,"no_unset_cast":true,"no_unused_imports":true,"no_useless_concat_operator":true,"no_useless_else":true,"no_useless_nullsafe_operator":true,"no_useless_return":true,"no_whitespace_before_comma_in_array":{"after_heredoc":true},"normalize_index_brace":true,"nullable_type_declaration_for_default_null_value":true,"object_operator_without_whitespace":true,"php_unit_fqcn_annotation":true,"php_unit_method_casing":true,"phpdoc_align":true,"phpdoc_annotation_without_dot":true,"phpdoc_indent":true,"phpdoc_inline_tag_normalizer":true,"phpdoc_no_access":true,"phpdoc_no_alias_tag":{"replacements":{"const":"var","link":"see","property-read":"property","property-write":"property","type":"var"}},"phpdoc_no_package":true,"phpdoc_no_useless_inheritdoc":true,"phpdoc_order":{"order":["param","return","throws"]},"phpdoc_return_self_reference":true,"phpdoc_scalar":{"types":["boolean","callback","double","integer","never-return","never-returns","no-return","real","str"]},"phpdoc_separation":{"groups":[["Annotation","NamedArgumentConstructor","Target"],["author","copyright","license"],["category","package","subpackage"],["property","property-read","property-write"],["deprecated","link","see","since"]],"skip_unlisted_annotations":false},"phpdoc_single_line_var_spacing":true,"phpdoc_summary":true,"phpdoc_tag_type":{"tags":{"inheritDoc":"inline"}},"phpdoc_to_comment":{"allow_before_return_statement":false},"phpdoc_trim":true,"phpdoc_trim_consecutive_blank_line_separation":true,"phpdoc_types":true,"phpdoc_var_annotation_correct_order":true,"phpdoc_var_without_name":true,"protected_to_private":true,"semicolon_after_instruction":true,"simple_to_complex_string_variable":true,"single_line_comment_spacing":true,"single_quote":true,"space_after_semicolon":{"remove_in_empty_for_expressions":true},"standardize_increment":true,"standardize_not_equals":true,"switch_continue_to_break":true,"trim_array_spaces":true,"type_declaration_spaces":{"elements":["function","property"]},"yoda_style":true},"ruleCustomisationPolicyVersion":"null-policy","hashes":{"Net\/DNS2\/Socket\/Sockets.php":"47a7e57ac6e84c9668491b0865591900","Net\/DNS2\/Socket\/Streams.php":"9c8c08e81b534c9731be00da70694714","Net\/DNS2\/Packet.php":"2a74eb2ee769577476d04e1cffefba53","Net\/DNS2\/RR\/DNAME.php":"e51190b55c4a8dd22a0aff51946ad80f","Net\/DNS2\/RR\/URI.php":"93ab7e15ebf5ddcc1ba65c0260ae3d7f","Net\/DNS2\/RR\/SSHFP.php":"8f631aa4b829ea8ba454f80ceb11fc25","Net\/DNS2\/RR\/RP.php":"b04450a51f7204ada9353b590777c965","Net\/DNS2\/RR\/ATMA.php":"1e8fac6de8b4caa2b62ea8371cdccc58","Net\/DNS2\/RR\/SMIMEA.php":"0538891c4de2783157951994907d1ebc","Net\/DNS2\/RR\/SPF.php":"28ba17aac96355ab2f694d1414fcbbac","Net\/DNS2\/RR\/RT.php":"9a6873fd23f1345b9387a3532f838851","Net\/DNS2\/RR\/OPENPGPKEY.php":"e82b3d5e14d1675553697625bf4fc01a","Net\/DNS2\/RR\/EUI64.php":"f2cc5f84e8600853094866e259c6b645","Net\/DNS2\/RR\/OPT.php":"5af1cc3c2884ec8084033ee7c762224d","Net\/DNS2\/RR\/EUI48.php":"999434a68410f0fdf60e3c41df4135ce","Net\/DNS2\/RR\/HIP.php":"cfcdde2299f52acbfd41e47dae7c69a8","Net\/DNS2\/RR\/NAPTR.php":"6cb4962af3a6ba59217301c4ba27b45a","Net\/DNS2\/RR\/CDS.php":"b26dc4ec7d32b1014c83ef6ee1feeb6b","Net\/DNS2\/RR\/WKS.php":"ce8ea4c341b3c30e53b9453ea143ef46","Net\/DNS2\/RR\/PTR.php":"3b1d2455ec1ed57e5e3a19ffa748b0ae","Net\/DNS2\/RR\/RRSIG.php":"473e38ca6515d9b4a46f57e22f97a154","Net\/DNS2\/RR\/CAA.php":"8ac25d3146612b0c679b2b59ac059141","Net\/DNS2\/RR\/SOA.php":"8218c6d17f5c3732551d9ba795239eb1","Net\/DNS2\/RR\/NSEC.php":"4bfde0dd9ac33deddd6bb99dff1f252b","Net\/DNS2\/RR\/AMTRELAY.php":"20812b8b87ee2e2cd2e364977c70e832","Net\/DNS2\/RR\/L32.php":"958f9f85e6f9145678e88b1a2753a15d","Net\/DNS2\/RR\/TA.php":"890b4ecd59ca19a7eb0fb50de1923975","Net\/DNS2\/RR\/LP.php":"8a140da35ba26182d353509e068cfbc9","Net\/DNS2\/RR\/AAAA.php":"c2c63471f65381c2fba918a3d8638fbf","Net\/DNS2\/RR\/TALINK.php":"2ff469a2fb58463e07e53ffa961fb917","Net\/DNS2\/RR\/DLV.php":"e13c82f13e3554f743a2f1d89a0900e4","Net\/DNS2\/RR\/X25.php":"a7a7ec82deb4d0d0abb3de7cb830cd61","Net\/DNS2\/RR\/KX.php":"7ea1056315fd7cce684297a63c6cc8d5","Net\/DNS2\/RR\/SIG.php":"6d5c0a28cd73d62a452adc737aff9f8a","Net\/DNS2\/RR\/CDNSKEY.php":"c96dc2c503710db85efde23716943f56","Net\/DNS2\/RR\/NIMLOC.php":"dc9145d7b48671977eab561d8ae47b67","Net\/DNS2\/RR\/TLSA.php":"a7f3438ff1dce5703596d64fa620af84","Net\/DNS2\/RR\/CERT.php":"7645931f8c9d0f34a170dc72b64d2864","Net\/DNS2\/RR\/A.php":"3b09fc990a055c44fa36b2aaab266a69","Net\/DNS2\/RR\/NSEC3.php":"d5bc6dde021377942663b6ea0b186752","Net\/DNS2\/RR\/DHCID.php":"4d240eca7019285656ae98f5bb0c3905","Net\/DNS2\/RR\/TXT.php":"d42dbacba0aafc51ef19badada8a1989","Net\/DNS2\/RR\/MX.php":"0f787212149763072b77a66e89adfde3","Net\/DNS2\/RR\/AFSDB.php":"9c298270c0797fd8bb7f0f2f515f369b","Net\/DNS2\/RR\/LOC.php":"1edf0aa6b3580580a444db95663c5924","Net\/DNS2\/RR\/KEY.php":"ee455ea64e98c0e72f3c6db34232e743","Net\/DNS2\/RR\/TKEY.php":"32572b223107a307997fbddbd8300eca","Net\/DNS2\/RR\/ANY.php":"998240eeb82a105654d7004016b71533","Net\/DNS2\/RR\/L64.php":"e4f58c5c7b12561cfe03ac78d7c0db7e","Net\/DNS2\/RR\/HINFO.php":"78b6e4b9572503fb8b5b6deaeb75beac","Net\/DNS2\/RR\/AVC.php":"d9e1397b301ed634b623dcbaef6c7d83","Net\/DNS2\/RR\/CNAME.php":"8e25a5fedcff48b527523ed2b64ab608","Net\/DNS2\/RR\/IPSECKEY.php":"568b436b661017876780a8444725d0bb","Net\/DNS2\/RR\/CSYNC.php":"f399c90080d3edb8aab02b8553859a09","Net\/DNS2\/RR\/NID.php":"61edb240591456784a403995e70e6bd4","Net\/DNS2\/RR\/APL.php":"4c61b0b4d74b7d9e38dbd6d3a22e45de","Net\/DNS2\/RR\/NSAP.php":"7d11a04311e14abe6750ce3c5a7c8554","Net\/DNS2\/RR\/TYPE65534.php":"2d0d2644f72d0373262a8768d29dcfcd","Net\/DNS2\/RR\/NSEC3PARAM.php":"86351873d3781f69d33fb9a27b71653b","Net\/DNS2\/RR\/DNSKEY.php":"469d94991bcb4db77b3307a53724ee63","Net\/DNS2\/Resolver.php":"6b9f14dddbd8a5cdabd8ef4267cf6d12","Net\/DNS2\/Exception.php":"04e7e0e67ee49dabb0ba6929870dd299","Net\/DNS2\/Question.php":"1ff87f244b68d1d8d4f99bfaa7e2bbfd","Net\/DNS2\/RR.php":"69fa81a6636f83684393649daaad3d29","Net\/DNS2\/BitMap.php":"575d75a4c877acb21728e9dd7df6e41c","Net\/DNS2\/Cache\/File.php":"96c093d403269ec8d084221dca92ef18","Net\/DNS2\/Cache\/Shm.php":"96657147fbda2f3e641f2e45b85e857d","Net\/DNS2\/Cache.php":"12d1b3610f98afaf1813d1f77713a73c","Net\/DNS2\/Packet\/Request.php":"58bba6f98196d55ab4dd174247693925","Net\/DNS2\/Packet\/Response.php":"24aebd8dc669e6e4813a2949781b0b68","Net\/DNS2\/RR\/SRV.php":"fbedef60b2907b32ca4a434e2b3cd629","Net\/DNS2\/RR\/TSIG.php":"7beb42f90cc6afea1d5ebbb944a9d5f7","Net\/DNS2\/RR\/ISDN.php":"f682479e1eb83bf85832996635f185eb","Net\/DNS2\/RR\/DS.php":"e7168cd6b9f998d8f172bfd561cf4596","Net\/DNS2\/RR\/PX.php":"242c4ef4f7b685364b4a5141a352d3ff","Net\/DNS2\/RR\/NS.php":"78e0cf007dd5ca25372095467a019f41","Net\/DNS2\/RR\/EID.php":"a7f986268c9581e1212eb919043f7d0f","Net\/DNS2\/Header.php":"99735297a8b6752196a154b5161a5627","Net\/DNS2\/Socket.php":"59c9d70dcfa6f862197bab1ecec2f77c","mactrack_view_arp.php":"2088402b352767ea497373fdb4b41c07","lib\/mactrack_foundry.php":"b860b34cd64c9de1532e142150d0fb9c","lib\/mactrack_dlink.php":"427a0731eb90ec84857f6f67dfdfae46","lib\/mactrack_aruba_oscx.php":"7987f56746e59370ccea30fadb56cd26","lib\/mactrack_extreme.php":"b9066cbcba733dc789696e8f206810d2","lib\/mactrack_linux.php":"3ea1de52357e884df50fc126e142b5ad","lib\/mactrack_norbay_ng.php":"37f4c82e9761c02e5130a0b9443a8320","lib\/mactrack_trendnet.php":"c212df2f477239fed04b87f847f256b5","lib\/mactrack_enterasys_N7.php":"f9b72bfa776adab0a52cf65d14e6a235","lib\/mactrack_tplink.php":"4d593d4710ee45aab41e72bd8695385d","lib\/mactrack_norbay.php":"139c8649cef3b3605c4ef0fce741db5f","lib\/mactrack_juniper.php":"8879266c3380da9d57e23059349b5bab","lib\/mactrack_dell.php":"12d8e907185eeea6aa29536a82f5893e","lib\/mactrack_vendors.php":"5d5440cfce4b897723d3320572d8ac97","lib\/mactrack_h3c_3com.php":"0f26339c08001e516e5c43c6001c9014","lib\/mactrack_hp.php":"dc917b47b6e466e64fb8ad490e8a32c0","lib\/mactrack_enterasys.php":"caec86fb1ab14dd0fa210e3fb68c1984","lib\/mactrack_hp_ngi.php":"e2263555a0ffa37c232201175d4f5e46","lib\/mactrack_cabletron.php":"10d079e0a78fa29183be2ef123e4507c","lib\/mactrack_hp_ng.php":"6d63f8a0feb59d27cab58b84160fc05b","lib\/mactrack_cisco.php":"d1572e3cdcbc6fea66bbacab583f2b94","mactrack_devices.php":"12393208a25d365496b2188661c1a6c5","mactrack_ajax.php":"c10a3e4f1800e5ea3bb23131a9e881d2","mactrack_snmp.php":"995c37cf7b2f141727bb78f4d86f3c67","locales\/po\/index.php":"b5d18b68d15480d2bdaed5d7e3e6b570","locales\/LC_MESSAGES\/index.php":"b5d18b68d15480d2bdaed5d7e3e6b570","locales\/index.php":"b5d18b68d15480d2bdaed5d7e3e6b570","mactrack_vendormacs.php":"59865b84b9723ecb592c335637527e82","mactrack_macauth.php":"19e44570f52ca9d21bd1e893e83d9f4d","mactrack_ajax_admin.php":"bda72cf599c75300ac7167065292788d","mactrack_sites.php":"b734902835e829f28b4e6ab310658165","images\/index.php":"b5d18b68d15480d2bdaed5d7e3e6b570","poller_mactrack.php":"e3a49f2165eeb241f2c816ef453bc92e","mactrack_view_dot1x.php":"dadd962a1774d26450265cfeac1d5ca4","mactrack_convert.php":"612bd5f0400eab64917915415d482f2b","mactrack_utilities.php":"1743148e22a05e698029f15451e7dd22","Net\/DNS2.php":"d74f4cb809fb0932a44be93205b27ed4","Net\/DNS2\/Lookups.php":"38d92ca2dcd8cd6050b64c14859da448","Net\/DNS2\/Notifier.php":"6b9b40fbe524e3a932b7dd58e6619ed8","Net\/DNS2\/PrivateKey.php":"17c018dfb90745bf359895372075c411","Net\/DNS2\/Updater.php":"613da8e25dd8e335c15e7a8f62bac96e","includes\/database.php":"2f2ab7d1d008703a958884ff83229b43","mactrack_macwatch.php":"97393c8b9a509a579302d6ea72f2d211","mactrack_device_types.php":"ccc2cdb0fbd20cf1cc1e46f7c2d7aa36","setup.php":"6d734711e6038c0cbc28bb5acddf848f","mactrack_view_devices.php":"2a772d32149ad067a3a8ced6c4f56730","mactrack_view_interfaces.php":"98e578aaf4409297acbc77d5b61b8a88","index.php":"b5d18b68d15480d2bdaed5d7e3e6b570","mactrack_view_sites.php":"584d66afb4f342956ecb9625ee5d0c0e","lib\/mactrack_3com.php":"cdda1639baee51411cc3c32d2fde25d6","lib\/index.php":"b5d18b68d15480d2bdaed5d7e3e6b570","lib\/mactrack_functions.php":"59ab53447dd9a6ef86c577456e6d10b3","mactrack_actions.php":"9b0705aba05cb1467d274dc10a46e26b","mactrack_resolver.php":"883c12cce6792f8d7bc029334b8d1d10","mactrack_scanner.php":"726e2d2699203c0e00307d2d357e15be","mactrack_view_graphs.php":"a1e1928bd264c205ef403bac1bae6325","mactrack_import_ouidb.php":"17c86a72ea5f7b9e0021cea3fcdba734","mactrack_view_ips.php":"acdfda28c96f99a11b536d65e1559ba9","mactrack_view_macs.php":"c86c44fb59c41e847d2efbfb692ec8d9"}} \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..f0141176 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,29 @@ +setRiskyAllowed(false) + ->setRules([ + '@auto' => true, + '@PhpCsFixer' => true + ]) + // 💡 by default, Fixer looks for `*.php` files excluding `./vendor/` - here, you can groom this config + ->setFinder( + (new Finder()) + // 💡 root folder to check + ->in(__DIR__) + // 💡 additional files, eg bin entry file + // ->append([__DIR__.'/bin-entry-file']) + // 💡 folders to exclude, if any + // ->exclude([/* ... */]) + // 💡 path patterns to exclude, if any + // ->notPath([/* ... */]) + // 💡 extra configs + // ->ignoreDotFiles(false) // true by default in v3, false in v4 or future mode + // ->ignoreVCS(true) // true by default + ) +; diff --git a/Net/DNS2.php b/Net/DNS2.php index b06d6cc8..f1b549fa 100644 --- a/Net/DNS2.php +++ b/Net/DNS2.php @@ -8,1358 +8,1235 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ -/* - * register the auto-load function - * - */ +// register the auto-load function spl_autoload_register('Net_DNS2::autoload'); /** * This is the base class for the Net_DNS2_Resolver and Net_DNS2_Updater classes. - * */ class Net_DNS2 { - /* - * the current version of this library - */ - const VERSION = '1.5.0'; - - /* - * the default path to a resolv.conf file - */ - const RESOLV_CONF = '/etc/resolv.conf'; - - /* - * override options from the resolv.conf file - * - * if this is set, then certain values from the resolv.conf file will override - * local settings. This is disabled by default to remain backwards compatible. - * - */ - public $use_resolv_options = false; - - /* - * use TCP only (true/false) - */ - public $use_tcp = false; - - /* - * DNS Port to use (53) - */ - public $dns_port = 53; - - /* - * the ip/port for use as a local socket - */ - public $local_host = ''; - public $local_port = 0; - - /* - * timeout value for socket connections - */ - public $timeout = 5; - - /* - * randomize the name servers list - */ - public $ns_random = false; - - /* - * default domains - */ - public $domain = ''; - - /* - * domain search list - not actually used right now - */ - public $search_list = []; - - /* - * enable cache; either "shared", "file" or "none" - */ - public $cache_type = 'none'; - - /* - * file name to use for shared memory segment or file cache - */ - public $cache_file = '/tmp/net_dns2.cache'; - - /* - * the max size of the cache file (in bytes) - */ - public $cache_size = 50000; - - /* - * the method to use for storing cache data; either "serialize" or "json" - * - * json is faster, but can't remember the class names (everything comes back - * as a "stdClass Object"; all the data is the same though. serialize is - * slower, but will have all the class info. - * - * defaults to 'serialize' - */ - public $cache_serializer = 'serialize'; - - /* - * by default, according to RFC 1034 - * - * CNAME RRs cause special action in DNS software. When a name server - * fails to find a desired RR in the resource set associated with the - * domain name, it checks to see if the resource set consists of a CNAME - * record with a matching class. If so, the name server includes the CNAME - * record in the response and restarts the query at the domain name - * specified in the data field of the CNAME record. - * - * this can cause "unexpected" behaviours, since i'm sure *most* people - * don't know DNS does this; there may be cases where Net_DNS2 returns a - * positive response, even though the hostname the user looked up did not - * actually exist. - * - * strict_query_mode means that if the hostname that was looked up isn't - * actually in the answer section of the response, Net_DNS2 will return an - * empty answer section, instead of an answer section that could contain - * CNAME records. - * - */ - public $strict_query_mode = false; - - /* - * if we should set the recursion desired bit to 1 or 0. - * - * by default this is set to true, we want the DNS server to perform a recursive - * request. If set to false, the RD bit will be set to 0, and the server will - * not perform recursion on the request. - */ - public $recurse = true; - - /* - * request DNSSEC values, by setting the DO flag to 1; this actually makes - * the resolver add a OPT RR to the additional section, and sets the DO flag - * in this RR to 1 - * - */ - public $dnssec = false; - - /* - * set the DNSSEC AD (Authentic Data) bit on/off; the AD bit on the request - * side was previously undefined, and resolvers we instructed to always clear - * the AD bit when sending a request. - * - * RFC6840 section 5.7 defines setting the AD bit in the query as a signal to - * the server that it wants the value of the AD bit, without needed to request - * all the DNSSEC data via the DO bit. - * - */ - public $dnssec_ad_flag = false; - - /* - * set the DNSSEC CD (Checking Disabled) bit on/off; turning this off, means - * that the DNS resolver will perform it's own signature validation- so the DNS - * servers simply pass through all the details. - * - */ - public $dnssec_cd_flag = false; - - /* - * the EDNS(0) UDP payload size to use when making DNSSEC requests - * see RFC 4035 section 4.1 - EDNS Support. - * - * there is some different ideas on the suggest size to support; but it seems to - * be "at least 1220 bytes, but SHOULD support 4000 bytes. - * - * we'll just support 4000 - * - */ - public $dnssec_payload_size = 4000; - - /* - * the last exception that was generated - */ - public $last_exception = null; - - /* - * the list of exceptions by name server - */ - public $last_exception_list = []; - - /* - * name server list - */ - public $nameservers = []; - - /* - * local sockets - */ - protected $sock = [ Net_DNS2_Socket::SOCK_DGRAM => [], Net_DNS2_Socket::SOCK_STREAM => [] ]; - - /* - * the TSIG or SIG RR object for authentication - */ - protected $auth_signature = null; - - /* - * the shared memory segment id for the local cache - */ - protected $cache = null; - - /* - * internal setting for enabling cache - */ - protected $use_cache = false; - - /** - * Constructor - base constructor for the Resolver and Updater - * - * @param mixed $options array of options or null for none - * - * @throws Net_DNS2_Exception - * @access public - * - */ - public function __construct(array $options = null) - { - // - // load any options that were provided - // - if (!empty($options)) { - - foreach ($options as $key => $value) { - - if ($key == 'nameservers') { - - $this->setServers($value); - } else { - - $this->$key = $value; - } - } - } - - // - // if we're set to use the local shared memory cache, then - // make sure it's been initialized - // - switch($this->cache_type) { - case 'shared': - if (extension_loaded('shmop')) { - - $this->cache = new Net_DNS2_Cache_Shm; - $this->use_cache = true; - } else { - - throw new Net_DNS2_Exception( - 'shmop library is not available for cache', - Net_DNS2_Lookups::E_CACHE_SHM_UNAVAIL - ); - } - break; - case 'file': - - $this->cache = new Net_DNS2_Cache_File; - $this->use_cache = true; - - break; - case 'none': - $this->use_cache = false; - break; - default: - - throw new Net_DNS2_Exception( - 'un-supported cache type: ' . $this->cache_type, - Net_DNS2_Lookups::E_CACHE_UNSUPPORTED - ); - } - } - - /** - * autoload call-back function; used to auto-load classes - * - * @param string $name the name of the class - * - * @return void - * @access public - * - */ - static public function autoload($name) - { - // - // only auto-load our classes - // - if (strncmp($name, 'Net_DNS2', 8) == 0) { - - include str_replace('_', '/', $name) . '.php'; - } - - return; - } - - /** - * sets the name servers to be used - * - * @param mixed $nameservers either an array of name servers, or a file name - * to parse, assuming it's in the resolv.conf format - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function setServers($nameservers) - { - // - // if it's an array, then use it directly - // - // otherwise, see if it's a path to a resolv.conf file and if so, load it - // - if (is_array($nameservers)) { - - $this->nameservers = $nameservers; - - } else { - - // - // temporary list of name servers; do it this way rather than just - // resetting the local nameservers value, just incase an exception - // is thrown here; this way we might avoid ending up with an empty - // namservers list. - // - $ns = []; - - // - // check to see if the file is readable - // - if (is_readable($nameservers) === true) { - - $data = file_get_contents($nameservers); - if ($data === false) { - throw new Net_DNS2_Exception( - 'failed to read contents of file: ' . $nameservers, - Net_DNS2_Lookups::E_NS_INVALID_FILE - ); - } - - $lines = explode("\n", $data); - - foreach ($lines as $line) { - - $line = trim($line); - - // - // ignore empty lines, and lines that are commented out - // - if ( (strlen($line) == 0) - || ($line[0] == '#') - || ($line[0] == ';') - ) { - continue; - } - - // - // ignore lines with no spaces in them. - // - if (strpos($line, ' ') === false) { - continue; - } - - list($key, $value) = preg_split('/\s+/', $line, 2); - - $key = trim(strtolower($key)); - $value = trim(strtolower($value)); - - switch($key) { - case 'nameserver': - - // - // nameserver can be a IPv4 or IPv6 address - // - if ( (self::isIPv4($value) == true) - || (self::isIPv6($value) == true) - ) { - - $ns[] = $value; - } else { - - throw new Net_DNS2_Exception( - 'invalid nameserver entry: ' . $value, - Net_DNS2_Lookups::E_NS_INVALID_ENTRY - ); - } - break; - - case 'domain': - $this->domain = $value; - break; - - case 'search': - $this->search_list = preg_split('/\s+/', $value); - break; - - case 'options': - $this->parseOptions($value); - break; - - default: - ; - } - } - - // - // if we don't have a domain, but we have a search list, then - // take the first entry on the search list as the domain - // - if ( (strlen($this->domain) == 0) - && (cacti_sizeof($this->search_list) > 0) - ) { - $this->domain = $this->search_list[0]; - } - - } else { - throw new Net_DNS2_Exception( - 'resolver file file provided is not readable: ' . $nameservers, - Net_DNS2_Lookups::E_NS_INVALID_FILE - ); - } - - // - // store the name servers locally - // - if (cacti_sizeof($ns) > 0) { - $this->nameservers = $ns; - } - } - - // - // remove any duplicates; not sure if we should bother with this- if people - // put duplicate name servers, who I am to stop them? - // - $this->nameservers = array_unique($this->nameservers); - - // - // check the name servers - // - $this->checkServers(); - - return true; - } - - /** - * return the internal $sock array - * - * @return array - * @access public - */ - public function getSockets() - { - return $this->sock; - } - - /** - * give users access to close all open sockets on the resolver object; resetting each - * array, calls the destructor on the Net_DNS2_Socket object, which calls the close() - * method on each object. - * - * @return boolean - * @access public - * - */ - public function closeSockets() - { - $this->sock[Net_DNS2_Socket::SOCK_DGRAM] = []; - $this->sock[Net_DNS2_Socket::SOCK_STREAM] = []; - - return true; - } - - /** - * parses the options line from a resolv.conf file; we don't support all the options - * yet, and using them is optional. - * - * @param string $value is the options string from the resolv.conf file. - * - * @return boolean - * @access private - * - */ - private function parseOptions($value) - { - // - // if overrides are disabled (the default), or the options list is empty for some - // reason, then we don't need to do any of this work. - // - if ( ($this->use_resolv_options == false) || (strlen($value) == 0) ) { - - return true; - } - - $options = preg_split('/\s+/', strtolower($value)); - - foreach ($options as $option) { - - // - // override the timeout value from the resolv.conf file. - // - if ( (strncmp($option, 'timeout', 7) == 0) && (strpos($option, ':') !== false) ) { - - list($key, $val) = explode(':', $option); - - if ( ($val > 0) && ($val <= 30) ) { - - $this->timeout = $val; - } - - // - // the rotate option just enabled the ns_random option - // - } else if (strncmp($option, 'rotate', 6) == 0) { - - $this->ns_random = true; - } - } - - return true; - } - - /** - * checks the list of name servers to make sure they're set - * - * @param mixed $default a path to a resolv.conf file or an array of servers. - * - * @return boolean - * @throws Net_DNS2_Exception - * @access protected - * - */ - protected function checkServers($default = null) - { - if (empty($this->nameservers)) { - - if (isset($default)) { - - $this->setServers($default); - } else { - - throw new Net_DNS2_Exception( - 'empty name servers list; you must provide a list of name '. - 'servers, or the path to a resolv.conf file.', - Net_DNS2_Lookups::E_NS_INVALID_ENTRY - ); - } - } - - return true; - } - - /** - * adds a TSIG RR object for authentication - * - * @param string $keyname the key name to use for the TSIG RR - * @param string $signature the key to sign the request. - * @param string $algorithm the algorithm to use - * - * @return boolean - * @access public - * @since function available since release 1.1.0 - * - */ - public function signTSIG( - $keyname, $signature = '', $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5 - ) { - // - // if the TSIG was pre-created and passed in, then we can just used - // it as provided. - // - if ($keyname instanceof Net_DNS2_RR_TSIG) { - - $this->auth_signature = $keyname; - - } else { - - // - // otherwise create the TSIG RR, but don't add it just yet; TSIG needs - // to be added as the last additional entry- so we'll add it just - // before we send. - // - $this->auth_signature = Net_DNS2_RR::fromString( - strtolower(trim($keyname)) . - ' TSIG '. $signature - ); - - // - // set the algorithm to use - // - $this->auth_signature->algorithm = $algorithm; - } - - return true; - } - - /** - * adds a SIG RR object for authentication - * - * @param string $filename the name of a file to load the signature from. - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * @since function available since release 1.1.0 - * - */ - public function signSIG0($filename) - { - // - // check for OpenSSL - // - if (extension_loaded('openssl') === false) { - - throw new Net_DNS2_Exception( - 'the OpenSSL extension is required to use SIG(0).', - Net_DNS2_Lookups::E_OPENSSL_UNAVAIL - ); - } - - // - // if the SIG was pre-created, then use it as-is - // - if ($filename instanceof Net_DNS2_RR_SIG) { - - $this->auth_signature = $filename; - - } else { - - // - // otherwise, it's filename which needs to be parsed and processed. - // - $private = new Net_DNS2_PrivateKey($filename); - - // - // create a new Net_DNS2_RR_SIG object - // - $this->auth_signature = new Net_DNS2_RR_SIG(); - - // - // reset some values - // - $this->auth_signature->name = $private->signname; - $this->auth_signature->ttl = 0; - $this->auth_signature->class = 'ANY'; - - // - // these values are pulled from the private key - // - $this->auth_signature->algorithm = $private->algorithm; - $this->auth_signature->keytag = $private->keytag; - $this->auth_signature->signname = $private->signname; - - // - // these values are hard-coded for SIG0 - // - $this->auth_signature->typecovered = 'SIG0'; - $this->auth_signature->labels = 0; - $this->auth_signature->origttl = 0; - - // - // generate the dates - // - $t = time(); - - $this->auth_signature->sigincep = gmdate('YmdHis', $t); - $this->auth_signature->sigexp = gmdate('YmdHis', $t + 500); - - // - // store the private key in the SIG object for later. - // - $this->auth_signature->private_key = $private; - } - - // - // only RSA algorithms are supported for SIG(0) - // - switch($this->auth_signature->algorithm) { - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: - break; - default: - throw new Net_DNS2_Exception( - 'only asymmetric algorithms work with SIG(0)!', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - return true; - } - - /** - * a simple function to determine if the RR type is cacheable - * - * @param string $_type the RR type string - * - * @return bool returns true/false if the RR type if cacheable - * @access public - * - */ - public function cacheable($_type) - { - switch($_type) { - case 'AXFR': - case 'OPT': - return false; - } - - return true; - } - - /** - * PHP doesn't support unsigned integers, but many of the RR's return - * unsigned values (like SOA), so there is the possibility that the - * value will overrun on 32bit systems, and you'll end up with a - * negative value. - * - * 64bit systems are not affected, as their PHP_IN_MAX value should - * be 64bit (ie 9223372036854775807) - * - * This function returns a negative integer value, as a string, with - * the correct unsigned value. - * - * @param string $_int the unsigned integer value to check - * - * @return string returns the unsigned value as a string. - * @access public - * - */ - public static function expandUint32($_int) - { - if ( ($_int < 0) && (PHP_INT_MAX == 2147483647) ) { - return sprintf('%u', $_int); - } else { - return $_int; - } - } - - /** - * returns true/false if the given address is a valid IPv4 address - * - * @param string $_address the IPv4 address to check - * - * @return boolean returns true/false if the address is IPv4 address - * @access public - * - */ - public static function isIPv4($_address) - { - // - // use filter_var() if it's available; it's faster than preg - // - if (extension_loaded('filter') == true) { - - if (filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == false) { - return false; - } - } else { - - // - // do the main check here; - // - if (inet_pton($_address) === false) { - return false; - } - - // - // then make sure we're not a IPv6 address - // - if (preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address) == 0) { - return false; - } - } - - return true; - } - - /** - * returns true/false if the given address is a valid IPv6 address - * - * @param string $_address the IPv6 address to check - * - * @return boolean returns true/false if the address is IPv6 address - * @access public - * - */ - public static function isIPv6($_address) - { - // - // use filter_var() if it's available; it's faster than preg - // - if (extension_loaded('filter') == true) { - if (filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) == false) { - return false; - } - } else { - - // - // do the main check here - // - if (inet_pton($_address) === false) { - return false; - } - - // - // then make sure it doesn't match a IPv4 address - // - if (preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address) == 1) { - return false; - } - } - - return true; - } - - /** - * formats the given IPv6 address as a fully expanded IPv6 address - * - * @param string $_address the IPv6 address to expand - * - * @return string the fully expanded IPv6 address - * @access public - * - */ - public static function expandIPv6($_address) - { - $hex = unpack('H*hex', inet_pton($_address)); - - return substr(preg_replace('/([A-f0-9]{4})/', "$1:", $hex['hex']), 0, -1); - } - - /** - * sends a standard Net_DNS2_Packet_Request packet - * - * @param Net_DNS2_Packet $request a Net_DNS2_Packet_Request object - * @param boolean $use_tcp true/false if the function should - * use TCP for the request - * - * @return Net_DNS2_Packet_Response - * @throws Net_DNS2_Exception - * @access protected - * - */ - protected function sendPacket(Net_DNS2_Packet $request, $use_tcp) - { - // - // get the data from the packet - // - $data = $request->get(); - if (strlen($data) < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - - throw new Net_DNS2_Exception( - 'invalid or empty packet for sending!', - Net_DNS2_Lookups::E_PACKET_INVALID, - null, - $request - ); - } - - reset($this->nameservers); - - // - // randomize the name server list if it's asked for - // - if ($this->ns_random == true) { - - shuffle($this->nameservers); - } - - // - // loop so we can handle server errors - // - $response = null; - $ns = ''; - - while (1) { - - // - // grab the next DNS server - // - $ns = current($this->nameservers); - next($this->nameservers); - - if ($ns === false) { - - if (is_null($this->last_exception) == false) { - - throw $this->last_exception; - } else { - - throw new Net_DNS2_Exception( - 'every name server provided has failed', - Net_DNS2_Lookups::E_NS_FAILED - ); - } - } - - // - // if the use TCP flag (force TCP) is set, or the packet is bigger than our - // max allowed UDP size- which is either 512, or if this is DNSSEC request, - // then whatever the configured dnssec_payload_size is. - // - $max_udp_size = Net_DNS2_Lookups::DNS_MAX_UDP_SIZE; - if ($this->dnssec == true) - { - $max_udp_size = $this->dnssec_payload_size; - } - - if ( ($use_tcp == true) || (strlen($data) > $max_udp_size) ) { - - try - { - $response = $this->sendTCPRequest($ns, $data, ($request->question[0]->qtype == 'AXFR') ? true : false); - - } catch(Net_DNS2_Exception $e) { - - $this->last_exception = $e; - $this->last_exception_list[$ns] = $e; - - continue; - } - - // - // otherwise, send it using UDP - // - } else { - - try - { - $response = $this->sendUDPRequest($ns, $data); - - // - // check the packet header for a truncated bit; if it was truncated, - // then re-send the request as TCP. - // - if ($response->header->tc == 1) { - - $response = $this->sendTCPRequest($ns, $data); - } - - } catch(Net_DNS2_Exception $e) { - - $this->last_exception = $e; - $this->last_exception_list[$ns] = $e; - - continue; - } - } - - // - // make sure header id's match between the request and response - // - if ($request->header->id != $response->header->id) { - - $this->last_exception = new Net_DNS2_Exception( - - 'invalid header: the request and response id do not match.', - Net_DNS2_Lookups::E_HEADER_INVALID, - null, - $request, - $response - ); - - $this->last_exception_list[$ns] = $this->last_exception; - continue; - } - - // - // make sure the response is actually a response - // - // 0 = query, 1 = response - // - if ($response->header->qr != Net_DNS2_Lookups::QR_RESPONSE) { - - $this->last_exception = new Net_DNS2_Exception( - - 'invalid header: the response provided is not a response packet.', - Net_DNS2_Lookups::E_HEADER_INVALID, - null, - $request, - $response - ); - - $this->last_exception_list[$ns] = $this->last_exception; - continue; - } - - // - // make sure the response code in the header is ok - // - if ($response->header->rcode != Net_DNS2_Lookups::RCODE_NOERROR) { - - $this->last_exception = new Net_DNS2_Exception( - - 'DNS request failed: ' . - Net_DNS2_Lookups::$result_code_messages[$response->header->rcode], - $response->header->rcode, - null, - $request, - $response - ); - - $this->last_exception_list[$ns] = $this->last_exception; - continue; - } - - break; - } - - return $response; - } - - /** - * cleans up a failed socket and throws the given exception - * - * @param string $_proto the protocol of the socket - * @param string $_ns the name server to use for the request - * @param string $_error the error message to throw at the end of the function - * - * @throws Net_DNS2_Exception - * @access private - * - */ - private function generateError($_proto, $_ns, $_error) - { - if (isset($this->sock[$_proto][$_ns]) == false) - { - throw new Net_DNS2_Exception('invalid socket referenced', Net_DNS2_Lookups::E_NS_INVALID_SOCKET); - } - - // - // grab the last error message off the socket - // - $last_error = $this->sock[$_proto][$_ns]->last_error; - - // - // remove it from the socket cache; this will call the destructor, which calls close() on the socket - // - unset($this->sock[$_proto][$_ns]); - - // - // throw the error provided - // - throw new Net_DNS2_Exception($last_error, $_error); - } - - /** - * sends a DNS request using TCP - * - * @param string $_ns the name server to use for the request - * @param string $_data the raw DNS packet data - * @param boolean $_axfr if this is a zone transfer request - * - * @return Net_DNS2_Packet_Response the response object - * @throws Net_DNS2_Exception - * @access private - * - */ - private function sendTCPRequest($_ns, $_data, $_axfr = false) - { - // - // grab the start time - // - $start_time = microtime(true); - - // - // see if we already have an open socket from a previous request; if so, try to use - // that instead of opening a new one. - // - if ( (!isset($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns])) - || (!($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] instanceof Net_DNS2_Socket)) - ) { - - // - // create the socket object - // - $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] = new Net_DNS2_Socket( - Net_DNS2_Socket::SOCK_STREAM, $_ns, $this->dns_port, $this->timeout - ); - - // - // if a local IP address / port is set, then add it - // - if (strlen($this->local_host) > 0) { - - $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->bindAddress( - $this->local_host, $this->local_port - ); - } - - // - // open the socket - // - if ($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->open() === false) { - - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - } - - // - // write the data to the socket; if it fails, continue on - // the while loop - // - if ($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->write($_data) === false) { - - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // read the content, using select to wait for a response - // - $size = 0; - $result = null; - $response = null; - - // - // handle zone transfer requests differently than other requests. - // - if ($_axfr == true) { - - $soa_count = 0; - - while (1) { - - // - // read the data off the socket - // - $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read($size, - ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE); - - if ( ($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE) ) { - - // - // if we get an error, then keeping this socket around for a future request, could cause - // an error- for example, https://github.com/mikepultz/netdns2/issues/61 - // - // in this case, the connection was timing out, which once it did finally respond, left - // data on the socket, which could be captured on a subsequent request. - // - // since there's no way to "reset" a socket, the only thing we can do it close it. - // - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // parse the first chunk as a packet - // - $chunk = new Net_DNS2_Packet_Response($result, $size); - - // - // if this is the first packet, then clone it directly, then - // go through it to see if there are two SOA records - // (indicating that it's the only packet) - // - if (is_null($response) == true) { - - $response = clone $chunk; - - // - // look for a failed response; if the zone transfer - // failed, then we don't need to do anything else at this - // point, and we should just break out. - // - if ($response->header->rcode != Net_DNS2_Lookups::RCODE_NOERROR) { - break; - } - - // - // go through each answer - // - foreach ($response->answer as $index => $rr) { - - // - // count the SOA records - // - if ($rr->type == 'SOA') { - $soa_count++; - } - } - - // - // if we have 2 or more SOA records, then we're done; - // otherwise continue out so we read the rest of the - // packets off the socket - // - if ($soa_count >= 2) { - break; - } else { - continue; - } - - } else { - - // - // go through all these answers, and look for SOA records - // - foreach ($chunk->answer as $index => $rr) { - - // - // count the number of SOA records we find - // - if ($rr->type == 'SOA') { - $soa_count++; - } - - // - // add the records to a single response object - // - $response->answer[] = $rr; - } - - // - // if we've found the second SOA record, we're done - // - if ($soa_count >= 2) { - break; - } - } - } - - // - // everything other than a AXFR - // - } else { - - $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read($size, - ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE); - - if ( ($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE) ) { - - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // create the packet object - // - $response = new Net_DNS2_Packet_Response($result, $size); - } - - // - // store the query time - // - $response->response_time = microtime(true) - $start_time; - - // - // add the name server that the response came from to the response object, - // and the socket type that was used. - // - $response->answer_from = $_ns; - $response->answer_socket_type = Net_DNS2_Socket::SOCK_STREAM; - - // - // return the Net_DNS2_Packet_Response object - // - return $response; - } - - /** - * sends a DNS request using UDP - * - * @param string $_ns the name server to use for the request - * @param string $_data the raw DNS packet data - * - * @return Net_DNS2_Packet_Response the response object - * @throws Net_DNS2_Exception - * @access private - * - */ - private function sendUDPRequest($_ns, $_data) - { - // - // grab the start time - // - $start_time = microtime(true); - - // - // see if we already have an open socket from a previous request; if so, try to use - // that instead of opening a new one. - // - if ( (!isset($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns])) - || (!($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] instanceof Net_DNS2_Socket)) - ) { - - // - // create the socket object - // - $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] = new Net_DNS2_Socket( - Net_DNS2_Socket::SOCK_DGRAM, $_ns, $this->dns_port, $this->timeout - ); - - // - // if a local IP address / port is set, then add it - // - if (strlen($this->local_host) > 0) { - - $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->bindAddress( - $this->local_host, $this->local_port - ); - } - - // - // open the socket - // - if ($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->open() === false) { - - $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - } - - // - // write the data to the socket - // - if ($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->write($_data) === false) { - - $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // read the content, using select to wait for a response - // - $size = 0; - - $result = $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->read($size, - ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE); - - if (( $result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { - - $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // create the packet object - // - $response = new Net_DNS2_Packet_Response($result, $size); - - // - // store the query time - // - $response->response_time = microtime(true) - $start_time; - - // - // add the name server that the response came from to the response object, - // and the socket type that was used. - // - $response->answer_from = $_ns; - $response->answer_socket_type = Net_DNS2_Socket::SOCK_DGRAM; - - // - // return the Net_DNS2_Packet_Response object - // - return $response; - } + // the current version of this library + public const VERSION = '1.5.0'; + + // the default path to a resolv.conf file + public const RESOLV_CONF = '/etc/resolv.conf'; + + /* + * override options from the resolv.conf file + * + * if this is set, then certain values from the resolv.conf file will override + * local settings. This is disabled by default to remain backwards compatible. + * + */ + public $use_resolv_options = false; + + // use TCP only (true/false) + public $use_tcp = false; + + // DNS Port to use (53) + public $dns_port = 53; + + // the ip/port for use as a local socket + public $local_host = ''; + public $local_port = 0; + + // timeout value for socket connections + public $timeout = 5; + + // randomize the name servers list + public $ns_random = false; + + // default domains + public $domain = ''; + + // domain search list - not actually used right now + public $search_list = []; + + // enable cache; either "shared", "file" or "none" + public $cache_type = 'none'; + + // file name to use for shared memory segment or file cache + public $cache_file = '/tmp/net_dns2.cache'; + + // the max size of the cache file (in bytes) + public $cache_size = 50000; + + /* + * the method to use for storing cache data; either "serialize" or "json" + * + * json is faster, but can't remember the class names (everything comes back + * as a "stdClass Object"; all the data is the same though. serialize is + * slower, but will have all the class info. + * + * defaults to 'serialize' + */ + public $cache_serializer = 'serialize'; + + /* + * by default, according to RFC 1034 + * + * CNAME RRs cause special action in DNS software. When a name server + * fails to find a desired RR in the resource set associated with the + * domain name, it checks to see if the resource set consists of a CNAME + * record with a matching class. If so, the name server includes the CNAME + * record in the response and restarts the query at the domain name + * specified in the data field of the CNAME record. + * + * this can cause "unexpected" behaviours, since i'm sure *most* people + * don't know DNS does this; there may be cases where Net_DNS2 returns a + * positive response, even though the hostname the user looked up did not + * actually exist. + * + * strict_query_mode means that if the hostname that was looked up isn't + * actually in the answer section of the response, Net_DNS2 will return an + * empty answer section, instead of an answer section that could contain + * CNAME records. + * + */ + public $strict_query_mode = false; + + /* + * if we should set the recursion desired bit to 1 or 0. + * + * by default this is set to true, we want the DNS server to perform a recursive + * request. If set to false, the RD bit will be set to 0, and the server will + * not perform recursion on the request. + */ + public $recurse = true; + + /* + * request DNSSEC values, by setting the DO flag to 1; this actually makes + * the resolver add a OPT RR to the additional section, and sets the DO flag + * in this RR to 1 + * + */ + public $dnssec = false; + + /* + * set the DNSSEC AD (Authentic Data) bit on/off; the AD bit on the request + * side was previously undefined, and resolvers we instructed to always clear + * the AD bit when sending a request. + * + * RFC6840 section 5.7 defines setting the AD bit in the query as a signal to + * the server that it wants the value of the AD bit, without needed to request + * all the DNSSEC data via the DO bit. + * + */ + public $dnssec_ad_flag = false; + + /* + * set the DNSSEC CD (Checking Disabled) bit on/off; turning this off, means + * that the DNS resolver will perform it's own signature validation- so the DNS + * servers simply pass through all the details. + * + */ + public $dnssec_cd_flag = false; + + /* + * the EDNS(0) UDP payload size to use when making DNSSEC requests + * see RFC 4035 section 4.1 - EDNS Support. + * + * there is some different ideas on the suggest size to support; but it seems to + * be "at least 1220 bytes, but SHOULD support 4000 bytes. + * + * we'll just support 4000 + * + */ + public $dnssec_payload_size = 4000; + + // the last exception that was generated + public $last_exception; + + // the list of exceptions by name server + public $last_exception_list = []; + + // name server list + public $nameservers = []; + + // local sockets + protected $sock = [Net_DNS2_Socket::SOCK_DGRAM => [], Net_DNS2_Socket::SOCK_STREAM => []]; + + // the TSIG or SIG RR object for authentication + protected $auth_signature; + + // the shared memory segment id for the local cache + protected $cache; + + // internal setting for enabling cache + protected $use_cache = false; + + /** + * Constructor - base constructor for the Resolver and Updater. + * + * @param mixed $options array of options or null for none + * + * @throws Net_DNS2_Exception + */ + public function __construct(?array $options = null) + { + // + // load any options that were provided + // + if (!empty($options)) { + foreach ($options as $key => $value) { + if ('nameservers' == $key) { + $this->setServers($value); + } else { + $this->{$key} = $value; + } + } + } + + // + // if we're set to use the local shared memory cache, then + // make sure it's been initialized + // + switch ($this->cache_type) { + case 'shared': + if (extension_loaded('shmop')) { + $this->cache = new Net_DNS2_Cache_Shm(); + $this->use_cache = true; + } else { + throw new Net_DNS2_Exception( + 'shmop library is not available for cache', + Net_DNS2_Lookups::E_CACHE_SHM_UNAVAIL + ); + } + + break; + + case 'file': + $this->cache = new Net_DNS2_Cache_File(); + $this->use_cache = true; + + break; + + case 'none': + $this->use_cache = false; + + break; + + default: + throw new Net_DNS2_Exception( + 'un-supported cache type: '.$this->cache_type, + Net_DNS2_Lookups::E_CACHE_UNSUPPORTED + ); + } + } + + /** + * autoload call-back function; used to auto-load classes. + * + * @param string $name the name of the class + */ + public static function autoload($name) + { + // + // only auto-load our classes + // + if (0 == strncmp($name, 'Net_DNS2', 8)) { + include str_replace('_', '/', $name).'.php'; + } + } + + /** + * sets the name servers to be used. + * + * @param mixed $nameservers either an array of name servers, or a file name + * to parse, assuming it's in the resolv.conf format + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function setServers($nameservers) + { + // + // if it's an array, then use it directly + // + // otherwise, see if it's a path to a resolv.conf file and if so, load it + // + if (is_array($nameservers)) { + $this->nameservers = $nameservers; + } else { + // + // temporary list of name servers; do it this way rather than just + // resetting the local nameservers value, just incase an exception + // is thrown here; this way we might avoid ending up with an empty + // namservers list. + // + $ns = []; + + // + // check to see if the file is readable + // + if (true === is_readable($nameservers)) { + $data = file_get_contents($nameservers); + if (false === $data) { + throw new Net_DNS2_Exception( + 'failed to read contents of file: '.$nameservers, + Net_DNS2_Lookups::E_NS_INVALID_FILE + ); + } + + $lines = explode("\n", $data); + + foreach ($lines as $line) { + $line = trim($line); + + // + // ignore empty lines, and lines that are commented out + // + if ((0 == strlen($line)) + || ('#' == $line[0]) + || (';' == $line[0]) + ) { + continue; + } + + // + // ignore lines with no spaces in them. + // + if (false === strpos($line, ' ')) { + continue; + } + + list($key, $value) = preg_split('/\s+/', $line, 2); + + $key = trim(strtolower($key)); + $value = trim(strtolower($value)); + + switch ($key) { + case 'nameserver': + // + // nameserver can be a IPv4 or IPv6 address + // + if ((true == self::isIPv4($value)) + || (true == self::isIPv6($value)) + ) { + $ns[] = $value; + } else { + throw new Net_DNS2_Exception( + 'invalid nameserver entry: '.$value, + Net_DNS2_Lookups::E_NS_INVALID_ENTRY + ); + } + + break; + + case 'domain': + $this->domain = $value; + + break; + + case 'search': + $this->search_list = preg_split('/\s+/', $value); + + break; + + case 'options': + $this->parseOptions($value); + + break; + + default:; + } + } + + // + // if we don't have a domain, but we have a search list, then + // take the first entry on the search list as the domain + // + if ((0 == strlen($this->domain)) + && (cacti_sizeof($this->search_list) > 0) + ) { + $this->domain = $this->search_list[0]; + } + } else { + throw new Net_DNS2_Exception( + 'resolver file file provided is not readable: '.$nameservers, + Net_DNS2_Lookups::E_NS_INVALID_FILE + ); + } + + // + // store the name servers locally + // + if (cacti_sizeof($ns) > 0) { + $this->nameservers = $ns; + } + } + + // + // remove any duplicates; not sure if we should bother with this- if people + // put duplicate name servers, who I am to stop them? + // + $this->nameservers = array_unique($this->nameservers); + + // + // check the name servers + // + $this->checkServers(); + + return true; + } + + /** + * return the internal $sock array. + * + * @return array + */ + public function getSockets() + { + return $this->sock; + } + + /** + * give users access to close all open sockets on the resolver object; resetting each + * array, calls the destructor on the Net_DNS2_Socket object, which calls the close() + * method on each object. + * + * @return bool + */ + public function closeSockets() + { + $this->sock[Net_DNS2_Socket::SOCK_DGRAM] = []; + $this->sock[Net_DNS2_Socket::SOCK_STREAM] = []; + + return true; + } + + /** + * adds a TSIG RR object for authentication. + * + * @param string $keyname the key name to use for the TSIG RR + * @param string $signature the key to sign the request + * @param string $algorithm the algorithm to use + * + * @return bool + * + * @since function available since release 1.1.0 + */ + public function signTSIG( + $keyname, + $signature = '', + $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5 + ) { + // + // if the TSIG was pre-created and passed in, then we can just used + // it as provided. + // + if ($keyname instanceof Net_DNS2_RR_TSIG) { + $this->auth_signature = $keyname; + } else { + // + // otherwise create the TSIG RR, but don't add it just yet; TSIG needs + // to be added as the last additional entry- so we'll add it just + // before we send. + // + $this->auth_signature = Net_DNS2_RR::fromString( + strtolower(trim($keyname)) + .' TSIG '.$signature + ); + + // + // set the algorithm to use + // + $this->auth_signature->algorithm = $algorithm; + } + + return true; + } + + /** + * adds a SIG RR object for authentication. + * + * @param string $filename the name of a file to load the signature from + * + * @return bool + * + * @throws Net_DNS2_Exception + * + * @since function available since release 1.1.0 + */ + public function signSIG0($filename) + { + // + // check for OpenSSL + // + if (false === extension_loaded('openssl')) { + throw new Net_DNS2_Exception( + 'the OpenSSL extension is required to use SIG(0).', + Net_DNS2_Lookups::E_OPENSSL_UNAVAIL + ); + } + + // + // if the SIG was pre-created, then use it as-is + // + if ($filename instanceof Net_DNS2_RR_SIG) { + $this->auth_signature = $filename; + } else { + // + // otherwise, it's filename which needs to be parsed and processed. + // + $private = new Net_DNS2_PrivateKey($filename); + + // + // create a new Net_DNS2_RR_SIG object + // + $this->auth_signature = new Net_DNS2_RR_SIG(); + + // + // reset some values + // + $this->auth_signature->name = $private->signname; + $this->auth_signature->ttl = 0; + $this->auth_signature->class = 'ANY'; + + // + // these values are pulled from the private key + // + $this->auth_signature->algorithm = $private->algorithm; + $this->auth_signature->keytag = $private->keytag; + $this->auth_signature->signname = $private->signname; + + // + // these values are hard-coded for SIG0 + // + $this->auth_signature->typecovered = 'SIG0'; + $this->auth_signature->labels = 0; + $this->auth_signature->origttl = 0; + + // + // generate the dates + // + $t = time(); + + $this->auth_signature->sigincep = gmdate('YmdHis', $t); + $this->auth_signature->sigexp = gmdate('YmdHis', $t + 500); + + // + // store the private key in the SIG object for later. + // + $this->auth_signature->private_key = $private; + } + + // + // only RSA algorithms are supported for SIG(0) + // + switch ($this->auth_signature->algorithm) { + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: + break; + + default: + throw new Net_DNS2_Exception( + 'only asymmetric algorithms work with SIG(0)!', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + return true; + } + + /** + * a simple function to determine if the RR type is cacheable. + * + * @param string $_type the RR type string + * + * @return bool returns true/false if the RR type if cacheable + */ + public function cacheable($_type) + { + switch ($_type) { + case 'AXFR': + case 'OPT': + return false; + } + + return true; + } + + /** + * PHP doesn't support unsigned integers, but many of the RR's return + * unsigned values (like SOA), so there is the possibility that the + * value will overrun on 32bit systems, and you'll end up with a + * negative value. + * + * 64bit systems are not affected, as their PHP_IN_MAX value should + * be 64bit (ie 9223372036854775807) + * + * This function returns a negative integer value, as a string, with + * the correct unsigned value. + * + * @param string $_int the unsigned integer value to check + * + * @return string returns the unsigned value as a string + */ + public static function expandUint32($_int) + { + if (($_int < 0) && (PHP_INT_MAX == 2147483647)) { + return sprintf('%u', $_int); + } + + return $_int; + } + + /** + * returns true/false if the given address is a valid IPv4 address. + * + * @param string $_address the IPv4 address to check + * + * @return bool returns true/false if the address is IPv4 address + */ + public static function isIPv4($_address) + { + // + // use filter_var() if it's available; it's faster than preg + // + if (true == extension_loaded('filter')) { + if (false == filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return false; + } + } else { + // + // do the main check here; + // + if (false === inet_pton($_address)) { + return false; + } + + // + // then make sure we're not a IPv6 address + // + if (0 == preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address)) { + return false; + } + } + + return true; + } + + /** + * returns true/false if the given address is a valid IPv6 address. + * + * @param string $_address the IPv6 address to check + * + * @return bool returns true/false if the address is IPv6 address + */ + public static function isIPv6($_address) + { + // + // use filter_var() if it's available; it's faster than preg + // + if (true == extension_loaded('filter')) { + if (false == filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + return false; + } + } else { + // + // do the main check here + // + if (false === inet_pton($_address)) { + return false; + } + + // + // then make sure it doesn't match a IPv4 address + // + if (1 == preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address)) { + return false; + } + } + + return true; + } + + /** + * formats the given IPv6 address as a fully expanded IPv6 address. + * + * @param string $_address the IPv6 address to expand + * + * @return string the fully expanded IPv6 address + */ + public static function expandIPv6($_address) + { + $hex = unpack('H*hex', inet_pton($_address)); + + return substr(preg_replace('/([A-f0-9]{4})/', '$1:', $hex['hex']), 0, -1); + } + + /** + * checks the list of name servers to make sure they're set. + * + * @param mixed $default a path to a resolv.conf file or an array of servers. + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + protected function checkServers($default = null) + { + if (empty($this->nameservers)) { + if (isset($default)) { + $this->setServers($default); + } else { + throw new Net_DNS2_Exception( + 'empty name servers list; you must provide a list of name ' + .'servers, or the path to a resolv.conf file.', + Net_DNS2_Lookups::E_NS_INVALID_ENTRY + ); + } + } + + return true; + } + + /** + * sends a standard Net_DNS2_Packet_Request packet. + * + * @param Net_DNS2_Packet $request a Net_DNS2_Packet_Request object + * @param bool $use_tcp true/false if the function should + * use TCP for the request + * + * @return Net_DNS2_Packet_Response + * + * @throws Net_DNS2_Exception + */ + protected function sendPacket(Net_DNS2_Packet $request, $use_tcp) + { + // + // get the data from the packet + // + $data = $request->get(); + if (strlen($data) < Net_DNS2_Lookups::DNS_HEADER_SIZE) { + throw new Net_DNS2_Exception( + 'invalid or empty packet for sending!', + Net_DNS2_Lookups::E_PACKET_INVALID, + null, + $request + ); + } + + reset($this->nameservers); + + // + // randomize the name server list if it's asked for + // + if (true == $this->ns_random) { + shuffle($this->nameservers); + } + + // + // loop so we can handle server errors + // + $response = null; + $ns = ''; + + while (1) { + // + // grab the next DNS server + // + $ns = current($this->nameservers); + next($this->nameservers); + + if (false === $ns) { + if (false == is_null($this->last_exception)) { + throw $this->last_exception; + } + + throw new Net_DNS2_Exception( + 'every name server provided has failed', + Net_DNS2_Lookups::E_NS_FAILED + ); + } + + // + // if the use TCP flag (force TCP) is set, or the packet is bigger than our + // max allowed UDP size- which is either 512, or if this is DNSSEC request, + // then whatever the configured dnssec_payload_size is. + // + $max_udp_size = Net_DNS2_Lookups::DNS_MAX_UDP_SIZE; + if (true == $this->dnssec) { + $max_udp_size = $this->dnssec_payload_size; + } + + if ((true == $use_tcp) || (strlen($data) > $max_udp_size)) { + try { + $response = $this->sendTCPRequest($ns, $data, ('AXFR' == $request->question[0]->qtype) ? true : false); + } catch (Net_DNS2_Exception $e) { + $this->last_exception = $e; + $this->last_exception_list[$ns] = $e; + + continue; + } + + // + // otherwise, send it using UDP + // + } else { + try { + $response = $this->sendUDPRequest($ns, $data); + + // + // check the packet header for a truncated bit; if it was truncated, + // then re-send the request as TCP. + // + if (1 == $response->header->tc) { + $response = $this->sendTCPRequest($ns, $data); + } + } catch (Net_DNS2_Exception $e) { + $this->last_exception = $e; + $this->last_exception_list[$ns] = $e; + + continue; + } + } + + // + // make sure header id's match between the request and response + // + if ($request->header->id != $response->header->id) { + $this->last_exception = new Net_DNS2_Exception( + 'invalid header: the request and response id do not match.', + Net_DNS2_Lookups::E_HEADER_INVALID, + null, + $request, + $response + ); + + $this->last_exception_list[$ns] = $this->last_exception; + + continue; + } + + // + // make sure the response is actually a response + // + // 0 = query, 1 = response + // + if (Net_DNS2_Lookups::QR_RESPONSE != $response->header->qr) { + $this->last_exception = new Net_DNS2_Exception( + 'invalid header: the response provided is not a response packet.', + Net_DNS2_Lookups::E_HEADER_INVALID, + null, + $request, + $response + ); + + $this->last_exception_list[$ns] = $this->last_exception; + + continue; + } + + // + // make sure the response code in the header is ok + // + if (Net_DNS2_Lookups::RCODE_NOERROR != $response->header->rcode) { + $this->last_exception = new Net_DNS2_Exception( + 'DNS request failed: ' + .Net_DNS2_Lookups::$result_code_messages[$response->header->rcode], + $response->header->rcode, + null, + $request, + $response + ); + + $this->last_exception_list[$ns] = $this->last_exception; + + continue; + } + + break; + } + + return $response; + } + + /** + * parses the options line from a resolv.conf file; we don't support all the options + * yet, and using them is optional. + * + * @param string $value is the options string from the resolv.conf file. + * + * @return bool + */ + private function parseOptions($value) + { + // + // if overrides are disabled (the default), or the options list is empty for some + // reason, then we don't need to do any of this work. + // + if ((false == $this->use_resolv_options) || (0 == strlen($value))) { + return true; + } + + $options = preg_split('/\s+/', strtolower($value)); + + foreach ($options as $option) { + // + // override the timeout value from the resolv.conf file. + // + if ((0 == strncmp($option, 'timeout', 7)) && (false !== strpos($option, ':'))) { + list($key, $val) = explode(':', $option); + + if (($val > 0) && ($val <= 30)) { + $this->timeout = $val; + } + + // + // the rotate option just enabled the ns_random option + // + } elseif (0 == strncmp($option, 'rotate', 6)) { + $this->ns_random = true; + } + } + + return true; + } + + /** + * cleans up a failed socket and throws the given exception. + * + * @param string $_proto the protocol of the socket + * @param string $_ns the name server to use for the request + * @param string $_error the error message to throw at the end of the function + * + * @throws Net_DNS2_Exception + */ + private function generateError($_proto, $_ns, $_error) + { + if (false == isset($this->sock[$_proto][$_ns])) { + throw new Net_DNS2_Exception('invalid socket referenced', Net_DNS2_Lookups::E_NS_INVALID_SOCKET); + } + + // + // grab the last error message off the socket + // + $last_error = $this->sock[$_proto][$_ns]->last_error; + + // + // remove it from the socket cache; this will call the destructor, which calls close() on the socket + // + unset($this->sock[$_proto][$_ns]); + + // + // throw the error provided + // + throw new Net_DNS2_Exception($last_error, $_error); + } + + /** + * sends a DNS request using TCP. + * + * @param string $_ns the name server to use for the request + * @param string $_data the raw DNS packet data + * @param bool $_axfr if this is a zone transfer request + * + * @return Net_DNS2_Packet_Response the response object + * + * @throws Net_DNS2_Exception + */ + private function sendTCPRequest($_ns, $_data, $_axfr = false) + { + // + // grab the start time + // + $start_time = microtime(true); + + // + // see if we already have an open socket from a previous request; if so, try to use + // that instead of opening a new one. + // + if ((!isset($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns])) + || (!$this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] instanceof Net_DNS2_Socket) + ) { + // + // create the socket object + // + $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] = new Net_DNS2_Socket( + Net_DNS2_Socket::SOCK_STREAM, + $_ns, + $this->dns_port, + $this->timeout + ); + + // + // if a local IP address / port is set, then add it + // + if (strlen($this->local_host) > 0) { + $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->bindAddress( + $this->local_host, + $this->local_port + ); + } + + // + // open the socket + // + if (false === $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->open()) { + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + } + + // + // write the data to the socket; if it fails, continue on + // the while loop + // + if (false === $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->write($_data)) { + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // read the content, using select to wait for a response + // + $size = 0; + $result = null; + $response = null; + + // + // handle zone transfer requests differently than other requests. + // + if (true == $_axfr) { + $soa_count = 0; + + while (1) { + // + // read the data off the socket + // + $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read( + $size, + (true == $this->dnssec) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE + ); + + if ((false === $result) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { + // + // if we get an error, then keeping this socket around for a future request, could cause + // an error- for example, https://github.com/mikepultz/netdns2/issues/61 + // + // in this case, the connection was timing out, which once it did finally respond, left + // data on the socket, which could be captured on a subsequent request. + // + // since there's no way to "reset" a socket, the only thing we can do it close it. + // + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // parse the first chunk as a packet + // + $chunk = new Net_DNS2_Packet_Response($result, $size); + + // + // if this is the first packet, then clone it directly, then + // go through it to see if there are two SOA records + // (indicating that it's the only packet) + // + if (true == is_null($response)) { + $response = clone $chunk; + + // + // look for a failed response; if the zone transfer + // failed, then we don't need to do anything else at this + // point, and we should just break out. + // + if (Net_DNS2_Lookups::RCODE_NOERROR != $response->header->rcode) { + break; + } + + // + // go through each answer + // + foreach ($response->answer as $index => $rr) { + // + // count the SOA records + // + if ('SOA' == $rr->type) { + ++$soa_count; + } + } + + // + // if we have 2 or more SOA records, then we're done; + // otherwise continue out so we read the rest of the + // packets off the socket + // + if ($soa_count >= 2) { + break; + } + + continue; + } + + // + // go through all these answers, and look for SOA records + // + foreach ($chunk->answer as $index => $rr) { + // + // count the number of SOA records we find + // + if ('SOA' == $rr->type) { + ++$soa_count; + } + + // + // add the records to a single response object + // + $response->answer[] = $rr; + } + + // + // if we've found the second SOA record, we're done + // + if ($soa_count >= 2) { + break; + } + } + + // + // everything other than a AXFR + // + } else { + $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read( + $size, + (true == $this->dnssec) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE + ); + + if ((false === $result) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // create the packet object + // + $response = new Net_DNS2_Packet_Response($result, $size); + } + + // + // store the query time + // + $response->response_time = microtime(true) - $start_time; + + // + // add the name server that the response came from to the response object, + // and the socket type that was used. + // + $response->answer_from = $_ns; + $response->answer_socket_type = Net_DNS2_Socket::SOCK_STREAM; + + // + // return the Net_DNS2_Packet_Response object + // + return $response; + } + + /** + * sends a DNS request using UDP. + * + * @param string $_ns the name server to use for the request + * @param string $_data the raw DNS packet data + * + * @return Net_DNS2_Packet_Response the response object + * + * @throws Net_DNS2_Exception + */ + private function sendUDPRequest($_ns, $_data) + { + // + // grab the start time + // + $start_time = microtime(true); + + // + // see if we already have an open socket from a previous request; if so, try to use + // that instead of opening a new one. + // + if ((!isset($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns])) + || (!$this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] instanceof Net_DNS2_Socket) + ) { + // + // create the socket object + // + $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] = new Net_DNS2_Socket( + Net_DNS2_Socket::SOCK_DGRAM, + $_ns, + $this->dns_port, + $this->timeout + ); + + // + // if a local IP address / port is set, then add it + // + if (strlen($this->local_host) > 0) { + $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->bindAddress( + $this->local_host, + $this->local_port + ); + } + + // + // open the socket + // + if (false === $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->open()) { + $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + } + + // + // write the data to the socket + // + if (false === $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->write($_data)) { + $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // read the content, using select to wait for a response + // + $size = 0; + + $result = $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->read( + $size, + (true == $this->dnssec) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE + ); + + if ((false === $result) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { + $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // create the packet object + // + $response = new Net_DNS2_Packet_Response($result, $size); + + // + // store the query time + // + $response->response_time = microtime(true) - $start_time; + + // + // add the name server that the response came from to the response object, + // and the socket type that was used. + // + $response->answer_from = $_ns; + $response->answer_socket_type = Net_DNS2_Socket::SOCK_DGRAM; + + // + // return the Net_DNS2_Packet_Response object + // + return $response; + } } diff --git a/Net/DNS2/BitMap.php b/Net/DNS2/BitMap.php index 1891a362..9172b1c9 100644 --- a/Net/DNS2/BitMap.php +++ b/Net/DNS2/BitMap.php @@ -8,195 +8,179 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * a class to handle converting RR bitmaps to arrays and back; used on NSEC - * and NSEC3 RR's - * + * and NSEC3 RR's. */ class Net_DNS2_BitMap { - /** - * parses a RR bitmap field defined in RFC3845, into an array of RR names. - * - * Type Bit Map(s) Field = ( Window Block # | Bitmap Length | Bitmap ) + - * - * @param string $data a bitmap stringto parse - * - * @return array - * @access public - * - */ - public static function bitMapToArray($data) - { - if (strlen($data) == 0) { - return []; - } - - $output = []; - $offset = 0; - $length = strlen($data); - - while ($offset < $length) { - - // - // unpack the window and length values - // - $x = unpack('@' . $offset . '/Cwindow/Clength', $data); - $offset += 2; - - // - // copy out the bitmap value - // - $bitmap = unpack('C*', substr($data, $offset, $x['length'])); - $offset += $x['length']; - - // - // I'm not sure if there's a better way of doing this, but PHP doesn't - // have a 'B' flag for unpack() - // - $bitstr = ''; - foreach ($bitmap as $r) { - $bitstr .= sprintf('%08b', $r); - } - - $blen = strlen($bitstr); - for ($i=0; $i<$blen; $i++) { - - if ($bitstr[$i] == '1') { - $type = $x['window'] * 256 + $i; - - if (isset(Net_DNS2_Lookups::$rr_types_by_id[$type])) { - - $output[] = Net_DNS2_Lookups::$rr_types_by_id[$type]; - } else { - - $output[] = 'TYPE' . $type; - } - } - } - } - - return $output; - } - - /** - * builds a RR Bit map from an array of RR type names - * - * @param array $data a list of RR names - * - * @return string - * @access public - * - */ - public static function arrayToBitMap(array $data) - { - if (cacti_sizeof($data) == 0) { - return ''; - } - - $current_window = 0; - - // - // go through each RR - // - $max = 0; - $bm = []; - - foreach ($data as $rr) { - $rr = strtoupper($rr); - - // - // get the type id for the RR - // - $type = @Net_DNS2_Lookups::$rr_types_by_name[$rr]; - if (isset($type)) { - - // - // skip meta types or qtypes - // - if ( (isset(Net_DNS2_Lookups::$rr_qtypes_by_id[$type])) - || (isset(Net_DNS2_Lookups::$rr_metatypes_by_id[$type])) - ) { - continue; - } - - } else { - - // - // if it's not found, then it must be defined as TYPE, per - // RFC3845 section 2.2, if it's not, we ignore it. - // - list($name, $type) = explode('TYPE', $rr); - if (!isset($type)) { - - continue; - } - } - - // - // build the current window - // - $current_window = (int)($type / 256); - - $val = $type - $current_window * 256.0; - if ($val > $max) { - $max = $val; - } - - $bm[$current_window][$val] = 1; - $bm[$current_window]['length'] = ceil(($max + 1) / 8); - } - - $output = ''; - - foreach ($bm as $window => $bitdata) { - - $bitstr = ''; - - for ($i=0; $i<$bm[$window]['length'] * 8; $i++) { - if (isset($bm[$window][$i])) { - $bitstr .= '1'; - } else { - $bitstr .= '0'; - } - } - - $output .= pack('CC', $window, $bm[$window]['length']); - $output .= pack('H*', self::bigBaseConvert($bitstr)); - } - - return $output; - } - - /** - * a base_convert that handles large numbers; forced to 2/16 - * - * @param string $number a bit string - * - * @return string - * @access public - * - */ - public static function bigBaseConvert($number) - { - $result = ''; - - $bin = substr(chunk_split(strrev($number), 4, '-'), 0, -1); - $temp = preg_split('[-]', $bin, -1, PREG_SPLIT_DELIM_CAPTURE); - - for ($i = cacti_sizeof($temp)-1;$i >= 0;$i--) { - $result = $result . base_convert(strrev($temp[$i]), 2, 16); - } - - return strtoupper($result); - } + /** + * parses a RR bitmap field defined in RFC3845, into an array of RR names. + * + * Type Bit Map(s) Field = ( Window Block # | Bitmap Length | Bitmap ) + + * + * @param string $data a bitmap stringto parse + * + * @return array + */ + public static function bitMapToArray($data) + { + if (0 == strlen($data)) { + return []; + } + + $output = []; + $offset = 0; + $length = strlen($data); + + while ($offset < $length) { + // + // unpack the window and length values + // + $x = unpack('@'.$offset.'/Cwindow/Clength', $data); + $offset += 2; + + // + // copy out the bitmap value + // + $bitmap = unpack('C*', substr($data, $offset, $x['length'])); + $offset += $x['length']; + + // + // I'm not sure if there's a better way of doing this, but PHP doesn't + // have a 'B' flag for unpack() + // + $bitstr = ''; + foreach ($bitmap as $r) { + $bitstr .= sprintf('%08b', $r); + } + + $blen = strlen($bitstr); + for ($i = 0; $i < $blen; ++$i) { + if ('1' == $bitstr[$i]) { + $type = $x['window'] * 256 + $i; + + if (isset(Net_DNS2_Lookups::$rr_types_by_id[$type])) { + $output[] = Net_DNS2_Lookups::$rr_types_by_id[$type]; + } else { + $output[] = 'TYPE'.$type; + } + } + } + } + + return $output; + } + + /** + * builds a RR Bit map from an array of RR type names. + * + * @param array $data a list of RR names + * + * @return string + */ + public static function arrayToBitMap(array $data) + { + if (0 == cacti_sizeof($data)) { + return ''; + } + + $current_window = 0; + + // + // go through each RR + // + $max = 0; + $bm = []; + + foreach ($data as $rr) { + $rr = strtoupper($rr); + + // + // get the type id for the RR + // + $type = @Net_DNS2_Lookups::$rr_types_by_name[$rr]; + if (isset($type)) { + // + // skip meta types or qtypes + // + if ((isset(Net_DNS2_Lookups::$rr_qtypes_by_id[$type])) + || (isset(Net_DNS2_Lookups::$rr_metatypes_by_id[$type])) + ) { + continue; + } + } else { + // + // if it's not found, then it must be defined as TYPE, per + // RFC3845 section 2.2, if it's not, we ignore it. + // + list($name, $type) = explode('TYPE', $rr); + if (!isset($type)) { + continue; + } + } + + // + // build the current window + // + $current_window = (int) ($type / 256); + + $val = $type - $current_window * 256.0; + if ($val > $max) { + $max = $val; + } + + $bm[$current_window][$val] = 1; + $bm[$current_window]['length'] = ceil(($max + 1) / 8); + } + + $output = ''; + + foreach ($bm as $window => $bitdata) { + $bitstr = ''; + + for ($i = 0; $i < $bm[$window]['length'] * 8; ++$i) { + if (isset($bm[$window][$i])) { + $bitstr .= '1'; + } else { + $bitstr .= '0'; + } + } + + $output .= pack('CC', $window, $bm[$window]['length']); + $output .= pack('H*', self::bigBaseConvert($bitstr)); + } + + return $output; + } + + /** + * a base_convert that handles large numbers; forced to 2/16. + * + * @param string $number a bit string + * + * @return string + */ + public static function bigBaseConvert($number) + { + $result = ''; + + $bin = substr(chunk_split(strrev($number), 4, '-'), 0, -1); + $temp = preg_split('[-]', $bin, -1, PREG_SPLIT_DELIM_CAPTURE); + + for ($i = cacti_sizeof($temp) - 1; $i >= 0; --$i) { + $result = $result.base_convert(strrev($temp[$i]), 2, 16); + } + + return strtoupper($result); + } } diff --git a/Net/DNS2/Cache.php b/Net/DNS2/Cache.php index 721a5871..97a2769a 100644 --- a/Net/DNS2/Cache.php +++ b/Net/DNS2/Cache.php @@ -8,256 +8,218 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.1.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.1.0 */ /** * A class to provide simple dns lookup caching. - * */ class Net_DNS2_Cache { - /* - * the filename of the cache file - */ - protected $cache_file = ''; - - /* - * the local data store for the cache - */ - protected $cache_data = []; - - /* - * the size of the cache to use - */ - protected $cache_size = 0; - - /* - * the cache serializer - */ - protected $cache_serializer; - - /* - * an internal flag to make sure we don't load the cache content more - * than once per instance. - */ - protected $cache_opened = false; - - /** - * returns true/false if the provided key is defined in the cache - * - * @param string $key the key to lookup in the local cache - * - * @return boolean - * @access public - * - */ - public function has($key) - { - return isset($this->cache_data[$key]); - } - - /** - * returns the value for the given key - * - * @param string $key the key to lookup in the local cache - * - * @return mixed returns the cache data on success, false on error - * @access public - * - */ - public function get($key) - { - if (isset($this->cache_data[$key])) { - - if ($this->cache_serializer == 'json') { - return json_decode($this->cache_data[$key]['object']); - } else { - return unserialize($this->cache_data[$key]['object']); - } - } else { - - return false; - } - } - - /** - * adds a new key/value pair to the cache - * - * @param string $key the key for the new cache entry - * @param mixed $data the data to store in cache - * - * @return void - * @access public - * - */ - public function put($key, $data) - { - $ttl = 86400 * 365; - - // - // clear the rdata values - // - $data->rdata = ''; - $data->rdlength = 0; - - // - // find the lowest TTL, and use that as the TTL for the whole cached - // object. The downside to using one TTL for the whole object, is that - // we'll invalidate entries before they actually expire, causing a - // real lookup to happen. - // - // The upside is that we don't need to require() each RR type in the - // cache, so we can look at their individual TTL's on each run- we only - // unserialize the actual RR object when it's get() from the cache. - // - foreach ($data->answer as $index => $rr) { - - if ($rr->ttl < $ttl) { - $ttl = $rr->ttl; - } - - $rr->rdata = ''; - $rr->rdlength = 0; - } - foreach ($data->authority as $index => $rr) { - - if ($rr->ttl < $ttl) { - $ttl = $rr->ttl; - } - - $rr->rdata = ''; - $rr->rdlength = 0; - } - foreach ($data->additional as $index => $rr) { - - if ($rr->ttl < $ttl) { - $ttl = $rr->ttl; - } - - $rr->rdata = ''; - $rr->rdlength = 0; - } - - $this->cache_data[$key] = [ - - 'cache_date' => time(), - 'ttl' => $ttl - ]; - - if ($this->cache_serializer == 'json') { - $this->cache_data[$key]['object'] = json_encode($data); - } else { - $this->cache_data[$key]['object'] = serialize($data); - } - } - - /** - * runs a clean up process on the cache data - * - * @return void - * @access protected - * - */ - protected function clean() - { - if (cacti_sizeof($this->cache_data) > 0) { - - // - // go through each entry and adjust their TTL, and remove entries that - // have expired - // - $now = time(); - - foreach ($this->cache_data as $key => $data) { - - $diff = $now - $data['cache_date']; - - if ($data['ttl'] <= $diff) { - - unset($this->cache_data[$key]); - } else { - - $this->cache_data[$key]['ttl'] -= $diff; - $this->cache_data[$key]['cache_date'] = $now; - } - } - } - } - - /** - * runs a clean up process on the cache data - * - * @return mixed - * @access protected - * - */ - protected function resize() - { - if (cacti_sizeof($this->cache_data) > 0) { - - // - // serialize the cache data - // - if ($this->cache_serializer == 'json') { - $cache = json_encode($this->cache_data); - } else { - $cache = serialize($this->cache_data); - } - - // - // only do this part if the size allocated to the cache storage - // is smaller than the actual cache data - // - if (strlen($cache) > $this->cache_size) { - - while (strlen($cache) > $this->cache_size) { - - // - // go through the data, and remove the entries closed to - // their expiration date. - // - $smallest_ttl = time(); - $smallest_key = null; - - foreach ($this->cache_data as $key => $data) { - - if ($data['ttl'] < $smallest_ttl) { - - $smallest_ttl = $data['ttl']; - $smallest_key = $key; - } - } - - // - // unset the key with the smallest TTL - // - unset($this->cache_data[$smallest_key]); - - // - // re-serialize - // - if ($this->cache_serializer == 'json') { - $cache = json_encode($this->cache_data); - } else { - $cache = serialize($this->cache_data); - } - } - } - - if ( ($cache == 'a:0:{}') || ($cache == '{}') ) { - return null; - } else { - return $cache; - } - } - - return null; - } + // the filename of the cache file + protected $cache_file = ''; + + // the local data store for the cache + protected $cache_data = []; + + // the size of the cache to use + protected $cache_size = 0; + + // the cache serializer + protected $cache_serializer; + + /* + * an internal flag to make sure we don't load the cache content more + * than once per instance. + */ + protected $cache_opened = false; + + /** + * returns true/false if the provided key is defined in the cache. + * + * @param string $key the key to lookup in the local cache + * + * @return bool + */ + public function has($key) + { + return isset($this->cache_data[$key]); + } + + /** + * returns the value for the given key. + * + * @param string $key the key to lookup in the local cache + * + * @return mixed returns the cache data on success, false on error + */ + public function get($key) + { + if (isset($this->cache_data[$key])) { + if ('json' == $this->cache_serializer) { + return json_decode($this->cache_data[$key]['object']); + } + + return unserialize($this->cache_data[$key]['object']); + } + + return false; + } + + /** + * adds a new key/value pair to the cache. + * + * @param string $key the key for the new cache entry + * @param mixed $data the data to store in cache + */ + public function put($key, $data) + { + $ttl = 86400 * 365; + + // + // clear the rdata values + // + $data->rdata = ''; + $data->rdlength = 0; + + // + // find the lowest TTL, and use that as the TTL for the whole cached + // object. The downside to using one TTL for the whole object, is that + // we'll invalidate entries before they actually expire, causing a + // real lookup to happen. + // + // The upside is that we don't need to require() each RR type in the + // cache, so we can look at their individual TTL's on each run- we only + // unserialize the actual RR object when it's get() from the cache. + // + foreach ($data->answer as $index => $rr) { + if ($rr->ttl < $ttl) { + $ttl = $rr->ttl; + } + + $rr->rdata = ''; + $rr->rdlength = 0; + } + foreach ($data->authority as $index => $rr) { + if ($rr->ttl < $ttl) { + $ttl = $rr->ttl; + } + + $rr->rdata = ''; + $rr->rdlength = 0; + } + foreach ($data->additional as $index => $rr) { + if ($rr->ttl < $ttl) { + $ttl = $rr->ttl; + } + + $rr->rdata = ''; + $rr->rdlength = 0; + } + + $this->cache_data[$key] = [ + 'cache_date' => time(), + 'ttl' => $ttl, + ]; + + if ('json' == $this->cache_serializer) { + $this->cache_data[$key]['object'] = json_encode($data); + } else { + $this->cache_data[$key]['object'] = serialize($data); + } + } + + /** + * runs a clean up process on the cache data. + */ + protected function clean() + { + if (cacti_sizeof($this->cache_data) > 0) { + // + // go through each entry and adjust their TTL, and remove entries that + // have expired + // + $now = time(); + + foreach ($this->cache_data as $key => $data) { + $diff = $now - $data['cache_date']; + + if ($data['ttl'] <= $diff) { + unset($this->cache_data[$key]); + } else { + $this->cache_data[$key]['ttl'] -= $diff; + $this->cache_data[$key]['cache_date'] = $now; + } + } + } + } + + /** + * runs a clean up process on the cache data. + * + * @return mixed + */ + protected function resize() + { + if (cacti_sizeof($this->cache_data) > 0) { + // + // serialize the cache data + // + if ('json' == $this->cache_serializer) { + $cache = json_encode($this->cache_data); + } else { + $cache = serialize($this->cache_data); + } + + // + // only do this part if the size allocated to the cache storage + // is smaller than the actual cache data + // + if (strlen($cache) > $this->cache_size) { + while (strlen($cache) > $this->cache_size) { + // + // go through the data, and remove the entries closed to + // their expiration date. + // + $smallest_ttl = time(); + $smallest_key = null; + + foreach ($this->cache_data as $key => $data) { + if ($data['ttl'] < $smallest_ttl) { + $smallest_ttl = $data['ttl']; + $smallest_key = $key; + } + } + + // + // unset the key with the smallest TTL + // + unset($this->cache_data[$smallest_key]); + + // + // re-serialize + // + if ('json' == $this->cache_serializer) { + $cache = json_encode($this->cache_data); + } else { + $cache = serialize($this->cache_data); + } + } + } + + if (('a:0:{}' == $cache) || ('{}' == $cache)) { + return null; + } + + return $cache; + } + + return null; + } } diff --git a/Net/DNS2/Cache/File.php b/Net/DNS2/Cache/File.php index a0e0b7bf..00992419 100644 --- a/Net/DNS2/Cache/File.php +++ b/Net/DNS2/Cache/File.php @@ -1,122 +1,36 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.1.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.1.0 */ /** - * File-based caching for the Net_DNS2_Cache class - * + * File-based caching for the Net_DNS2_Cache class. */ class Net_DNS2_Cache_File extends Net_DNS2_Cache { /** - * open a cache object - * - * @param string $cache_file path to a file to use for cache storage - * @param integer $size the size of the shared memory segment to create - * @param string $serializer the name of the cache serialize to use - * - * @throws Net_DNS2_Exception - * @access public - * @return void - * - */ - public function open($cache_file, $size, $serializer) - { - $this->cache_size = $size; - $this->cache_file = $cache_file; - $this->cache_serializer = $serializer; - - // - // check that the file exists first - // - if ( ($this->cache_opened == false) - && (file_exists($this->cache_file) == true) - && (filesize($this->cache_file) > 0) - ) { - // - // open the file for reading - // - $fp = @fopen($this->cache_file, 'r'); - if ($fp !== false) { - - // - // lock the file just in case - // - flock($fp, LOCK_EX); - - // - // read the file contents - // - $data = fread($fp, filesize($this->cache_file)); - - $decoded = null; - - if ($this->cache_serializer == 'json') { - - $decoded = json_decode($data, true); - } else { - - $decoded = unserialize($data); - } - - if (is_array($decoded) == true) { - - $this->cache_data = $decoded; - } else { - - $this->cache_data = []; - } - - // - // unlock - // - flock($fp, LOCK_UN); - - // - // close the file - // - fclose($fp); - - // - // clean up the data - // - $this->clean(); - - // - // mark this so we don't read this contents more than once per instance. - // - $this->cache_opened = true; - } - } - } - - /** - * Destructor - * - * @access public - * + * Destructor. */ public function __destruct() { // // if there's no cache file set, then there's nothing to do // - if (strlen($this->cache_file) == 0) { + if (0 == strlen($this->cache_file)) { return; } @@ -124,13 +38,12 @@ public function __destruct() // open the file for reading/writing // $fp = fopen($this->cache_file, 'a+'); - if ($fp !== false) { - + if (false !== $fp) { // // lock the file just in case // flock($fp, LOCK_EX); - + // // seek to the start of the file to read // @@ -140,8 +53,7 @@ public function __destruct() // read the file contents // $data = @fread($fp, filesize($this->cache_file)); - if ( ($data !== false) && (strlen($data) > 0) ) { - + if ((false !== $data) && (strlen($data) > 0)) { // // unserialize and store the data // @@ -149,16 +61,13 @@ public function __destruct() $decoded = null; - if ($this->cache_serializer == 'json') { - + if ('json' == $this->cache_serializer) { $decoded = json_decode($data, true); } else { - $decoded = unserialize($data); } - - if (is_array($decoded) == true) { + if (true == is_array($decoded)) { $this->cache_data = array_merge($c, $decoded); } } @@ -178,7 +87,6 @@ public function __destruct() // $data = $this->resize(); if (!is_null($data)) { - // // write the file contents // @@ -196,4 +104,78 @@ public function __destruct() fclose($fp); } } + + /** + * open a cache object. + * + * @param string $cache_file path to a file to use for cache storage + * @param int $size the size of the shared memory segment to create + * @param string $serializer the name of the cache serialize to use + * + * @throws Net_DNS2_Exception + */ + public function open($cache_file, $size, $serializer) + { + $this->cache_size = $size; + $this->cache_file = $cache_file; + $this->cache_serializer = $serializer; + + // + // check that the file exists first + // + if ((false == $this->cache_opened) + && (true == file_exists($this->cache_file)) + && (filesize($this->cache_file) > 0) + ) { + // + // open the file for reading + // + $fp = @fopen($this->cache_file, 'r'); + if (false !== $fp) { + // + // lock the file just in case + // + flock($fp, LOCK_EX); + + // + // read the file contents + // + $data = fread($fp, filesize($this->cache_file)); + + $decoded = null; + + if ('json' == $this->cache_serializer) { + $decoded = json_decode($data, true); + } else { + $decoded = unserialize($data); + } + + if (true == is_array($decoded)) { + $this->cache_data = $decoded; + } else { + $this->cache_data = []; + } + + // + // unlock + // + flock($fp, LOCK_UN); + + // + // close the file + // + fclose($fp); + + // + // clean up the data + // + $this->clean(); + + // + // mark this so we don't read this contents more than once per instance. + // + $this->cache_opened = true; + } + } + } } diff --git a/Net/DNS2/Cache/Shm.php b/Net/DNS2/Cache/Shm.php index 5308b53f..38b9c42c 100644 --- a/Net/DNS2/Cache/Shm.php +++ b/Net/DNS2/Cache/Shm.php @@ -1,163 +1,47 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.1.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.1.0 */ /** - * Shared Memory-based caching for the Net_DNS2_Cache class - * + * Shared Memory-based caching for the Net_DNS2_Cache class. */ class Net_DNS2_Cache_Shm extends Net_DNS2_Cache { - /* - * resource id of the shared memory cache - */ + // resource id of the shared memory cache private $_cache_id = false; - /* - * the IPC key - */ + // the IPC key private $_cache_file_tok = -1; /** - * open a cache object - * - * @param string $cache_file path to a file to use for cache storage - * @param integer $size the size of the shared memory segment to create - * @param string $serializer the name of the cache serialize to use - * - * @throws Net_DNS2_Exception - * @access public - * @return void - * - */ - public function open($cache_file, $size, $serializer) - { - $this->cache_size = $size; - $this->cache_file = $cache_file; - $this->cache_serializer = $serializer; - - // - // if we've already loaded the cache data, then just return right away - // - if ($this->cache_opened == true) - { - return; - } - - // - // make sure the file exists first - // - if (!file_exists($cache_file)) { - - if (file_put_contents($cache_file, '') === false) { - - throw new Net_DNS2_Exception( - 'failed to create empty SHM file: ' . $cache_file, - Net_DNS2_Lookups::E_CACHE_SHM_FILE - ); - } - } - - // - // convert the filename to a IPC key - // - $this->_cache_file_tok = ftok($cache_file, 't'); - if ($this->_cache_file_tok == -1) { - - throw new Net_DNS2_Exception( - 'failed on ftok() file: ' . $this->_cache_file_tok, - Net_DNS2_Lookups::E_CACHE_SHM_FILE - ); - } - - // - // try to open an existing cache; if it doesn't exist, then there's no - // cache, and nothing to do. - // - $this->_cache_id = @shmop_open($this->_cache_file_tok, 'w', 0, 0); - if ($this->_cache_id !== false) { - - // - // this returns the size allocated, and not the size used, but it's - // still a good check to make sure there's space allocated. - // - $allocated = shmop_size($this->_cache_id); - if ($allocated > 0) { - - // - // read the data from the shared memory segment - // - $data = trim(shmop_read($this->_cache_id, 0, $allocated)); - if ( ($data !== false) && (strlen($data) > 0) ) { - - // - // unserialize and store the data - // - $decoded = null; - - if ($this->cache_serializer == 'json') { - - $decoded = json_decode($data, true); - } else { - - $decoded = unserialize($data); - } - - if (is_array($decoded) == true) { - - $this->cache_data = $decoded; - } else { - - $this->cache_data = []; - } - - // - // call clean to clean up old entries - // - $this->clean(); - - // - // mark the cache as loaded, so we don't load it more than once - // - $this->cache_opened = true; - } - } - } - } - - /** - * Destructor - * - * @access public - * + * Destructor. */ public function __destruct() { // // if there's no cache file set, then there's nothing to do // - if (strlen($this->cache_file) == 0) { + if (0 == strlen($this->cache_file)) { return; } $fp = fopen($this->cache_file, 'r'); - if ($fp !== false) { - + if (false !== $fp) { // // lock the file // @@ -166,22 +50,26 @@ public function __destruct() // // check to see if we have an open shm segment // - if ($this->_cache_id === false) { - + if (false === $this->_cache_id) { // // try opening it again, incase it was created by another // process in the mean time // $this->_cache_id = @shmop_open( - $this->_cache_file_tok, 'w', 0, 0 + $this->_cache_file_tok, + 'w', + 0, + 0 ); - if ($this->_cache_id === false) { - + if (false === $this->_cache_id) { // // otherwise, create it. // $this->_cache_id = @shmop_open( - $this->_cache_file_tok, 'c', 0, $this->cache_size + $this->_cache_file_tok, + 'c', + 0, + $this->cache_size ); } } @@ -198,26 +86,22 @@ public function __destruct() // // if there was some data - // - if ( ($data !== false) && (strlen($data) > 0) ) { - + // + if ((false !== $data) && (strlen($data) > 0)) { // // unserialize and store the data // $c = $this->cache_data; $decoded = null; - - if ($this->cache_serializer == 'json') { - + + if ('json' == $this->cache_serializer) { $decoded = json_decode($data, true); } else { - $decoded = unserialize($data); - } - - if (is_array($decoded) == true) { - + } + + if (true == is_array($decoded)) { $this->cache_data = array_merge($c, $decoded); } } @@ -237,14 +121,16 @@ public function __destruct() // $data = $this->resize(); if (!is_null($data)) { - // // re-create segment // $this->_cache_id = @shmop_open( - $this->_cache_file_tok, 'c', 0644, $this->cache_size + $this->_cache_file_tok, + 'c', + 0644, + $this->cache_size ); - if ($this->_cache_id === false) { + if (false === $this->_cache_id) { return; } @@ -267,4 +153,97 @@ public function __destruct() fclose($fp); } } + + /** + * open a cache object. + * + * @param string $cache_file path to a file to use for cache storage + * @param int $size the size of the shared memory segment to create + * @param string $serializer the name of the cache serialize to use + * + * @throws Net_DNS2_Exception + */ + public function open($cache_file, $size, $serializer) + { + $this->cache_size = $size; + $this->cache_file = $cache_file; + $this->cache_serializer = $serializer; + + // + // if we've already loaded the cache data, then just return right away + // + if (true == $this->cache_opened) { + return; + } + + // + // make sure the file exists first + // + if (!file_exists($cache_file)) { + if (false === file_put_contents($cache_file, '')) { + throw new Net_DNS2_Exception( + 'failed to create empty SHM file: '.$cache_file, + Net_DNS2_Lookups::E_CACHE_SHM_FILE + ); + } + } + + // + // convert the filename to a IPC key + // + $this->_cache_file_tok = ftok($cache_file, 't'); + if (-1 == $this->_cache_file_tok) { + throw new Net_DNS2_Exception( + 'failed on ftok() file: '.$this->_cache_file_tok, + Net_DNS2_Lookups::E_CACHE_SHM_FILE + ); + } + + // + // try to open an existing cache; if it doesn't exist, then there's no + // cache, and nothing to do. + // + $this->_cache_id = @shmop_open($this->_cache_file_tok, 'w', 0, 0); + if (false !== $this->_cache_id) { + // + // this returns the size allocated, and not the size used, but it's + // still a good check to make sure there's space allocated. + // + $allocated = shmop_size($this->_cache_id); + if ($allocated > 0) { + // + // read the data from the shared memory segment + // + $data = trim(shmop_read($this->_cache_id, 0, $allocated)); + if ((false !== $data) && (strlen($data) > 0)) { + // + // unserialize and store the data + // + $decoded = null; + + if ('json' == $this->cache_serializer) { + $decoded = json_decode($data, true); + } else { + $decoded = unserialize($data); + } + + if (true == is_array($decoded)) { + $this->cache_data = $decoded; + } else { + $this->cache_data = []; + } + + // + // call clean to clean up old entries + // + $this->clean(); + + // + // mark the cache as loaded, so we don't load it more than once + // + $this->cache_opened = true; + } + } + } + } } diff --git a/Net/DNS2/Exception.php b/Net/DNS2/Exception.php index 3b9e93c2..0e802757 100644 --- a/Net/DNS2/Exception.php +++ b/Net/DNS2/Exception.php @@ -1,25 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * Exception handler used by Net_DNS2 - * + * Exception handler used by Net_DNS2. */ class Net_DNS2_Exception extends Exception { @@ -28,23 +27,20 @@ class Net_DNS2_Exception extends Exception /** * Constructor - overload the constructor so we can pass in the request - * and response object (when it's available) + * and response object (when it's available). * * @param string $message the exception message * @param int $code the exception code * @param object $previous the previous Exception object * @param object $request the Net_DNS2_Packet_Request object for this request * @param object $response the Net_DNS2_Packet_Response object for this request - * - * @access public - * */ public function __construct( - $message = '', - $code = 0, - $previous = null, - Net_DNS2_Packet_Request $request = null, - Net_DNS2_Packet_Response $response = null + $message = '', + $code = 0, + $previous = null, + ?Net_DNS2_Packet_Request $request = null, + ?Net_DNS2_Packet_Response $response = null ) { // // store the request/response objects (if passed) @@ -59,22 +55,19 @@ public function __construct( // // https://code.google.com/p/netdns2/issues/detail?id=25 // - if (version_compare(PHP_VERSION, '5.3.0', '>=') == true) { - + if (true == version_compare(PHP_VERSION, '5.3.0', '>=')) { parent::__construct($message, $code, $previous); } else { - parent::__construct($message, $code); } } /** - * returns the Net_DNS2_Packet_Request object (if available) + * returns the Net_DNS2_Packet_Request object (if available). * * @return Net_DNS2_Packet_Request object - * @access public - * @since function available since release 1.3.1 * + * @since function available since release 1.3.1 */ public function getRequest() { @@ -82,12 +75,11 @@ public function getRequest() } /** - * returns the Net_DNS2_Packet_Response object (if available) + * returns the Net_DNS2_Packet_Response object (if available). * * @return Net_DNS2_Packet_Response object - * @access public - * @since function available since release 1.3.1 * + * @since function available since release 1.3.1 */ public function getResponse() { diff --git a/Net/DNS2/Header.php b/Net/DNS2/Header.php index 6532ec10..b3229215 100644 --- a/Net/DNS2/Header.php +++ b/Net/DNS2/Header.php @@ -1,28 +1,28 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * DNS Packet Header class + * DNS Packet Header class. * * This class handles parsing and constructing DNS Packet Headers as defined * by section 4.1.1 of RFC1035. - * + * * DNS header format - RFC1035 section 4.1.1 * DNS header format - RFC4035 section 3.2 * @@ -40,7 +40,6 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | ARCOUNT | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_Header { @@ -61,95 +60,85 @@ class Net_DNS2_Header public $arcount; // 16 bit - rr's in the additional records section /** - * Constructor - builds a new Net_DNS2_Header object + * Constructor - builds a new Net_DNS2_Header object. * * @param mixed &$packet either a Net_DNS2_Packet object or null * * @throws Net_DNS2_Exception - * @access public - * */ - public function __construct(Net_DNS2_Packet &$packet = null) + public function __construct(?Net_DNS2_Packet &$packet = null) { if (!is_null($packet)) { - $this->set($packet); } else { - - $this->id = $this->nextPacketId(); - $this->qr = Net_DNS2_Lookups::QR_QUERY; - $this->opcode = Net_DNS2_Lookups::OPCODE_QUERY; - $this->aa = 0; - $this->tc = 0; - $this->rd = 1; - $this->ra = 0; - $this->z = 0; - $this->ad = 0; - $this->cd = 0; - $this->rcode = Net_DNS2_Lookups::RCODE_NOERROR; - $this->qdcount = 1; - $this->ancount = 0; - $this->nscount = 0; - $this->arcount = 0; + $this->id = $this->nextPacketId(); + $this->qr = Net_DNS2_Lookups::QR_QUERY; + $this->opcode = Net_DNS2_Lookups::OPCODE_QUERY; + $this->aa = 0; + $this->tc = 0; + $this->rd = 1; + $this->ra = 0; + $this->z = 0; + $this->ad = 0; + $this->cd = 0; + $this->rcode = Net_DNS2_Lookups::RCODE_NOERROR; + $this->qdcount = 1; + $this->ancount = 0; + $this->nscount = 0; + $this->arcount = 0; } } /** - * returns the next available packet id - * - * @return integer - * @access public + * magic __toString() method to return the header as a string. * + * @return string */ - public function nextPacketId() + public function __toString() { - if (++Net_DNS2_Lookups::$next_packet_id > 65535) { + $output = ";;\n;; Header:\n"; - Net_DNS2_Lookups::$next_packet_id = 1; - } + $output .= ";;\t id = ".$this->id."\n"; + $output .= ";;\t qr = ".$this->qr."\n"; + $output .= ";;\t opcode = ".$this->opcode."\n"; + $output .= ";;\t aa = ".$this->aa."\n"; + $output .= ";;\t tc = ".$this->tc."\n"; + $output .= ";;\t rd = ".$this->rd."\n"; + $output .= ";;\t ra = ".$this->ra."\n"; + $output .= ";;\t z = ".$this->z."\n"; + $output .= ";;\t ad = ".$this->ad."\n"; + $output .= ";;\t cd = ".$this->cd."\n"; + $output .= ";;\t rcode = ".$this->rcode."\n"; + $output .= ";;\t qdcount = ".$this->qdcount."\n"; + $output .= ";;\t ancount = ".$this->ancount."\n"; + $output .= ";;\t nscount = ".$this->nscount."\n"; + $output .= ";;\t arcount = ".$this->arcount."\n"; - return Net_DNS2_Lookups::$next_packet_id; + return $output; } /** - * magic __toString() method to return the header as a string - * - * @return string - * @access public + * returns the next available packet id. * + * @return int */ - public function __toString() + public function nextPacketId() { - $output = ";;\n;; Header:\n"; - - $output .= ";;\t id = " . $this->id . "\n"; - $output .= ";;\t qr = " . $this->qr . "\n"; - $output .= ";;\t opcode = " . $this->opcode . "\n"; - $output .= ";;\t aa = " . $this->aa . "\n"; - $output .= ";;\t tc = " . $this->tc . "\n"; - $output .= ";;\t rd = " . $this->rd . "\n"; - $output .= ";;\t ra = " . $this->ra . "\n"; - $output .= ";;\t z = " . $this->z . "\n"; - $output .= ";;\t ad = " . $this->ad . "\n"; - $output .= ";;\t cd = " . $this->cd . "\n"; - $output .= ";;\t rcode = " . $this->rcode . "\n"; - $output .= ";;\t qdcount = " . $this->qdcount . "\n"; - $output .= ";;\t ancount = " . $this->ancount . "\n"; - $output .= ";;\t nscount = " . $this->nscount . "\n"; - $output .= ";;\t arcount = " . $this->arcount . "\n"; + if (++Net_DNS2_Lookups::$next_packet_id > 65535) { + Net_DNS2_Lookups::$next_packet_id = 1; + } - return $output; + return Net_DNS2_Lookups::$next_packet_id; } /** - * constructs a Net_DNS2_Header from a Net_DNS2_Packet object + * constructs a Net_DNS2_Header from a Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet Object * - * @return boolean - * @throws Net_DNS2_Exception - * @access public + * @return bool * + * @throws Net_DNS2_Exception */ public function set(Net_DNS2_Packet &$packet) { @@ -157,7 +146,6 @@ public function set(Net_DNS2_Packet &$packet) // the header must be at least 12 bytes long. // if ($packet->rdlength < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - throw new Net_DNS2_Exception( 'invalid header data provided; too small', Net_DNS2_Lookups::E_HEADER_INVALID @@ -169,31 +157,31 @@ public function set(Net_DNS2_Packet &$packet) // // parse the values // - $this->id = ord($packet->rdata[$offset]) << 8 | - ord($packet->rdata[++$offset]); + $this->id = ord($packet->rdata[$offset]) << 8 + | ord($packet->rdata[++$offset]); ++$offset; - $this->qr = (ord($packet->rdata[$offset]) >> 7) & 0x1; - $this->opcode = (ord($packet->rdata[$offset]) >> 3) & 0xf; - $this->aa = (ord($packet->rdata[$offset]) >> 2) & 0x1; - $this->tc = (ord($packet->rdata[$offset]) >> 1) & 0x1; - $this->rd = ord($packet->rdata[$offset]) & 0x1; + $this->qr = (ord($packet->rdata[$offset]) >> 7) & 0x1; + $this->opcode = (ord($packet->rdata[$offset]) >> 3) & 0xF; + $this->aa = (ord($packet->rdata[$offset]) >> 2) & 0x1; + $this->tc = (ord($packet->rdata[$offset]) >> 1) & 0x1; + $this->rd = ord($packet->rdata[$offset]) & 0x1; ++$offset; - $this->ra = (ord($packet->rdata[$offset]) >> 7) & 0x1; - $this->z = (ord($packet->rdata[$offset]) >> 6) & 0x1; - $this->ad = (ord($packet->rdata[$offset]) >> 5) & 0x1; - $this->cd = (ord($packet->rdata[$offset]) >> 4) & 0x1; - $this->rcode = ord($packet->rdata[$offset]) & 0xf; - - $this->qdcount = ord($packet->rdata[++$offset]) << 8 | - ord($packet->rdata[++$offset]); - $this->ancount = ord($packet->rdata[++$offset]) << 8 | - ord($packet->rdata[++$offset]); - $this->nscount = ord($packet->rdata[++$offset]) << 8 | - ord($packet->rdata[++$offset]); - $this->arcount = ord($packet->rdata[++$offset]) << 8 | - ord($packet->rdata[++$offset]); + $this->ra = (ord($packet->rdata[$offset]) >> 7) & 0x1; + $this->z = (ord($packet->rdata[$offset]) >> 6) & 0x1; + $this->ad = (ord($packet->rdata[$offset]) >> 5) & 0x1; + $this->cd = (ord($packet->rdata[$offset]) >> 4) & 0x1; + $this->rcode = ord($packet->rdata[$offset]) & 0xF; + + $this->qdcount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + $this->ancount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + $this->nscount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + $this->arcount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); // // increment the internal offset @@ -204,26 +192,24 @@ public function set(Net_DNS2_Packet &$packet) } /** - * returns a binary packed DNS Header + * returns a binary packed DNS Header. * * @param Net_DNS2_Packet &$packet Object * - * @return string - * @access public - * + * @return string */ public function get(Net_DNS2_Packet &$packet) { $packet->offset += Net_DNS2_Lookups::DNS_HEADER_SIZE; - return pack('n', $this->id) . - chr( - ($this->qr << 7) | ($this->opcode << 3) | - ($this->aa << 2) | ($this->tc << 1) | ($this->rd) - ) . - chr( + return pack('n', $this->id) + .chr( + ($this->qr << 7) | ($this->opcode << 3) + | ($this->aa << 2) | ($this->tc << 1) | $this->rd + ) + .chr( ($this->ra << 7) | ($this->ad << 5) | ($this->cd << 4) | $this->rcode - ) . - pack('n4', $this->qdcount, $this->ancount, $this->nscount, $this->arcount); + ) + .pack('n4', $this->qdcount, $this->ancount, $this->nscount, $this->arcount); } } diff --git a/Net/DNS2/Lookups.php b/Net/DNS2/Lookups.php index 9b223f54..f1e86403 100644 --- a/Net/DNS2/Lookups.php +++ b/Net/DNS2/Lookups.php @@ -1,560 +1,512 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ // // initialize the packet id value // -Net_DNS2_Lookups::$next_packet_id = mt_rand(0, 65535); +Net_DNS2_Lookups::$next_packet_id = mt_rand(0, 65535); // // build the reverse lookup tables; this is just so we don't have to // have duplicate static content laying around. // -Net_DNS2_Lookups::$rr_types_by_id = array_flip(Net_DNS2_Lookups::$rr_types_by_name); -Net_DNS2_Lookups::$classes_by_id = array_flip(Net_DNS2_Lookups::$classes_by_name); +Net_DNS2_Lookups::$rr_types_by_id = array_flip(Net_DNS2_Lookups::$rr_types_by_name); +Net_DNS2_Lookups::$classes_by_id = array_flip(Net_DNS2_Lookups::$classes_by_name); Net_DNS2_Lookups::$rr_types_class_to_id = array_flip(Net_DNS2_Lookups::$rr_types_id_to_class); Net_DNS2_Lookups::$algorithm_name_to_id = array_flip(Net_DNS2_Lookups::$algorithm_id_to_name); -Net_DNS2_Lookups::$digest_name_to_id = array_flip(Net_DNS2_Lookups::$digest_id_to_name); -Net_DNS2_Lookups::$rr_qtypes_by_id = array_flip(Net_DNS2_Lookups::$rr_qtypes_by_name); -Net_DNS2_Lookups::$rr_metatypes_by_id = array_flip(Net_DNS2_Lookups::$rr_metatypes_by_name); -Net_DNS2_Lookups::$protocol_by_id = array_flip(Net_DNS2_Lookups::$protocol_by_name); +Net_DNS2_Lookups::$digest_name_to_id = array_flip(Net_DNS2_Lookups::$digest_id_to_name); +Net_DNS2_Lookups::$rr_qtypes_by_id = array_flip(Net_DNS2_Lookups::$rr_qtypes_by_name); +Net_DNS2_Lookups::$rr_metatypes_by_id = array_flip(Net_DNS2_Lookups::$rr_metatypes_by_name); +Net_DNS2_Lookups::$protocol_by_id = array_flip(Net_DNS2_Lookups::$protocol_by_name); /** - * This class provides simple lookups used throughout the Net_DNS2 code - * + * This class provides simple lookups used throughout the Net_DNS2 code. */ class Net_DNS2_Lookups { - /* - * size (in bytes) of a header in a standard DNS packet - */ - const DNS_HEADER_SIZE = 12; - - /* - * max size of a UDP packet - */ - const DNS_MAX_UDP_SIZE = 512; - - /* - * Query/Response flag - */ - const QR_QUERY = 0; // RFC 1035 - const QR_RESPONSE = 1; // RFC 1035 - - /* - * DNS Op Codes - */ - const OPCODE_QUERY = 0; // RFC 1035 - const OPCODE_IQUERY = 1; // RFC 1035, RFC 3425 - const OPCODE_STATUS = 2; // RFC 1035 - const OPCODE_NOTIFY = 4; // RFC 1996 - const OPCODE_UPDATE = 5; // RFC 2136 - const OPCODE_DSO = 6; // RFC 8490 - - /* - * Resource Record Classes - */ - const RR_CLASS_IN = 1; // RFC 1035 - const RR_CLASS_CH = 3; // RFC 1035 - const RR_CLASS_HS = 4; // RFC 1035 - const RR_CLASS_NONE = 254; // RFC 2136 - const RR_CLASS_ANY = 255; // RFC 1035 - - /* - * DNS Response Codes - */ - const RCODE_NOERROR = 0; // RFC 1035 - const RCODE_FORMERR = 1; // RFC 1035 - const RCODE_SERVFAIL = 2; // RFC 1035 - const RCODE_NXDOMAIN = 3; // RFC 1035 - const RCODE_NOTIMP = 4; // RFC 1035 - const RCODE_REFUSED = 5; // RFC 1035 - const RCODE_YXDOMAIN = 6; // RFC 2136 - const RCODE_YXRRSET = 7; // RFC 2136 - const RCODE_NXRRSET = 8; // RFC 2136 - const RCODE_NOTAUTH = 9; // RFC 2136 - const RCODE_NOTZONE = 10; // RFC 2136 - const RCODE_DSOTYPENI = 11; // RFC 8490 + // size (in bytes) of a header in a standard DNS packet + public const DNS_HEADER_SIZE = 12; + + // max size of a UDP packet + public const DNS_MAX_UDP_SIZE = 512; + + // Query/Response flag + public const QR_QUERY = 0; // RFC 1035 + public const QR_RESPONSE = 1; // RFC 1035 + + // DNS Op Codes + public const OPCODE_QUERY = 0; // RFC 1035 + public const OPCODE_IQUERY = 1; // RFC 1035, RFC 3425 + public const OPCODE_STATUS = 2; // RFC 1035 + public const OPCODE_NOTIFY = 4; // RFC 1996 + public const OPCODE_UPDATE = 5; // RFC 2136 + public const OPCODE_DSO = 6; // RFC 8490 + + // Resource Record Classes + public const RR_CLASS_IN = 1; // RFC 1035 + public const RR_CLASS_CH = 3; // RFC 1035 + public const RR_CLASS_HS = 4; // RFC 1035 + public const RR_CLASS_NONE = 254; // RFC 2136 + public const RR_CLASS_ANY = 255; // RFC 1035 + + // DNS Response Codes + public const RCODE_NOERROR = 0; // RFC 1035 + public const RCODE_FORMERR = 1; // RFC 1035 + public const RCODE_SERVFAIL = 2; // RFC 1035 + public const RCODE_NXDOMAIN = 3; // RFC 1035 + public const RCODE_NOTIMP = 4; // RFC 1035 + public const RCODE_REFUSED = 5; // RFC 1035 + public const RCODE_YXDOMAIN = 6; // RFC 2136 + public const RCODE_YXRRSET = 7; // RFC 2136 + public const RCODE_NXRRSET = 8; // RFC 2136 + public const RCODE_NOTAUTH = 9; // RFC 2136 + public const RCODE_NOTZONE = 10; // RFC 2136 + public const RCODE_DSOTYPENI = 11; // RFC 8490 // 12-15 reserved - const RCODE_BADSIG = 16; // RFC 2845 - const RCODE_BADVERS = 16; // RFC 6891 - const RCODE_BADKEY = 17; // RFC 2845 - const RCODE_BADTIME = 18; // RFC 2845 - const RCODE_BADMODE = 19; // RFC 2930 - const RCODE_BADNAME = 20; // RFC 2930 - const RCODE_BADALG = 21; // RFC 2930 - const RCODE_BADTRUNC = 22; // RFC 4635 - const RCODE_BADCOOKIE = 23; // RFC 7873 - - /* - * internal errors codes returned by the exceptions class - */ - const E_NONE = 0; - const E_DNS_FORMERR = self::RCODE_FORMERR; - const E_DNS_SERVFAIL = self::RCODE_SERVFAIL; - const E_DNS_NXDOMAIN = self::RCODE_NXDOMAIN; - const E_DNS_NOTIMP = self::RCODE_NOTIMP; - const E_DNS_REFUSED = self::RCODE_REFUSED; - const E_DNS_YXDOMAIN = self::RCODE_YXDOMAIN; - const E_DNS_YXRRSET = self::RCODE_YXRRSET; - const E_DNS_NXRRSET = self::RCODE_NXRRSET; - const E_DNS_NOTAUTH = self::RCODE_NOTAUTH; - const E_DNS_NOTZONE = self::RCODE_NOTZONE; + public const RCODE_BADSIG = 16; // RFC 2845 + public const RCODE_BADVERS = 16; // RFC 6891 + public const RCODE_BADKEY = 17; // RFC 2845 + public const RCODE_BADTIME = 18; // RFC 2845 + public const RCODE_BADMODE = 19; // RFC 2930 + public const RCODE_BADNAME = 20; // RFC 2930 + public const RCODE_BADALG = 21; // RFC 2930 + public const RCODE_BADTRUNC = 22; // RFC 4635 + public const RCODE_BADCOOKIE = 23; // RFC 7873 + + // internal errors codes returned by the exceptions class + public const E_NONE = 0; + public const E_DNS_FORMERR = self::RCODE_FORMERR; + public const E_DNS_SERVFAIL = self::RCODE_SERVFAIL; + public const E_DNS_NXDOMAIN = self::RCODE_NXDOMAIN; + public const E_DNS_NOTIMP = self::RCODE_NOTIMP; + public const E_DNS_REFUSED = self::RCODE_REFUSED; + public const E_DNS_YXDOMAIN = self::RCODE_YXDOMAIN; + public const E_DNS_YXRRSET = self::RCODE_YXRRSET; + public const E_DNS_NXRRSET = self::RCODE_NXRRSET; + public const E_DNS_NOTAUTH = self::RCODE_NOTAUTH; + public const E_DNS_NOTZONE = self::RCODE_NOTZONE; // 11-15 reserved - const E_DNS_BADSIG = self::RCODE_BADSIG; - const E_DNS_BADKEY = self::RCODE_BADKEY; - const E_DNS_BADTIME = self::RCODE_BADTIME; - const E_DNS_BADMODE = self::RCODE_BADMODE; - const E_DNS_BADNAME = self::RCODE_BADNAME; - const E_DNS_BADALG = self::RCODE_BADALG; - const E_DNS_BADTRUNC = self::RCODE_BADTRUNC; - const E_DNS_BADCOOKIE = self::RCODE_BADCOOKIE; + public const E_DNS_BADSIG = self::RCODE_BADSIG; + public const E_DNS_BADKEY = self::RCODE_BADKEY; + public const E_DNS_BADTIME = self::RCODE_BADTIME; + public const E_DNS_BADMODE = self::RCODE_BADMODE; + public const E_DNS_BADNAME = self::RCODE_BADNAME; + public const E_DNS_BADALG = self::RCODE_BADALG; + public const E_DNS_BADTRUNC = self::RCODE_BADTRUNC; + public const E_DNS_BADCOOKIE = self::RCODE_BADCOOKIE; // other error conditions - const E_NS_INVALID_FILE = 200; - const E_NS_INVALID_ENTRY = 201; - const E_NS_FAILED = 202; - const E_NS_SOCKET_FAILED = 203; - const E_NS_INVALID_SOCKET = 204; - - const E_PACKET_INVALID = 300; - const E_PARSE_ERROR = 301; - const E_HEADER_INVALID = 302; - const E_QUESTION_INVALID = 303; - const E_RR_INVALID = 304; - - const E_OPENSSL_ERROR = 400; - const E_OPENSSL_UNAVAIL = 401; - const E_OPENSSL_INV_PKEY = 402; - const E_OPENSSL_INV_ALGO = 403; - - const E_CACHE_UNSUPPORTED = 500; - const E_CACHE_SHM_FILE = 501; - const E_CACHE_SHM_UNAVAIL = 502; - - /* - * EDNS0 Option Codes (OPT) - */ + public const E_NS_INVALID_FILE = 200; + public const E_NS_INVALID_ENTRY = 201; + public const E_NS_FAILED = 202; + public const E_NS_SOCKET_FAILED = 203; + public const E_NS_INVALID_SOCKET = 204; + + public const E_PACKET_INVALID = 300; + public const E_PARSE_ERROR = 301; + public const E_HEADER_INVALID = 302; + public const E_QUESTION_INVALID = 303; + public const E_RR_INVALID = 304; + + public const E_OPENSSL_ERROR = 400; + public const E_OPENSSL_UNAVAIL = 401; + public const E_OPENSSL_INV_PKEY = 402; + public const E_OPENSSL_INV_ALGO = 403; + + public const E_CACHE_UNSUPPORTED = 500; + public const E_CACHE_SHM_FILE = 501; + public const E_CACHE_SHM_UNAVAIL = 502; + + // EDNS0 Option Codes (OPT) // 0 - Reserved - const EDNS0_OPT_LLQ = 1; - const EDNS0_OPT_UL = 2; - const EDNS0_OPT_NSID = 3; + public const EDNS0_OPT_LLQ = 1; + public const EDNS0_OPT_UL = 2; + public const EDNS0_OPT_NSID = 3; // 4 - Reserved - const EDNS0_OPT_DAU = 5; - const EDNS0_OPT_DHU = 6; - const EDNS0_OPT_N3U = 7; - const EDNS0_OPT_CLIENT_SUBNET = 8; - const EDNS0_OPT_EXPIRE = 9; - const EDNS0_OPT_COOKIE = 10; - const EDNS0_OPT_TCP_KEEPALIVE = 11; - const EDNS0_OPT_PADDING = 12; - const EDNS0_OPT_CHAIN = 13; - const EDNS0_OPT_KEY_TAG = 14; + public const EDNS0_OPT_DAU = 5; + public const EDNS0_OPT_DHU = 6; + public const EDNS0_OPT_N3U = 7; + public const EDNS0_OPT_CLIENT_SUBNET = 8; + public const EDNS0_OPT_EXPIRE = 9; + public const EDNS0_OPT_COOKIE = 10; + public const EDNS0_OPT_TCP_KEEPALIVE = 11; + public const EDNS0_OPT_PADDING = 12; + public const EDNS0_OPT_CHAIN = 13; + public const EDNS0_OPT_KEY_TAG = 14; // 15 - unsassigned - const EDNS0_OPT_CLIENT_TAG = 16; - const EDNS0_OPT_SERVER_TAG = 17; + public const EDNS0_OPT_CLIENT_TAG = 16; + public const EDNS0_OPT_SERVER_TAG = 17; // 18-26945 - unassigned - const EDNS0_OPT_DEVICEID = 26946; - - /* - * DNSSEC Algorithms - */ - const DNSSEC_ALGORITHM_RES = 0; - const DNSSEC_ALGORITHM_RSAMD5 = 1; - const DNSSEC_ALGORITHM_DH = 2; - const DNSSEC_ALGORITHM_DSA = 3; - const DNSSEC_ALGORITHM_ECC = 4; - const DNSSEC_ALGORITHM_RSASHA1 = 5; - const DNSSEC_ALGORITHM_DSANSEC3SHA1 = 6; - const DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 = 7; - const DNSSEC_ALGORITHM_RSASHA256 = 8; - const DNSSEC_ALGORITHM_RSASHA512 = 10; - const DNSSEC_ALGORITHM_ECCGOST = 12; - const DNSSEC_ALGORITHM_ECDSAP256SHA256 = 13; - const DNSSEC_ALGORITHM_ECDSAP384SHA384 = 14; - const DNSSEC_ALGORITHM_ED25519 = 15; - const DNSSEC_ALGORITHM_ED448 = 16; - const DNSSEC_ALGORITHM_INDIRECT = 252; - const DNSSEC_ALGORITHM_PRIVATEDNS = 253; - const DNSSEC_ALGORITHM_PRIVATEOID = 254; - - /* - * DNSSEC Digest Types - */ - const DNSSEC_DIGEST_RES = 0; - const DNSSEC_DIGEST_SHA1 = 1; - const DNSSEC_DIGEST_SHA256 = 2; - const DNSSEC_DIGEST_GOST = 3; - const DNSSEC_DIGEST_SHA384 = 4; - - /* - * The packet id used when sending requests - */ + public const EDNS0_OPT_DEVICEID = 26946; + + // DNSSEC Algorithms + public const DNSSEC_ALGORITHM_RES = 0; + public const DNSSEC_ALGORITHM_RSAMD5 = 1; + public const DNSSEC_ALGORITHM_DH = 2; + public const DNSSEC_ALGORITHM_DSA = 3; + public const DNSSEC_ALGORITHM_ECC = 4; + public const DNSSEC_ALGORITHM_RSASHA1 = 5; + public const DNSSEC_ALGORITHM_DSANSEC3SHA1 = 6; + public const DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 = 7; + public const DNSSEC_ALGORITHM_RSASHA256 = 8; + public const DNSSEC_ALGORITHM_RSASHA512 = 10; + public const DNSSEC_ALGORITHM_ECCGOST = 12; + public const DNSSEC_ALGORITHM_ECDSAP256SHA256 = 13; + public const DNSSEC_ALGORITHM_ECDSAP384SHA384 = 14; + public const DNSSEC_ALGORITHM_ED25519 = 15; + public const DNSSEC_ALGORITHM_ED448 = 16; + public const DNSSEC_ALGORITHM_INDIRECT = 252; + public const DNSSEC_ALGORITHM_PRIVATEDNS = 253; + public const DNSSEC_ALGORITHM_PRIVATEOID = 254; + + // DNSSEC Digest Types + public const DNSSEC_DIGEST_RES = 0; + public const DNSSEC_DIGEST_SHA1 = 1; + public const DNSSEC_DIGEST_SHA256 = 2; + public const DNSSEC_DIGEST_GOST = 3; + public const DNSSEC_DIGEST_SHA384 = 4; + + // The packet id used when sending requests public static $next_packet_id; - /* - * Used to map resource record types to their id's, and back - */ - public static $rr_types_by_id = []; + // Used to map resource record types to their id's, and back + public static $rr_types_by_id = []; public static $rr_types_by_name = [ - - 'SIG0' => 0, // RFC 2931 pseudo type - 'A' => 1, // RFC 1035 - 'NS' => 2, // RFC 1035 - 'MD' => 3, // RFC 1035 - obsolete, Not implemented - 'MF' => 4, // RFC 1035 - obsolete, Not implemented - 'CNAME' => 5, // RFC 1035 - 'SOA' => 6, // RFC 1035 - 'MB' => 7, // RFC 1035 - obsolete, Not implemented - 'MG' => 8, // RFC 1035 - obsolete, Not implemented - 'MR' => 9, // RFC 1035 - obsolete, Not implemented - 'NULL' => 10, // RFC 1035 - obsolete, Not implemented - 'WKS' => 11, // RFC 1035 - 'PTR' => 12, // RFC 1035 - 'HINFO' => 13, // RFC 1035 - 'MINFO' => 14, // RFC 1035 - obsolete, Not implemented - 'MX' => 15, // RFC 1035 - 'TXT' => 16, // RFC 1035 - 'RP' => 17, // RFC 1183 - 'AFSDB' => 18, // RFC 1183 - 'X25' => 19, // RFC 1183 - 'ISDN' => 20, // RFC 1183 - 'RT' => 21, // RFC 1183 - 'NSAP' => 22, // RFC 1706 - 'NSAP_PTR' => 23, // RFC 1348 - obsolete, Not implemented - 'SIG' => 24, // RFC 2535 - 'KEY' => 25, // RFC 2535, RFC 2930 - 'PX' => 26, // RFC 2163 - 'GPOS' => 27, // RFC 1712 - Not implemented - 'AAAA' => 28, // RFC 3596 - 'LOC' => 29, // RFC 1876 - 'NXT' => 30, // RFC 2065, obsoleted by by RFC 3755 - 'EID' => 31, // [Patton][Patton1995] - 'NIMLOC' => 32, // [Patton][Patton1995] - 'SRV' => 33, // RFC 2782 - 'ATMA' => 34, // Windows only - 'NAPTR' => 35, // RFC 2915 - 'KX' => 36, // RFC 2230 - 'CERT' => 37, // RFC 4398 - 'A6' => 38, // downgraded to experimental by RFC 3363 - 'DNAME' => 39, // RFC 2672 - 'SINK' => 40, // Not implemented - 'OPT' => 41, // RFC 2671 - 'APL' => 42, // RFC 3123 - 'DS' => 43, // RFC 4034 - 'SSHFP' => 44, // RFC 4255 - 'IPSECKEY' => 45, // RFC 4025 - 'RRSIG' => 46, // RFC 4034 - 'NSEC' => 47, // RFC 4034 - 'DNSKEY' => 48, // RFC 4034 - 'DHCID' => 49, // RFC 4701 - 'NSEC3' => 50, // RFC 5155 - 'NSEC3PARAM' => 51, // RFC 5155 - 'TLSA' => 52, // RFC 6698 - 'SMIMEA' => 53, // RFC 8162 - - // 54 unassigned - - 'HIP' => 55, // RFC 5205 - 'NINFO' => 56, // Not implemented - 'RKEY' => 57, // Not implemented - 'TALINK' => 58, // - 'CDS' => 59, // RFC 7344 - 'CDNSKEY' => 60, // RFC 7344 - 'OPENPGPKEY' => 61, // RFC 7929 - 'CSYNC' => 62, // RFC 7477 - 'ZONEMD' => 63, // Not implemented yet - 'SVCB' => 64, // Not implemented yet - 'HTTPS' => 65, // Not implemented yet - - // 66 - 98 unassigned - - 'SPF' => 99, // RFC 4408 - 'UINFO' => 100, // no RFC, Not implemented - 'UID' => 101, // no RFC, Not implemented - 'GID' => 102, // no RFC, Not implemented - 'UNSPEC' => 103, // no RFC, Not implemented - 'NID' => 104, // RFC 6742 - 'L32' => 105, // RFC 6742 - 'L64' => 106, // RFC 6742 - 'LP' => 107, // RFC 6742 - 'EUI48' => 108, // RFC 7043 - 'EUI64' => 109, // RFC 7043 - - // 110 - 248 unassigned - - 'TKEY' => 249, // RFC 2930 - 'TSIG' => 250, // RFC 2845 - 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported - 'AXFR' => 252, // RFC 1035 - 'MAILB' => 253, // RFC 883, Not implemented - 'MAILA' => 254, // RFC 973, Not implemented - 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' - 'URI' => 256, // RFC 7553 - 'CAA' => 257, // RFC 8659 - 'AVC' => 258, // Application Visibility and Control - 'DOA' => 259, // Not implemented yet - 'AMTRELAY' => 260, // RFC 8777 - - // 261 - 32767 unassigned - - 'TA' => 32768, // same as DS - 'DLV' => 32769, // RFC 4431 - 'TYPE65534' => 65534 // Private Bind record + 'SIG0' => 0, // RFC 2931 pseudo type + 'A' => 1, // RFC 1035 + 'NS' => 2, // RFC 1035 + 'MD' => 3, // RFC 1035 - obsolete, Not implemented + 'MF' => 4, // RFC 1035 - obsolete, Not implemented + 'CNAME' => 5, // RFC 1035 + 'SOA' => 6, // RFC 1035 + 'MB' => 7, // RFC 1035 - obsolete, Not implemented + 'MG' => 8, // RFC 1035 - obsolete, Not implemented + 'MR' => 9, // RFC 1035 - obsolete, Not implemented + 'NULL' => 10, // RFC 1035 - obsolete, Not implemented + 'WKS' => 11, // RFC 1035 + 'PTR' => 12, // RFC 1035 + 'HINFO' => 13, // RFC 1035 + 'MINFO' => 14, // RFC 1035 - obsolete, Not implemented + 'MX' => 15, // RFC 1035 + 'TXT' => 16, // RFC 1035 + 'RP' => 17, // RFC 1183 + 'AFSDB' => 18, // RFC 1183 + 'X25' => 19, // RFC 1183 + 'ISDN' => 20, // RFC 1183 + 'RT' => 21, // RFC 1183 + 'NSAP' => 22, // RFC 1706 + 'NSAP_PTR' => 23, // RFC 1348 - obsolete, Not implemented + 'SIG' => 24, // RFC 2535 + 'KEY' => 25, // RFC 2535, RFC 2930 + 'PX' => 26, // RFC 2163 + 'GPOS' => 27, // RFC 1712 - Not implemented + 'AAAA' => 28, // RFC 3596 + 'LOC' => 29, // RFC 1876 + 'NXT' => 30, // RFC 2065, obsoleted by by RFC 3755 + 'EID' => 31, // [Patton][Patton1995] + 'NIMLOC' => 32, // [Patton][Patton1995] + 'SRV' => 33, // RFC 2782 + 'ATMA' => 34, // Windows only + 'NAPTR' => 35, // RFC 2915 + 'KX' => 36, // RFC 2230 + 'CERT' => 37, // RFC 4398 + 'A6' => 38, // downgraded to experimental by RFC 3363 + 'DNAME' => 39, // RFC 2672 + 'SINK' => 40, // Not implemented + 'OPT' => 41, // RFC 2671 + 'APL' => 42, // RFC 3123 + 'DS' => 43, // RFC 4034 + 'SSHFP' => 44, // RFC 4255 + 'IPSECKEY' => 45, // RFC 4025 + 'RRSIG' => 46, // RFC 4034 + 'NSEC' => 47, // RFC 4034 + 'DNSKEY' => 48, // RFC 4034 + 'DHCID' => 49, // RFC 4701 + 'NSEC3' => 50, // RFC 5155 + 'NSEC3PARAM' => 51, // RFC 5155 + 'TLSA' => 52, // RFC 6698 + 'SMIMEA' => 53, // RFC 8162 + + // 54 unassigned + + 'HIP' => 55, // RFC 5205 + 'NINFO' => 56, // Not implemented + 'RKEY' => 57, // Not implemented + 'TALINK' => 58, + 'CDS' => 59, // RFC 7344 + 'CDNSKEY' => 60, // RFC 7344 + 'OPENPGPKEY' => 61, // RFC 7929 + 'CSYNC' => 62, // RFC 7477 + 'ZONEMD' => 63, // Not implemented yet + 'SVCB' => 64, // Not implemented yet + 'HTTPS' => 65, // Not implemented yet + + // 66 - 98 unassigned + + 'SPF' => 99, // RFC 4408 + 'UINFO' => 100, // no RFC, Not implemented + 'UID' => 101, // no RFC, Not implemented + 'GID' => 102, // no RFC, Not implemented + 'UNSPEC' => 103, // no RFC, Not implemented + 'NID' => 104, // RFC 6742 + 'L32' => 105, // RFC 6742 + 'L64' => 106, // RFC 6742 + 'LP' => 107, // RFC 6742 + 'EUI48' => 108, // RFC 7043 + 'EUI64' => 109, // RFC 7043 + + // 110 - 248 unassigned + + 'TKEY' => 249, // RFC 2930 + 'TSIG' => 250, // RFC 2845 + 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported + 'AXFR' => 252, // RFC 1035 + 'MAILB' => 253, // RFC 883, Not implemented + 'MAILA' => 254, // RFC 973, Not implemented + 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' + 'URI' => 256, // RFC 7553 + 'CAA' => 257, // RFC 8659 + 'AVC' => 258, // Application Visibility and Control + 'DOA' => 259, // Not implemented yet + 'AMTRELAY' => 260, // RFC 8777 + + // 261 - 32767 unassigned + + 'TA' => 32768, // same as DS + 'DLV' => 32769, // RFC 4431 + 'TYPE65534' => 65534, // Private Bind record ]; - /* - * Qtypes and Metatypes - defined in RFC2929 section 3.1 - */ - public static $rr_qtypes_by_id = []; - public static $rr_qtypes_by_name = [ - - 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported - 'AXFR' => 252, // RFC 1035 - 'MAILB' => 253, // RFC 883, Not implemented - 'MAILA' => 254, // RFC 973, Not implemented - 'ANY' => 255 // RFC 1035 - we support both 'ANY' and '*' + // Qtypes and Metatypes - defined in RFC2929 section 3.1 + public static $rr_qtypes_by_id = []; + public static $rr_qtypes_by_name = [ + 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported + 'AXFR' => 252, // RFC 1035 + 'MAILB' => 253, // RFC 883, Not implemented + 'MAILA' => 254, // RFC 973, Not implemented + 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' ]; - - public static $rr_metatypes_by_id = []; - public static $rr_metatypes_by_name = [ - 'OPT' => 41, // RFC 2671 - 'TKEY' => 249, // RFC 2930 - 'TSIG' => 250 // RFC 2845 + public static $rr_metatypes_by_id = []; + public static $rr_metatypes_by_name = [ + 'OPT' => 41, // RFC 2671 + 'TKEY' => 249, // RFC 2930 + 'TSIG' => 250, // RFC 2845 ]; - /* - * used to map resource record id's to RR class names - */ + // used to map resource record id's to RR class names public static $rr_types_class_to_id = []; public static $rr_types_id_to_class = [ - - 1 => 'Net_DNS2_RR_A', - 2 => 'Net_DNS2_RR_NS', - 5 => 'Net_DNS2_RR_CNAME', - 6 => 'Net_DNS2_RR_SOA', - 11 => 'Net_DNS2_RR_WKS', - 12 => 'Net_DNS2_RR_PTR', - 13 => 'Net_DNS2_RR_HINFO', - 15 => 'Net_DNS2_RR_MX', - 16 => 'Net_DNS2_RR_TXT', - 17 => 'Net_DNS2_RR_RP', - 18 => 'Net_DNS2_RR_AFSDB', - 19 => 'Net_DNS2_RR_X25', - 20 => 'Net_DNS2_RR_ISDN', - 21 => 'Net_DNS2_RR_RT', - 22 => 'Net_DNS2_RR_NSAP', - 24 => 'Net_DNS2_RR_SIG', - 25 => 'Net_DNS2_RR_KEY', - 26 => 'Net_DNS2_RR_PX', - 28 => 'Net_DNS2_RR_AAAA', - 29 => 'Net_DNS2_RR_LOC', - 31 => 'Net_DNS2_RR_EID', - 32 => 'Net_DNS2_RR_NIMLOC', - 33 => 'Net_DNS2_RR_SRV', - 34 => 'Net_DNS2_RR_ATMA', - 35 => 'Net_DNS2_RR_NAPTR', - 36 => 'Net_DNS2_RR_KX', - 37 => 'Net_DNS2_RR_CERT', - 39 => 'Net_DNS2_RR_DNAME', - 41 => 'Net_DNS2_RR_OPT', - 42 => 'Net_DNS2_RR_APL', - 43 => 'Net_DNS2_RR_DS', - 44 => 'Net_DNS2_RR_SSHFP', - 45 => 'Net_DNS2_RR_IPSECKEY', - 46 => 'Net_DNS2_RR_RRSIG', - 47 => 'Net_DNS2_RR_NSEC', - 48 => 'Net_DNS2_RR_DNSKEY', - 49 => 'Net_DNS2_RR_DHCID', - 50 => 'Net_DNS2_RR_NSEC3', - 51 => 'Net_DNS2_RR_NSEC3PARAM', - 52 => 'Net_DNS2_RR_TLSA', - 53 => 'Net_DNS2_RR_SMIMEA', - 55 => 'Net_DNS2_RR_HIP', - 58 => 'Net_DNS2_RR_TALINK', - 59 => 'Net_DNS2_RR_CDS', - 60 => 'Net_DNS2_RR_CDNSKEY', - 61 => 'Net_DNS2_RR_OPENPGPKEY', - 62 => 'Net_DNS2_RR_CSYNC', - 99 => 'Net_DNS2_RR_SPF', - 104 => 'Net_DNS2_RR_NID', - 105 => 'Net_DNS2_RR_L32', - 106 => 'Net_DNS2_RR_L64', - 107 => 'Net_DNS2_RR_LP', - 108 => 'Net_DNS2_RR_EUI48', - 109 => 'Net_DNS2_RR_EUI64', - - 249 => 'Net_DNS2_RR_TKEY', - 250 => 'Net_DNS2_RR_TSIG', - - // 251 - IXFR - handled as a full zone transfer (252) - // 252 - AXFR - handled as a function call - - 255 => 'Net_DNS2_RR_ANY', - 256 => 'Net_DNS2_RR_URI', - 257 => 'Net_DNS2_RR_CAA', - 258 => 'Net_DNS2_RR_AVC', - 260 => 'Net_DNS2_RR_AMTRELAY', - 32768 => 'Net_DNS2_RR_TA', - 32769 => 'Net_DNS2_RR_DLV', - 65534 => 'Net_DNS2_RR_TYPE65534' + 1 => 'Net_DNS2_RR_A', + 2 => 'Net_DNS2_RR_NS', + 5 => 'Net_DNS2_RR_CNAME', + 6 => 'Net_DNS2_RR_SOA', + 11 => 'Net_DNS2_RR_WKS', + 12 => 'Net_DNS2_RR_PTR', + 13 => 'Net_DNS2_RR_HINFO', + 15 => 'Net_DNS2_RR_MX', + 16 => 'Net_DNS2_RR_TXT', + 17 => 'Net_DNS2_RR_RP', + 18 => 'Net_DNS2_RR_AFSDB', + 19 => 'Net_DNS2_RR_X25', + 20 => 'Net_DNS2_RR_ISDN', + 21 => 'Net_DNS2_RR_RT', + 22 => 'Net_DNS2_RR_NSAP', + 24 => 'Net_DNS2_RR_SIG', + 25 => 'Net_DNS2_RR_KEY', + 26 => 'Net_DNS2_RR_PX', + 28 => 'Net_DNS2_RR_AAAA', + 29 => 'Net_DNS2_RR_LOC', + 31 => 'Net_DNS2_RR_EID', + 32 => 'Net_DNS2_RR_NIMLOC', + 33 => 'Net_DNS2_RR_SRV', + 34 => 'Net_DNS2_RR_ATMA', + 35 => 'Net_DNS2_RR_NAPTR', + 36 => 'Net_DNS2_RR_KX', + 37 => 'Net_DNS2_RR_CERT', + 39 => 'Net_DNS2_RR_DNAME', + 41 => 'Net_DNS2_RR_OPT', + 42 => 'Net_DNS2_RR_APL', + 43 => 'Net_DNS2_RR_DS', + 44 => 'Net_DNS2_RR_SSHFP', + 45 => 'Net_DNS2_RR_IPSECKEY', + 46 => 'Net_DNS2_RR_RRSIG', + 47 => 'Net_DNS2_RR_NSEC', + 48 => 'Net_DNS2_RR_DNSKEY', + 49 => 'Net_DNS2_RR_DHCID', + 50 => 'Net_DNS2_RR_NSEC3', + 51 => 'Net_DNS2_RR_NSEC3PARAM', + 52 => 'Net_DNS2_RR_TLSA', + 53 => 'Net_DNS2_RR_SMIMEA', + 55 => 'Net_DNS2_RR_HIP', + 58 => 'Net_DNS2_RR_TALINK', + 59 => 'Net_DNS2_RR_CDS', + 60 => 'Net_DNS2_RR_CDNSKEY', + 61 => 'Net_DNS2_RR_OPENPGPKEY', + 62 => 'Net_DNS2_RR_CSYNC', + 99 => 'Net_DNS2_RR_SPF', + 104 => 'Net_DNS2_RR_NID', + 105 => 'Net_DNS2_RR_L32', + 106 => 'Net_DNS2_RR_L64', + 107 => 'Net_DNS2_RR_LP', + 108 => 'Net_DNS2_RR_EUI48', + 109 => 'Net_DNS2_RR_EUI64', + + 249 => 'Net_DNS2_RR_TKEY', + 250 => 'Net_DNS2_RR_TSIG', + + // 251 - IXFR - handled as a full zone transfer (252) + // 252 - AXFR - handled as a function call + + 255 => 'Net_DNS2_RR_ANY', + 256 => 'Net_DNS2_RR_URI', + 257 => 'Net_DNS2_RR_CAA', + 258 => 'Net_DNS2_RR_AVC', + 260 => 'Net_DNS2_RR_AMTRELAY', + 32768 => 'Net_DNS2_RR_TA', + 32769 => 'Net_DNS2_RR_DLV', + 65534 => 'Net_DNS2_RR_TYPE65534', ]; - /* - * used to map resource record class names to their id's, and back - */ - public static $classes_by_id = []; - public static $classes_by_name = [ - - 'IN' => self::RR_CLASS_IN, // RFC 1035 - 'CH' => self::RR_CLASS_CH, // RFC 1035 - 'HS' => self::RR_CLASS_HS, // RFC 1035 - 'NONE' => self::RR_CLASS_NONE, // RFC 2136 - 'ANY' => self::RR_CLASS_ANY // RFC 1035 + // used to map resource record class names to their id's, and back + public static $classes_by_id = []; + public static $classes_by_name = [ + 'IN' => self::RR_CLASS_IN, // RFC 1035 + 'CH' => self::RR_CLASS_CH, // RFC 1035 + 'HS' => self::RR_CLASS_HS, // RFC 1035 + 'NONE' => self::RR_CLASS_NONE, // RFC 2136 + 'ANY' => self::RR_CLASS_ANY, // RFC 1035 ]; - /* - * maps response codes to error messages - */ + // maps response codes to error messages public static $result_code_messages = [ - - self::RCODE_NOERROR => 'The request completed successfully.', - self::RCODE_FORMERR => 'The name server was unable to interpret the query.', - self::RCODE_SERVFAIL => 'The name server was unable to process this query due to a problem with the name server.', - self::RCODE_NXDOMAIN => 'The domain name referenced in the query does not exist.', - self::RCODE_NOTIMP => 'The name server does not support the requested kind of query.', - self::RCODE_REFUSED => 'The name server refuses to perform the specified operation for policy reasons.', - self::RCODE_YXDOMAIN => 'Name Exists when it should not.', - self::RCODE_YXRRSET => 'RR Set Exists when it should not.', - self::RCODE_NXRRSET => 'RR Set that should exist does not.', - self::RCODE_NOTAUTH => 'Server Not Authoritative for zone.', - self::RCODE_NOTZONE => 'Name not contained in zone.', - - self::RCODE_BADSIG => 'TSIG Signature Failure.', - self::RCODE_BADKEY => 'Key not recognized.', - self::RCODE_BADTIME => 'Signature out of time window.', - self::RCODE_BADMODE => 'Bad TKEY Mode.', - self::RCODE_BADNAME => 'Duplicate key name.', - self::RCODE_BADALG => 'Algorithm not supported.', - self::RCODE_BADTRUNC => 'Bad truncation.' + self::RCODE_NOERROR => 'The request completed successfully.', + self::RCODE_FORMERR => 'The name server was unable to interpret the query.', + self::RCODE_SERVFAIL => 'The name server was unable to process this query due to a problem with the name server.', + self::RCODE_NXDOMAIN => 'The domain name referenced in the query does not exist.', + self::RCODE_NOTIMP => 'The name server does not support the requested kind of query.', + self::RCODE_REFUSED => 'The name server refuses to perform the specified operation for policy reasons.', + self::RCODE_YXDOMAIN => 'Name Exists when it should not.', + self::RCODE_YXRRSET => 'RR Set Exists when it should not.', + self::RCODE_NXRRSET => 'RR Set that should exist does not.', + self::RCODE_NOTAUTH => 'Server Not Authoritative for zone.', + self::RCODE_NOTZONE => 'Name not contained in zone.', + + self::RCODE_BADSIG => 'TSIG Signature Failure.', + self::RCODE_BADKEY => 'Key not recognized.', + self::RCODE_BADTIME => 'Signature out of time window.', + self::RCODE_BADMODE => 'Bad TKEY Mode.', + self::RCODE_BADNAME => 'Duplicate key name.', + self::RCODE_BADALG => 'Algorithm not supported.', + self::RCODE_BADTRUNC => 'Bad truncation.', ]; - /* - * maps DNS SEC alrorithms to their mnemonics - */ + // maps DNS SEC alrorithms to their mnemonics public static $algorithm_name_to_id = []; public static $algorithm_id_to_name = [ - - self::DNSSEC_ALGORITHM_RES => 'RES', - self::DNSSEC_ALGORITHM_RSAMD5 => 'RSAMD5', - self::DNSSEC_ALGORITHM_DH => 'DH', - self::DNSSEC_ALGORITHM_DSA => 'DSA', - self::DNSSEC_ALGORITHM_ECC => 'ECC', - self::DNSSEC_ALGORITHM_RSASHA1 => 'RSASHA1', - self::DNSSEC_ALGORITHM_DSANSEC3SHA1 => 'DSA-NSEC3-SHA1', - self::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 => 'RSASHA1-NSEC3-SHA1', - self::DNSSEC_ALGORITHM_RSASHA256 => 'RSASHA256', - self::DNSSEC_ALGORITHM_RSASHA512 => 'RSASHA512', - self::DNSSEC_ALGORITHM_ECCGOST => 'ECC-GOST', - self::DNSSEC_ALGORITHM_ECDSAP256SHA256 => 'ECDSAP256SHA256', - self::DNSSEC_ALGORITHM_ECDSAP384SHA384 => 'ECDSAP384SHA384', - self::DNSSEC_ALGORITHM_ED25519 => 'ED25519', - self::DNSSEC_ALGORITHM_ED448 => 'ED448', - self::DNSSEC_ALGORITHM_INDIRECT => 'INDIRECT', - self::DNSSEC_ALGORITHM_PRIVATEDNS => 'PRIVATEDNS', - self::DNSSEC_ALGORITHM_PRIVATEOID => 'PRIVATEOID' + self::DNSSEC_ALGORITHM_RES => 'RES', + self::DNSSEC_ALGORITHM_RSAMD5 => 'RSAMD5', + self::DNSSEC_ALGORITHM_DH => 'DH', + self::DNSSEC_ALGORITHM_DSA => 'DSA', + self::DNSSEC_ALGORITHM_ECC => 'ECC', + self::DNSSEC_ALGORITHM_RSASHA1 => 'RSASHA1', + self::DNSSEC_ALGORITHM_DSANSEC3SHA1 => 'DSA-NSEC3-SHA1', + self::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 => 'RSASHA1-NSEC3-SHA1', + self::DNSSEC_ALGORITHM_RSASHA256 => 'RSASHA256', + self::DNSSEC_ALGORITHM_RSASHA512 => 'RSASHA512', + self::DNSSEC_ALGORITHM_ECCGOST => 'ECC-GOST', + self::DNSSEC_ALGORITHM_ECDSAP256SHA256 => 'ECDSAP256SHA256', + self::DNSSEC_ALGORITHM_ECDSAP384SHA384 => 'ECDSAP384SHA384', + self::DNSSEC_ALGORITHM_ED25519 => 'ED25519', + self::DNSSEC_ALGORITHM_ED448 => 'ED448', + self::DNSSEC_ALGORITHM_INDIRECT => 'INDIRECT', + self::DNSSEC_ALGORITHM_PRIVATEDNS => 'PRIVATEDNS', + self::DNSSEC_ALGORITHM_PRIVATEOID => 'PRIVATEOID', ]; - /* - * maps DNSSEC digest types to their mnemonics - */ + // maps DNSSEC digest types to their mnemonics public static $digest_name_to_id = []; public static $digest_id_to_name = [ - - self::DNSSEC_DIGEST_RES => 'RES', - self::DNSSEC_DIGEST_SHA1 => 'SHA-1', - self::DNSSEC_DIGEST_SHA256 => 'SHA-256', - self::DNSSEC_DIGEST_GOST => 'GOST-R-34.11-94', - self::DNSSEC_DIGEST_SHA384 => 'SHA-384' + self::DNSSEC_DIGEST_RES => 'RES', + self::DNSSEC_DIGEST_SHA1 => 'SHA-1', + self::DNSSEC_DIGEST_SHA256 => 'SHA-256', + self::DNSSEC_DIGEST_GOST => 'GOST-R-34.11-94', + self::DNSSEC_DIGEST_SHA384 => 'SHA-384', ]; - /* - * Protocols names - RFC 1010 - */ - public static $protocol_by_id = []; + // Protocols names - RFC 1010 + public static $protocol_by_id = []; public static $protocol_by_name = [ - - 'ICMP' => 1, - 'IGMP' => 2, - 'GGP' => 3, - 'ST' => 5, - 'TCP' => 6, - 'UCL' => 7, - 'EGP' => 8, - 'IGP' => 9, - 'BBN-RCC-MON' => 10, - 'NVP-II' => 11, - 'PUP' => 12, - 'ARGUS' => 13, - 'EMCON' => 14, - 'XNET' => 15, - 'CHAOS' => 16, - 'UDP' => 17, - 'MUX' => 18, - 'DCN-MEAS' => 19, - 'HMP' => 20, - 'PRM' => 21, - 'XNS-IDP' => 22, - 'TRUNK-1' => 23, - 'TRUNK-2' => 24, - 'LEAF-1' => 25, - 'LEAF-2' => 26, - 'RDP' => 27, - 'IRTP' => 28, - 'ISO-TP4' => 29, - 'NETBLT' => 30, - 'MFE-NSP' => 31, - 'MERIT-INP' => 32, - 'SEP' => 33, + 'ICMP' => 1, + 'IGMP' => 2, + 'GGP' => 3, + 'ST' => 5, + 'TCP' => 6, + 'UCL' => 7, + 'EGP' => 8, + 'IGP' => 9, + 'BBN-RCC-MON' => 10, + 'NVP-II' => 11, + 'PUP' => 12, + 'ARGUS' => 13, + 'EMCON' => 14, + 'XNET' => 15, + 'CHAOS' => 16, + 'UDP' => 17, + 'MUX' => 18, + 'DCN-MEAS' => 19, + 'HMP' => 20, + 'PRM' => 21, + 'XNS-IDP' => 22, + 'TRUNK-1' => 23, + 'TRUNK-2' => 24, + 'LEAF-1' => 25, + 'LEAF-2' => 26, + 'RDP' => 27, + 'IRTP' => 28, + 'ISO-TP4' => 29, + 'NETBLT' => 30, + 'MFE-NSP' => 31, + 'MERIT-INP' => 32, + 'SEP' => 33, // 34 - 60 - Unassigned // 61 - any host internal protocol - 'CFTP' => 62, + 'CFTP' => 62, // 63 - any local network - 'SAT-EXPAK' => 64, - 'MIT-SUBNET' => 65, - 'RVD' => 66, - 'IPPC' => 67, + 'SAT-EXPAK' => 64, + 'MIT-SUBNET' => 65, + 'RVD' => 66, + 'IPPC' => 67, // 68 - any distributed file system - 'SAT-MON' => 69, + 'SAT-MON' => 69, // 70 - Unassigned - 'IPCV' => 71, + 'IPCV' => 71, // 72 - 75 - Unassigned - 'BR-SAT-MON' => 76, + 'BR-SAT-MON' => 76, // 77 - Unassigned - 'WB-MON' => 78, - 'WB-EXPAK' => 79 + 'WB-MON' => 78, + 'WB-EXPAK' => 79, // 80 - 254 - Unassigned // 255 - Reserved ]; diff --git a/Net/DNS2/Notifier.php b/Net/DNS2/Notifier.php index e8dc2dbc..4cedc885 100644 --- a/Net/DNS2/Notifier.php +++ b/Net/DNS2/Notifier.php @@ -8,13 +8,13 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** @@ -27,194 +27,186 @@ * * Generally, query (recursive) lookups are done against caching server, while * notify requests are done against authoritative servers. - * */ class Net_DNS2_Notifier extends Net_DNS2 { - /* - * a Net_DNS2_Packet_Request object used for the notify request - */ - private $_packet; - - /** - * Constructor - builds a new Net_DNS2_Notifier objected used for doing - * DNS notification for a changed zone - * - * @param string $zone the domain name to use for DNS updates - * @param mixed $options an array of config options or null - * - * @throws Net_DNS2_Exception - * @access public - * - */ - public function __construct($zone, array $options = null) - { - parent::__construct($options); - - // - // create the packet - // - $this->_packet = new Net_DNS2_Packet_Request( - strtolower(trim($zone, " \n\r\t.")), 'SOA', 'IN' - ); - - // - // make sure the opcode on the packet is set to NOTIFY - // - $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_NOTIFY; - } - - /** - * checks that the given name matches the name for the zone we're notifying - * - * @param string $name The name to be checked. - * - * @return boolean - * @throws Net_DNS2_Exception - * @access private - * - */ - private function _checkName($name) - { - if (!preg_match('/' . $this->_packet->question[0]->qname . '$/', $name)) { - - throw new Net_DNS2_Exception( - 'name provided (' . $name . ') does not match zone name (' . - $this->_packet->question[0]->qname . ')', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - return true; - } - - /** - * 3.7 - Add RR to notify - * - * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be sent in the notify message - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function add(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - // - // add the RR to the "notify" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - return true; - } - - /** - * add a signature to the request for authentication - * - * @param string $keyname the key name to use for the TSIG RR - * @param string $signature the key to sign the request. - * - * @return boolean - * @access public - * @see Net_DNS2::signTSIG() - * @deprecated function deprecated in 1.1.0 - * - */ - public function signature($keyname, $signature, $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5) - { - return $this->signTSIG($keyname, $signature, $algorithm); - } - - /** - * returns the current internal packet object. - * - * @return Net_DNS2_Packet_Request - * @access public - # - */ - public function packet() - { - // - // take a copy - // - $p = $this->_packet; - - // - // check for an authentication method; either TSIG or SIG - // - if ( ($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $p->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $p->header->qdcount = cacti_sizeof($p->question); - $p->header->ancount = cacti_sizeof($p->answer); - $p->header->nscount = cacti_sizeof($p->authority); - $p->header->arcount = cacti_sizeof($p->additional); - - return $p; - } - - /** - * executes the notify request - * - * @param Net_DNS2_Packet_Response &$response ref to the response object - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function notify(&$response = null) - { - // - // check for an authentication method; either TSIG or SIG - // - if ( ($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $this->_packet->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); - $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); - $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); - $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); - - // - // make sure we have some data to send - // - if ($this->_packet->header->qdcount == 0) { - throw new Net_DNS2_Exception( - 'empty headers- nothing to send!', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - // - // send the packet and get back the response - // - $response = $this->sendPacket($this->_packet, $this->use_tcp); - - // - // clear the internal packet so if we make another request, we don't have - // old data being sent. - // - $this->_packet->reset(); - - // - // for notifies, we just need to know it worked- we don't actually need to - // return the response object - // - return true; - } + // a Net_DNS2_Packet_Request object used for the notify request + private $_packet; + + /** + * Constructor - builds a new Net_DNS2_Notifier objected used for doing + * DNS notification for a changed zone. + * + * @param string $zone the domain name to use for DNS updates + * @param mixed $options an array of config options or null + * + * @throws Net_DNS2_Exception + */ + public function __construct($zone, ?array $options = null) + { + parent::__construct($options); + + // + // create the packet + // + $this->_packet = new Net_DNS2_Packet_Request( + strtolower(trim($zone, " \n\r\t.")), + 'SOA', + 'IN' + ); + + // + // make sure the opcode on the packet is set to NOTIFY + // + $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_NOTIFY; + } + + /** + * 3.7 - Add RR to notify. + * + * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be sent in the notify message + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function add(Net_DNS2_RR $rr) + { + $this->_checkName($rr->name); + // + // add the RR to the "notify" section + // + if (!in_array($rr, $this->_packet->answer)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * add a signature to the request for authentication. + * + * @param string $keyname the key name to use for the TSIG RR + * @param string $signature the key to sign the request + * @param mixed $algorithm + * + * @return bool + * + * @see Net_DNS2::signTSIG() + * @deprecated function deprecated in 1.1.0 + */ + public function signature($keyname, $signature, $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5) + { + return $this->signTSIG($keyname, $signature, $algorithm); + } + + /** + * returns the current internal packet object. + * + * @return Net_DNS2_Packet_Request + */ + public function packet() + { + // + // take a copy + // + $p = $this->_packet; + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $p->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $p->header->qdcount = cacti_sizeof($p->question); + $p->header->ancount = cacti_sizeof($p->answer); + $p->header->nscount = cacti_sizeof($p->authority); + $p->header->arcount = cacti_sizeof($p->additional); + + return $p; + } + + /** + * executes the notify request. + * + * @param Net_DNS2_Packet_Response &$response ref to the response object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function notify(&$response = null) + { + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $this->_packet->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); + $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); + $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); + $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); + + // + // make sure we have some data to send + // + if (0 == $this->_packet->header->qdcount) { + throw new Net_DNS2_Exception( + 'empty headers- nothing to send!', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + // + // send the packet and get back the response + // + $response = $this->sendPacket($this->_packet, $this->use_tcp); + + // + // clear the internal packet so if we make another request, we don't have + // old data being sent. + // + $this->_packet->reset(); + + // + // for notifies, we just need to know it worked- we don't actually need to + // return the response object + // + return true; + } + + /** + * checks that the given name matches the name for the zone we're notifying. + * + * @param string $name the name to be checked + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + private function _checkName($name) + { + if (!preg_match('/'.$this->_packet->question[0]->qname.'$/', $name)) { + throw new Net_DNS2_Exception( + 'name provided ('.$name.') does not match zone name (' + .$this->_packet->question[0]->qname.')', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + return true; + } } diff --git a/Net/DNS2/Packet.php b/Net/DNS2/Packet.php index b52cc8d6..466a1735 100644 --- a/Net/DNS2/Packet.php +++ b/Net/DNS2/Packet.php @@ -1,28 +1,28 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ + * + * @see https://netdns2.com/ * @since File available since Release 0.6.0 * * This file contains code based off the Net::DNS Perl module by Michael Fuhr. * * This is the copyright notice from the PERL Net::DNS module: * - * Copyright (c) 1997-2000 Michael Fuhr. All rights reserved. This program is - * free software; you can redistribute it and/or modify it under the same terms + * Copyright (c) 1997-2000 Michael Fuhr. All rights reserved. This program is + * free software; you can redistribute it and/or modify it under the same terms * as Perl itself. - * */ /** @@ -30,24 +30,17 @@ * * The Net_DNS2_Packet_Request and Net_DNS2_Packet_Response classes extend this * class. - * */ class Net_DNS2_Packet { - /* - * the full binary data and length for this packet - */ + // the full binary data and length for this packet public $rdata; public $rdlength; - /* - * the offset pointer used when building/parsing packets - */ + // the offset pointer used when building/parsing packets public $offset = 0; - /* - * Net_DNS2_Header object with the DNS packet header - */ + // Net_DNS2_Header object with the DNS packet header public $header; /* @@ -60,7 +53,7 @@ class Net_DNS2_Packet /* * array of Net_DNS2_RR Objects for Answers - * + * * used as "prerequisite" for updates per RFC2136 * */ @@ -74,73 +67,58 @@ class Net_DNS2_Packet */ public $authority = []; - /* - * array of Net_DNS2_RR Objects for Additional - */ + // array of Net_DNS2_RR Objects for Additional public $additional = []; - /* - * array of compressed labeles - */ + // array of compressed labeles private $_compressed = []; /** - * magic __toString() method to return the Net_DNS2_Packet as a string + * magic __toString() method to return the Net_DNS2_Packet as a string. * * @return string - * @access public - * */ public function __toString() { $output = $this->header->__toString(); foreach ($this->question as $x) { - - $output .= $x->__toString() . "\n"; + $output .= $x->__toString()."\n"; } foreach ($this->answer as $x) { - - $output .= $x->__toString() . "\n"; + $output .= $x->__toString()."\n"; } foreach ($this->authority as $x) { - - $output .= $x->__toString() . "\n"; + $output .= $x->__toString()."\n"; } foreach ($this->additional as $x) { - - $output .= $x->__toString() . "\n"; + $output .= $x->__toString()."\n"; } return $output; } /** - * returns a full binary DNS packet + * returns a full binary DNS packet. * * @return string - * @throws Net_DNS2_Exception - * @access public * + * @throws Net_DNS2_Exception */ public function get() { $data = $this->header->get($this); foreach ($this->question as $x) { - $data .= $x->get($this); } foreach ($this->answer as $x) { - $data .= $x->get($this); } foreach ($this->authority as $x) { - $data .= $x->get($this); } foreach ($this->additional as $x) { - $data .= $x->get($this); } @@ -148,17 +126,15 @@ public function get() } /** - * applies a standard DNS name compression on the given name/offset + * applies a standard DNS name compression on the given name/offset. * - * This logic was based on the Net::DNS::Packet::dn_comp() function + * This logic was based on the Net::DNS::Packet::dn_comp() function * by Michanel Fuhr * - * @param string $name the name to be compressed - * @param integer &$offset the offset into the given packet object + * @param string $name the name to be compressed + * @param int &$offset the offset into the given packet object * * @return string - * @access public - * */ public function compress($name, &$offset) { @@ -168,16 +144,14 @@ public function compress($name, &$offset) // // there's only a few cases like this- the rname in SOA for example // - $names = str_replace('\.', '.', preg_split('/(?_compressed[$dname])) { - - $compname .= pack('n', 0xc000 | $this->_compressed[$dname]); + $compname .= pack('n', 0xC000 | $this->_compressed[$dname]); $offset += 2; break; @@ -191,12 +165,11 @@ public function compress($name, &$offset) if ($length <= 0) { continue; } - + // // truncate see RFC1035 2.3.1 // if ($length > 63) { - $length = 63; $first = substr($first, 0, $length); } @@ -206,25 +179,22 @@ public function compress($name, &$offset) } if (empty($names)) { - $compname .= pack('C', 0); - $offset++; + ++$offset; } return $compname; } /** - * applies a standard DNS name compression on the given name/offset + * applies a standard DNS name compression on the given name/offset. * - * This logic was based on the Net::DNS::Packet::dn_comp() function + * This logic was based on the Net::DNS::Packet::dn_comp() function * by Michanel Fuhr * * @param string $name the name to be compressed * * @return string - * @access public - * */ public static function pack($name) { @@ -233,7 +203,6 @@ public static function pack($name) $compname = ''; while (!empty($names)) { - $first = array_shift($names); $length = strlen($first); @@ -242,24 +211,22 @@ public static function pack($name) } $compname .= "\0"; - $offset++; + ++$offset; return $compname; } /** - * expands the domain name stored at a given offset in a DNS Packet + * expands the domain name stored at a given offset in a DNS Packet. * * This logic was based on the Net::DNS::Packet::dn_expand() function * by Michanel Fuhr * - * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name - * @param integer &$offset the offset into the given packet object - * @param boolean $escape_dot_literals if we should escape periods in names - * - * @return mixed either the domain name or null if it's not found. - * @access public + * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name + * @param int &$offset the offset into the given packet object + * @param bool $escape_dot_literals if we should escape periods in names * + * @return mixed either the domain name or null if it's not found */ public static function expand(Net_DNS2_Packet &$packet, &$offset, $escape_dot_literals = false) { @@ -269,75 +236,67 @@ public static function expand(Net_DNS2_Packet &$packet, &$offset, $escape_dot_li if ($packet->rdlength < ($offset + 1)) { return null; } - - $xlen = ord($packet->rdata[$offset]); - if ($xlen == 0) { + $xlen = ord($packet->rdata[$offset]); + if (0 == $xlen) { ++$offset; - break; - } else if (($xlen & 0xc0) == 0xc0) { + break; + } + if (($xlen & 0xC0) == 0xC0) { if ($packet->rdlength < ($offset + 2)) { - return null; } - $ptr = ord($packet->rdata[$offset]) << 8 | ord($packet->rdata[$offset+1]); - $ptr = $ptr & 0x3fff; + $ptr = ord($packet->rdata[$offset]) << 8 | ord($packet->rdata[$offset + 1]); + $ptr = $ptr & 0x3FFF; $name2 = Net_DNS2_Packet::expand($packet, $ptr); if (is_null($name2)) { - return null; } $name .= $name2; $offset += 2; - - break; - } else { - ++$offset; - - if ($packet->rdlength < ($offset + $xlen)) { - - return null; - } - $elem = ''; - $elem = substr($packet->rdata, $offset, $xlen); + break; + } + ++$offset; - // - // escape literal dots in certain cases (SOA rname) - // - if ( ($escape_dot_literals == true) && (strpos($elem, '.') !== false) ) { + if ($packet->rdlength < ($offset + $xlen)) { + return null; + } - $elem = str_replace('.', '\.', $elem); - } + $elem = ''; + $elem = substr($packet->rdata, $offset, $xlen); - $name .= $elem . '.'; - $offset += $xlen; + // + // escape literal dots in certain cases (SOA rname) + // + if ((true == $escape_dot_literals) && (false !== strpos($elem, '.'))) { + $elem = str_replace('.', '\.', $elem); } + + $name .= $elem.'.'; + $offset += $xlen; } return trim($name, '.'); } /** - * parses a domain label from a DNS Packet at the given offset + * parses a domain label from a DNS Packet at the given offset. * * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name - * @param integer &$offset the offset into the given packet object - * - * @return mixed either the domain name or null if it's not found. - * @access public + * @param int &$offset the offset into the given packet object * + * @return mixed either the domain name or null if it's not found */ public static function label(Net_DNS2_Packet &$packet, &$offset) { $name = ''; if ($packet->rdlength < ($offset + 1)) { - return null; } @@ -345,11 +304,9 @@ public static function label(Net_DNS2_Packet &$packet, &$offset) ++$offset; if (($xlen + $offset) > $packet->rdlength) { - $name = substr($packet->rdata, $offset); $offset = $packet->rdlength; } else { - $name = substr($packet->rdata, $offset, $xlen); $offset += $xlen; } @@ -363,39 +320,35 @@ public static function label(Net_DNS2_Packet &$packet, &$offset) * * @param Net_DNS2_Packet $packet the DNS packet to copy the data from * - * @return boolean - * @access public - * + * @return bool */ public function copy(Net_DNS2_Packet $packet) { - $this->header = $packet->header; - $this->question = $packet->question; - $this->answer = $packet->answer; - $this->authority = $packet->authority; - $this->additional = $packet->additional; + $this->header = $packet->header; + $this->question = $packet->question; + $this->answer = $packet->answer; + $this->authority = $packet->authority; + $this->additional = $packet->additional; return true; } /** - * resets the values in the current packet object - * - * @return boolean - * @access public + * resets the values in the current packet object. * + * @return bool */ public function reset() { - $this->header->id = $this->header->nextPacketId(); - $this->rdata = ''; - $this->rdlength = 0; - $this->offset = 0; - $this->answer = []; - $this->authority = []; - $this->additional = []; - $this->_compressed = []; - + $this->header->id = $this->header->nextPacketId(); + $this->rdata = ''; + $this->rdlength = 0; + $this->offset = 0; + $this->answer = []; + $this->authority = []; + $this->additional = []; + $this->_compressed = []; + return true; } } diff --git a/Net/DNS2/Packet/Request.php b/Net/DNS2/Packet/Request.php index 22d5902a..92391ee3 100644 --- a/Net/DNS2/Packet/Request.php +++ b/Net/DNS2/Packet/Request.php @@ -1,39 +1,36 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * This class handles building new DNS request packets; packets used for DNS * queries and updates. - * */ class Net_DNS2_Packet_Request extends Net_DNS2_Packet { /** - * Constructor - builds a new Net_DNS2_Packet_Request object + * Constructor - builds a new Net_DNS2_Packet_Request object. * * @param string $name the domain name for the packet * @param string $type the DNS RR type for the packet * @param string $class the DNS class for the packet * * @throws Net_DNS2_Exception - * @access public - * */ public function __construct($name, $type = null, $class = null) { @@ -41,23 +38,22 @@ public function __construct($name, $type = null, $class = null) } /** - * builds a new Net_DNS2_Packet_Request object + * builds a new Net_DNS2_Packet_Request object. * * @param string $name the domain name for the packet * @param string $type the DNS RR type for the packet * @param string $class the DNS class for the packet * - * @return boolean - * @throws Net_DNS2_Exception - * @access public + * @return bool * + * @throws Net_DNS2_Exception */ public function set($name, $type = 'A', $class = 'IN') { // // generate a new header // - $this->header = new Net_DNS2_Header; + $this->header = new Net_DNS2_Header(); // // add a new question @@ -67,7 +63,7 @@ public function set($name, $type = 'A', $class = 'IN') // // allow queries directly to . for the root name servers // - if ($name != '.') { + if ('.' != $name) { $name = trim(strtolower($name), " \t\n\r\0\x0B."); } @@ -78,7 +74,6 @@ public function set($name, $type = 'A', $class = 'IN') // check that the input string has some data in it // if (empty($name)) { - throw new Net_DNS2_Exception( 'empty query string provided', Net_DNS2_Lookups::E_PACKET_INVALID @@ -88,25 +83,23 @@ public function set($name, $type = 'A', $class = 'IN') // // if the type is "*", rename it to "ANY"- both are acceptable. // - if ($type == '*') { - + if ('*' == $type) { $type = 'ANY'; } // // check that the type and class are valid - // - if ( (!isset(Net_DNS2_Lookups::$rr_types_by_name[$type])) - || (!isset(Net_DNS2_Lookups::$classes_by_name[$class])) + // + if ((!isset(Net_DNS2_Lookups::$rr_types_by_name[$type])) + || (!isset(Net_DNS2_Lookups::$classes_by_name[$class])) ) { throw new Net_DNS2_Exception( - 'invalid type (' . $type . ') or class (' . $class . ') specified.', + 'invalid type ('.$type.') or class ('.$class.') specified.', Net_DNS2_Lookups::E_PACKET_INVALID ); } - if ($type == 'PTR') { - + if ('PTR' == $type) { // // if it's a PTR request for an IP address, then make sure we tack on // the arpa domain. @@ -114,32 +107,27 @@ public function set($name, $type = 'A', $class = 'IN') // there are other types of PTR requests, so if an IP adress doesn't match, // then just let it flow through and assume it's a hostname // - if (Net_DNS2::isIPv4($name) == true) { - + if (true == Net_DNS2::isIPv4($name)) { // // IPv4 // $name = implode('.', array_reverse(explode('.', $name))); $name .= '.in-addr.arpa'; - - } else if (Net_DNS2::isIPv6($name) == true) { - + } elseif (true == Net_DNS2::isIPv6($name)) { // // IPv6 // $e = Net_DNS2::expandIPv6($name); - if ($e !== false) { - + if (false !== $e) { $name = implode( - '.', array_reverse(str_split(str_replace(':', '', $e))) + '.', + array_reverse(str_split(str_replace(':', '', $e))) ); $name .= '.ip6.arpa'; - } else { - throw new Net_DNS2_Exception( - 'unsupported PTR value: ' . $name, + 'unsupported PTR value: '.$name, Net_DNS2_Lookups::E_PACKET_INVALID ); } @@ -149,19 +137,19 @@ public function set($name, $type = 'A', $class = 'IN') // // store the data // - $q->qname = $name; - $q->qtype = $type; - $q->qclass = $class; + $q->qname = $name; + $q->qtype = $type; + $q->qclass = $class; - $this->question[] = $q; + $this->question[] = $q; // // the answer, authority and additional are empty; they can be modified // after the request is created for UPDATE requests if needed. // - $this->answer = []; - $this->authority = []; - $this->additional = []; + $this->answer = []; + $this->authority = []; + $this->additional = []; return true; } diff --git a/Net/DNS2/Packet/Response.php b/Net/DNS2/Packet/Response.php index 7d0d3c74..a5d1f0a4 100644 --- a/Net/DNS2/Packet/Response.php +++ b/Net/DNS2/Packet/Response.php @@ -1,53 +1,44 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * This class handles building new DNS response packets; it parses binary packed - * packets that come off the wire - * + * packets that come off the wire. */ class Net_DNS2_Packet_Response extends Net_DNS2_Packet { - /* - * The name servers that this response came from - */ + // The name servers that this response came from public $answer_from; - /* - * The socket type the answer came from (TCP/UDP) - */ + // The socket type the answer came from (TCP/UDP) public $answer_socket_type; - /* - * The query response time in microseconds - */ + // The query response time in microseconds public $response_time = 0; /** - * Constructor - builds a new Net_DNS2_Packet_Response object + * Constructor - builds a new Net_DNS2_Packet_Response object. * - * @param string $data binary DNS packet - * @param integer $size the length of the DNS packet + * @param string $data binary DNS packet + * @param int $size the length of the DNS packet * * @throws Net_DNS2_Exception - * @access public - * */ public function __construct($data, $size) { @@ -55,27 +46,26 @@ public function __construct($data, $size) } /** - * builds a new Net_DNS2_Packet_Response object + * builds a new Net_DNS2_Packet_Response object. * - * @param string $data binary DNS packet - * @param integer $size the length of the DNS packet + * @param string $data binary DNS packet + * @param int $size the length of the DNS packet * - * @return boolean - * @throws Net_DNS2_Exception - * @access public + * @return bool * + * @throws Net_DNS2_Exception */ public function set($data, $size) { // // store the full packet // - $this->rdata = $data; + $this->rdata = $data; $this->rdlength = $size; // // parse the header - // + // // we don't bother checking the size earlier, because the first thing the // header class does, is check the size and throw and exception if it's // invalid. @@ -87,12 +77,11 @@ public function set($data, $size) // rest of the packet is probably empty; and there's no point in processing // anything else. // - // we also don't need to worry about checking to see if the the header is - // null or not, since the Net_DNS2_Header() constructor will throw an + // we also don't need to worry about checking to see if the the header is + // null or not, since the Net_DNS2_Header() constructor will throw an // exception if the packet is invalid. // - if ($this->header->tc == 1) { - + if (1 == $this->header->tc) { return false; } @@ -100,7 +89,6 @@ public function set($data, $size) // parse the questions // for ($x = 0; $x < $this->header->qdcount; ++$x) { - $this->question[$x] = new Net_DNS2_Question($this); } @@ -108,23 +96,19 @@ public function set($data, $size) // parse the answers // for ($x = 0; $x < $this->header->ancount; ++$x) { - $o = Net_DNS2_RR::parse($this); if (!is_null($o)) { - $this->answer[] = $o; } - } + } // // parse the authority section // for ($x = 0; $x < $this->header->nscount; ++$x) { - $o = Net_DNS2_RR::parse($this); if (!is_null($o)) { - - $this->authority[] = $o; + $this->authority[] = $o; } } @@ -132,11 +116,9 @@ public function set($data, $size) // parse the additional section // for ($x = 0; $x < $this->header->arcount; ++$x) { - $o = Net_DNS2_RR::parse($this); if (!is_null($o)) { - - $this->additional[] = $o; + $this->additional[] = $o; } } diff --git a/Net/DNS2/PrivateKey.php b/Net/DNS2/PrivateKey.php index 8f521458..3aa3f713 100644 --- a/Net/DNS2/PrivateKey.php +++ b/Net/DNS2/PrivateKey.php @@ -8,369 +8,327 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.1.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.1.0 */ /** - * SSL Private Key container class - * + * SSL Private Key container class. */ class Net_DNS2_PrivateKey { - /* - * the filename that was loaded; stored for reference - */ - public $filename; - - /* - * the keytag for the signature - */ - public $keytag; - - /* - * the sign name for the signature - */ - public $signname; - - /* - * the algorithm used for the signature - */ - public $algorithm; - - /* - * the key format of the signature - */ - public $key_format; - - /* - * the openssl private key id - */ - public $instance; - - /* - * RSA: modulus - */ - private $_modulus; - - /* - * RSA: public exponent - */ - private $_public_exponent; - - /* - * RSA: rivate exponent - */ - private $_private_exponent; - - /* - * RSA: prime1 - */ - private $_prime1; - - /* - * RSA: prime2 - */ - private $_prime2; - - /* - * RSA: exponent 1 - */ - private $_exponent1; - - /* - * RSA: exponent 2 - */ - private $_exponent2; - - /* - * RSA: coefficient - */ - private $_coefficient; - - /* - * DSA: prime - */ - public $prime; - - /* - * DSA: subprime - */ - public $subprime; - - /* - * DSA: base - */ - public $base; - - /* - * DSA: private value - */ - public $private_value; - - /* - * DSA: public value - */ - public $public_value; - - /** - * Constructor - base constructor the private key container class - * - * @param string $file path to a private-key file to parse and load - * - * @throws Net_DNS2_Exception - * @access public - * - */ - public function __construct($file = null) - { - if (isset($file)) { - $this->parseFile($file); - } - } - - /** - * parses a private key file generated by dnssec-keygen - * - * @param string $file path to a private-key file to parse and load - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function parseFile($file) - { - // - // check for OpenSSL - // - if (extension_loaded('openssl') === false) { - - throw new Net_DNS2_Exception( - 'the OpenSSL extension is required to use parse private key.', - Net_DNS2_Lookups::E_OPENSSL_UNAVAIL - ); - } - - // - // check to make sure the file exists - // - if (is_readable($file) == false) { - - throw new Net_DNS2_Exception( - 'invalid private key file: ' . $file, - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // get the base filename, and parse it for the local value - // - $keyname = basename($file); - if (strlen($keyname) == 0) { - - throw new Net_DNS2_Exception( - 'failed to get basename() for: ' . $file, - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // parse the keyname - // - if (preg_match("/K(.*)\.\+(\d{3})\+(\d*)\.private/", $keyname, $matches)) { - - $this->signname = $matches[1]; - $this->algorithm = intval($matches[2]); - $this->keytag = intval($matches[3]); - - } else { - - throw new Net_DNS2_Exception( - 'file ' . $keyname . ' does not look like a private key file!', - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // read all the data from the - // - $data = file($file, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); - if (cacti_sizeof($data) == 0) { - throw new Net_DNS2_Exception( - 'file ' . $keyname . ' is empty!', - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - foreach ($data as $line) { - - list($key, $value) = explode(':', $line); - - $key = trim($key); - $value = trim($value); - - switch(strtolower($key)) { - - case 'private-key-format': - $this->key_format = $value; - break; - - case 'algorithm': - if ($this->algorithm != $value) { - throw new Net_DNS2_Exception( - 'Algorithm mismatch! filename is ' . $this->algorithm . - ', contents say ' . $value, - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - break; - - // - // RSA - // - case 'modulus': - $this->_modulus = $value; - break; - - case 'publicexponent': - $this->_public_exponent = $value; - break; - - case 'privateexponent': - $this->_private_exponent = $value; - break; - - case 'prime1': - $this->_prime1 = $value; - break; - - case 'prime2': - $this->_prime2 = $value; - break; - - case 'exponent1': - $this->_exponent1 = $value; - break; - - case 'exponent2': - $this->_exponent2 = $value; - break; - - case 'coefficient': - $this->_coefficient = $value; - break; - - // - // DSA - this won't work in PHP until the OpenSSL extension is better - // - case 'prime(p)': - $this->prime = $value; - break; - - case 'subprime(q)': - $this->subprime = $value; - break; - - case 'base(g)': - $this->base = $value; - break; - - case 'private_value(x)': - $this->private_value = $value; - break; - - case 'public_value(y)': - $this->public_value = $value; - break; - - default: - throw new Net_DNS2_Exception( - 'unknown private key data: ' . $key . ': ' . $value, - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - } - - // - // generate the private key - // - $args = []; - - switch($this->algorithm) { - - // - // RSA - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - - $args = [ - - 'rsa' => [ - - 'n' => base64_decode($this->_modulus), - 'e' => base64_decode($this->_public_exponent), - 'd' => base64_decode($this->_private_exponent), - 'p' => base64_decode($this->_prime1), - 'q' => base64_decode($this->_prime2), - 'dmp1' => base64_decode($this->_exponent1), - 'dmq1' => base64_decode($this->_exponent2), - 'iqmp' => base64_decode($this->_coefficient) - ] - ]; - - break; - - // - // DSA - this won't work in PHP until the OpenSSL extension is better - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: - - $args = [ - - 'dsa' => [ - - 'p' => base64_decode($this->prime), - 'q' => base64_decode($this->subprime), - 'g' => base64_decode($this->base), - 'priv_key' => base64_decode($this->private_value), - 'pub_key' => base64_decode($this->public_value) - ] - ]; - - break; - - default: - throw new Net_DNS2_Exception( - 'we only currently support RSAMD5 and RSASHA1 encryption.', - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // generate and store the key - // - $this->instance = openssl_pkey_new($args); - if ($this->instance === false) { - throw new Net_DNS2_Exception( - openssl_error_string(), - Net_DNS2_Lookups::E_OPENSSL_ERROR - ); - } - - // - // store the filename incase we need it for something - // - $this->filename = $file; - - return true; - } + // the filename that was loaded; stored for reference + public $filename; + + // the keytag for the signature + public $keytag; + + // the sign name for the signature + public $signname; + + // the algorithm used for the signature + public $algorithm; + + // the key format of the signature + public $key_format; + + // the openssl private key id + public $instance; + + // DSA: prime + public $prime; + + // DSA: subprime + public $subprime; + + // DSA: base + public $base; + + // DSA: private value + public $private_value; + + // DSA: public value + public $public_value; + + // RSA: modulus + private $_modulus; + + // RSA: public exponent + private $_public_exponent; + + // RSA: rivate exponent + private $_private_exponent; + + // RSA: prime1 + private $_prime1; + + // RSA: prime2 + private $_prime2; + + // RSA: exponent 1 + private $_exponent1; + + // RSA: exponent 2 + private $_exponent2; + + // RSA: coefficient + private $_coefficient; + + /** + * Constructor - base constructor the private key container class. + * + * @param string $file path to a private-key file to parse and load + * + * @throws Net_DNS2_Exception + */ + public function __construct($file = null) + { + if (isset($file)) { + $this->parseFile($file); + } + } + + /** + * parses a private key file generated by dnssec-keygen. + * + * @param string $file path to a private-key file to parse and load + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function parseFile($file) + { + // + // check for OpenSSL + // + if (false === extension_loaded('openssl')) { + throw new Net_DNS2_Exception( + 'the OpenSSL extension is required to use parse private key.', + Net_DNS2_Lookups::E_OPENSSL_UNAVAIL + ); + } + + // + // check to make sure the file exists + // + if (false == is_readable($file)) { + throw new Net_DNS2_Exception( + 'invalid private key file: '.$file, + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // get the base filename, and parse it for the local value + // + $keyname = basename($file); + if (0 == strlen($keyname)) { + throw new Net_DNS2_Exception( + 'failed to get basename() for: '.$file, + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // parse the keyname + // + if (preg_match('/K(.*)\\.\\+(\\d{3})\\+(\\d*)\\.private/', $keyname, $matches)) { + $this->signname = $matches[1]; + $this->algorithm = intval($matches[2]); + $this->keytag = intval($matches[3]); + } else { + throw new Net_DNS2_Exception( + 'file '.$keyname.' does not look like a private key file!', + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // read all the data from the + // + $data = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + if (0 == cacti_sizeof($data)) { + throw new Net_DNS2_Exception( + 'file '.$keyname.' is empty!', + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + foreach ($data as $line) { + list($key, $value) = explode(':', $line); + + $key = trim($key); + $value = trim($value); + + switch (strtolower($key)) { + case 'private-key-format': + $this->key_format = $value; + + break; + + case 'algorithm': + if ($this->algorithm != $value) { + throw new Net_DNS2_Exception( + 'Algorithm mismatch! filename is '.$this->algorithm + .', contents say '.$value, + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + break; + + // + // RSA + // + case 'modulus': + $this->_modulus = $value; + + break; + + case 'publicexponent': + $this->_public_exponent = $value; + + break; + + case 'privateexponent': + $this->_private_exponent = $value; + + break; + + case 'prime1': + $this->_prime1 = $value; + + break; + + case 'prime2': + $this->_prime2 = $value; + + break; + + case 'exponent1': + $this->_exponent1 = $value; + + break; + + case 'exponent2': + $this->_exponent2 = $value; + + break; + + case 'coefficient': + $this->_coefficient = $value; + + break; + + // + // DSA - this won't work in PHP until the OpenSSL extension is better + // + case 'prime(p)': + $this->prime = $value; + + break; + + case 'subprime(q)': + $this->subprime = $value; + + break; + + case 'base(g)': + $this->base = $value; + + break; + + case 'private_value(x)': + $this->private_value = $value; + + break; + + case 'public_value(y)': + $this->public_value = $value; + + break; + + default: + throw new Net_DNS2_Exception( + 'unknown private key data: '.$key.': '.$value, + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + } + + // + // generate the private key + // + $args = []; + + switch ($this->algorithm) { + // + // RSA + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + $args = [ + 'rsa' => [ + 'n' => base64_decode($this->_modulus), + 'e' => base64_decode($this->_public_exponent), + 'd' => base64_decode($this->_private_exponent), + 'p' => base64_decode($this->_prime1), + 'q' => base64_decode($this->_prime2), + 'dmp1' => base64_decode($this->_exponent1), + 'dmq1' => base64_decode($this->_exponent2), + 'iqmp' => base64_decode($this->_coefficient), + ], + ]; + + break; + + // + // DSA - this won't work in PHP until the OpenSSL extension is better + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: + $args = [ + 'dsa' => [ + 'p' => base64_decode($this->prime), + 'q' => base64_decode($this->subprime), + 'g' => base64_decode($this->base), + 'priv_key' => base64_decode($this->private_value), + 'pub_key' => base64_decode($this->public_value), + ], + ]; + + break; + + default: + throw new Net_DNS2_Exception( + 'we only currently support RSAMD5 and RSASHA1 encryption.', + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // generate and store the key + // + $this->instance = openssl_pkey_new($args); + if (false === $this->instance) { + throw new Net_DNS2_Exception( + openssl_error_string(), + Net_DNS2_Lookups::E_OPENSSL_ERROR + ); + } + + // + // store the filename incase we need it for something + // + $this->filename = $file; + + return true; + } } diff --git a/Net/DNS2/Question.php b/Net/DNS2/Question.php index 7146ce02..aa7393ec 100644 --- a/Net/DNS2/Question.php +++ b/Net/DNS2/Question.php @@ -1,20 +1,20 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** @@ -35,7 +35,6 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | QCLASS | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_Question { @@ -54,7 +53,7 @@ class Net_DNS2_Question * */ public $qtype; - + /* * The RR class for the questino * @@ -64,50 +63,43 @@ class Net_DNS2_Question public $qclass; /** - * Constructor - builds a new Net_DNS2_Question object + * Constructor - builds a new Net_DNS2_Question object. * - * @param mixed &$packet either a Net_DNS2_Packet object, or null to + * @param mixed &$packet either a Net_DNS2_Packet object, or null to * build an empty object * * @throws Net_DNS2_Exception - * @access public - * */ - public function __construct(Net_DNS2_Packet &$packet = null) + public function __construct(?Net_DNS2_Packet &$packet = null) { if (!is_null($packet)) { - $this->set($packet); } else { - - $this->qname = ''; - $this->qtype = 'A'; - $this->qclass = 'IN'; + $this->qname = ''; + $this->qtype = 'A'; + $this->qclass = 'IN'; } } /** - * magic __toString() function to return the Net_DNS2_Question object as a string + * magic __toString() function to return the Net_DNS2_Question object as a string. * * @return string - * @access public - * */ public function __toString() { - return ";;\n;; Question:\n;;\t " . $this->qname . '. ' . - $this->qtype . ' ' . $this->qclass . "\n"; + return ";;\n;; Question:\n;;\t ".$this->qname.'. ' + .$this->qtype.' '.$this->qclass."\n"; } /** - * builds a new Net_DNS2_Header object from a Net_DNS2_Packet object + * builds a new Net_DNS2_Header object from a Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet object * - * @return boolean - * @throws Net_DNS2_Exception - * @access public + * @return bool * + * @throws Net_DNS2_Exception */ public function set(Net_DNS2_Packet &$packet) { @@ -116,7 +108,6 @@ public function set(Net_DNS2_Packet &$packet) // $this->qname = $packet->expand($packet, $packet->offset); if ($packet->rdlength < ($packet->offset + 4)) { - throw new Net_DNS2_Exception( 'invalid question section: to small', Net_DNS2_Lookups::E_QUESTION_INVALID @@ -126,22 +117,21 @@ public function set(Net_DNS2_Packet &$packet) // // unpack the type and class // - $type = ord($packet->rdata[$packet->offset++]) << 8 | - ord($packet->rdata[$packet->offset++]); - $class = ord($packet->rdata[$packet->offset++]) << 8 | - ord($packet->rdata[$packet->offset++]); + $type = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + $class = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); // // validate it // - $type_name = Net_DNS2_Lookups::$rr_types_by_id[$type]; + $type_name = Net_DNS2_Lookups::$rr_types_by_id[$type]; $class_name = Net_DNS2_Lookups::$classes_by_id[$class]; - if ( (!isset($type_name)) || (!isset($class_name)) ) { - + if ((!isset($type_name)) || (!isset($class_name))) { throw new Net_DNS2_Exception( - 'invalid question section: invalid type (' . $type . - ') or class (' . $class . ') specified.', + 'invalid question section: invalid type ('.$type + .') or class ('.$class.') specified.', Net_DNS2_Lookups::E_QUESTION_INVALID ); } @@ -149,46 +139,44 @@ public function set(Net_DNS2_Packet &$packet) // // store it // - $this->qtype = $type_name; - $this->qclass = $class_name; + $this->qtype = $type_name; + $this->qclass = $class_name; return true; } /** - * returns a binary packed Net_DNS2_Question object + * returns a binary packed Net_DNS2_Question object. * - * @param Net_DNS2_Packet &$packet the Net_DNS2_Packet object this question is + * @param Net_DNS2_Packet &$packet the Net_DNS2_Packet object this question is * part of. This needs to be passed in so that * the compressed qname value can be packed in - * with the names of the other parts of the + * with the names of the other parts of the * packet. * * @return string - * @throws Net_DNS2_Exception - * @access public * + * @throws Net_DNS2_Exception */ public function get(Net_DNS2_Packet &$packet) { // // validate the type and class // - $type = Net_DNS2_Lookups::$rr_types_by_name[$this->qtype]; + $type = Net_DNS2_Lookups::$rr_types_by_name[$this->qtype]; $class = Net_DNS2_Lookups::$classes_by_name[$this->qclass]; - if ( (!isset($type)) || (!isset($class)) ) { - + if ((!isset($type)) || (!isset($class))) { throw new Net_DNS2_Exception( - 'invalid question section: invalid type (' . $this->qtype . - ') or class (' . $this->qclass . ') specified.', + 'invalid question section: invalid type ('.$this->qtype + .') or class ('.$this->qclass.') specified.', Net_DNS2_Lookups::E_QUESTION_INVALID ); } $data = $packet->compress($this->qname, $packet->offset); - $data .= chr($type >> 8) . chr($type) . chr($class >> 8) . chr($class); + $data .= chr($type >> 8).chr($type).chr($class >> 8).chr($class); $packet->offset += 4; return $data; diff --git a/Net/DNS2/RR.php b/Net/DNS2/RR.php index 822c4894..4131342c 100644 --- a/Net/DNS2/RR.php +++ b/Net/DNS2/RR.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * This is the base class for DNS Resource Records + * This is the base class for DNS Resource Records. * * Each resource record type (defined in RR/*.php) extends this class for * base functionality. @@ -48,569 +48,500 @@ * / RDATA / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ abstract class Net_DNS2_RR { - /* - * The name of the resource record - */ - public $name; - - /* - * The resource record type - */ - public $type; - - /* - * The resource record class - */ - public $class; - - /* - * The time to live for this resource record - */ - public $ttl; - - /* - * The length of the rdata field - */ - public $rdlength; - - /* - * The resource record specific data as a packed binary string - */ - public $rdata; - - /** - * abstract definition - method to return a RR as a string; not to - * be confused with the __toString() magic method. - * - * @return string - * @access protected - * - */ - abstract protected function rrToString(); - - /** - * abstract definition - parses a RR from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - abstract protected function rrFromString(array $rdata); - - /** - * abstract definition - sets a Net_DNS2_RR from a Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - abstract protected function rrSet(Net_DNS2_Packet &$packet); - - /** - * abstract definition - returns a binary packet DNS RR object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed string or - * null on failure - * @access protected - * - */ - abstract protected function rrGet(Net_DNS2_Packet &$packet); - - /** - * Constructor - builds a new Net_DNS2_RR object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create - * an empty object - * @param array $rr an array with RR parse values or null to - * create an empty object - * - * @throws Net_DNS2_Exception - * @access public - * - */ - public function __construct(Net_DNS2_Packet &$packet = null, array $rr = null) - { - if ( (!is_null($packet)) && (!is_null($rr)) ) { - - if ($this->set($packet, $rr) == false) { - - throw new Net_DNS2_Exception( - 'failed to generate resource record', - Net_DNS2_Lookups::E_RR_INVALID - ); - } - } else { - - $class = Net_DNS2_Lookups::$rr_types_class_to_id[get_class($this)]; - if (isset($class)) { - - $this->type = Net_DNS2_Lookups::$rr_types_by_id[$class]; - } - - $this->class = 'IN'; - $this->ttl = 86400; - } - } - - /** - * magic __toString() method to return the Net_DNS2_RR object object as a string - * - * @return string - * @access public - * - */ - public function __toString() - { - return $this->name . '. ' . $this->ttl . ' ' . $this->class . - ' ' . $this->type . ' ' . $this->rrToString(); - } - - /** - * return the same data as __toString(), but as an array, so each value can be - * used without having to parse the string. - * - * @return array - * @access public - * - */ - public function asArray() - { - return [ - - 'name' => $this->name, - 'ttl' => $this->ttl, - 'class' => $this->class, - 'type' => $this->type, - 'rdata' => $this->rrToString() - ]; - } - - /** - * return a formatted string; if a string has spaces in it, then return - * it with double quotes around it, otherwise, return it as it was passed in. - * - * @param string $string the string to format - * - * @return string - * @access protected - * - */ - protected function formatString($string) - { - return '"' . str_replace('"', '\"', trim($string, '"')) . '"'; - } - - /** - * builds an array of strings from an array of chunks of text split by spaces - * - * @param array $chunks an array of chunks of text split by spaces - * - * @return array - * @access protected - * - */ - protected function buildString(array $chunks) - { - $data = []; - $c = 0; - $in = false; - - foreach ($chunks as $r) { - - $r = trim($r); - if (strlen($r) == 0) { - continue; - } - - if ( ($r[0] == '"') - && ($r[strlen($r) - 1] == '"') - && ($r[strlen($r) - 2] != '\\') - ) { - - $data[$c] = $r; - ++$c; - $in = false; - - } else if ($r[0] == '"') { - - $data[$c] = $r; - $in = true; - - } else if ( ($r[strlen($r) - 1] == '"') - && ($r[strlen($r) - 2] != '\\') - ) { - - $data[$c] .= ' ' . $r; - ++$c; - $in = false; - - } else { - - if ($in == true) { - $data[$c] .= ' ' . $r; - } else { - $data[$c++] = $r; - } - } - } - - foreach ($data as $index => $string) { - - $data[$index] = str_replace('\"', '"', trim($string, '"')); - } - - return $data; - } - - /** - * builds a new Net_DNS2_RR object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create - * an empty object - * @param array $rr an array with RR parse values or null to - * create an empty object - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function set(Net_DNS2_Packet &$packet, array $rr) - { - $this->name = $rr['name']; - $this->type = Net_DNS2_Lookups::$rr_types_by_id[$rr['type']]; - - // - // for RR OPT (41), the class value includes the requesters UDP payload size, - // and not a class value - // - if ($this->type == 'OPT') { - $this->class = $rr['class']; - } else { - $this->class = Net_DNS2_Lookups::$classes_by_id[$rr['class']]; - } - - $this->ttl = $rr['ttl']; - $this->rdlength = $rr['rdlength']; - $this->rdata = substr($packet->rdata, $packet->offset, $rr['rdlength']); - - return $this->rrSet($packet); - } - - /** - * returns a binary packed DNS RR object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for - * compressing names - * - * @return string - * @throws Net_DNS2_Exception - * @access public - * - */ - public function get(Net_DNS2_Packet &$packet) - { - $data = ''; - $rdata = ''; - - // - // pack the name - // - $data = $packet->compress($this->name, $packet->offset); - - // - // pack the main values - // - if ($this->type == 'OPT') { - - // - // pre-build the TTL value - // - $this->preBuild(); - - // - // the class value is different for OPT types - // - $data .= pack( - 'nnN', - Net_DNS2_Lookups::$rr_types_by_name[$this->type], - $this->class, - $this->ttl - ); - } else { - - $data .= pack( - 'nnN', - Net_DNS2_Lookups::$rr_types_by_name[$this->type], - Net_DNS2_Lookups::$classes_by_name[$this->class], - $this->ttl - ); - } - - // - // increase the offset, and allow for the rdlength - // - $packet->offset += 10; - - // - // get the RR specific details - // - if ($this->rdlength != -1) { - - $rdata = $this->rrGet($packet); - } - - // - // add the RR - // - $data .= pack('n', strlen($rdata)) . $rdata; - - return $data; - } - - /** - * parses a binary packet, and returns the appropriate Net_DNS2_RR object, - * based on the RR type of the binary content. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for - * decompressing names - * - * @return mixed returns a new Net_DNS2_RR_* object for - * the given RR - * @throws Net_DNS2_Exception - * @access public - * - */ - public static function parse(Net_DNS2_Packet &$packet) - { - $object = []; - - // - // expand the name - // - $object['name'] = $packet->expand($packet, $packet->offset); - if (is_null($object['name'])) { - - throw new Net_DNS2_Exception( - 'failed to parse resource record: failed to expand name.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - if ($packet->rdlength < ($packet->offset + 10)) { - - throw new Net_DNS2_Exception( - 'failed to parse resource record: packet too small.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - // - // unpack the RR details - // - $object['type'] = ord($packet->rdata[$packet->offset++]) << 8 | - ord($packet->rdata[$packet->offset++]); - $object['class'] = ord($packet->rdata[$packet->offset++]) << 8 | - ord($packet->rdata[$packet->offset++]); - - $object['ttl'] = ord($packet->rdata[$packet->offset++]) << 24 | - ord($packet->rdata[$packet->offset++]) << 16 | - ord($packet->rdata[$packet->offset++]) << 8 | - ord($packet->rdata[$packet->offset++]); - - $object['rdlength'] = ord($packet->rdata[$packet->offset++]) << 8 | - ord($packet->rdata[$packet->offset++]); - - if ($packet->rdlength < ($packet->offset + $object['rdlength'])) { - return null; - } - - // - // lookup the class to use - // - $o = null; - $class = Net_DNS2_Lookups::$rr_types_id_to_class[$object['type']]; - - if (isset($class)) { - - $o = new $class($packet, $object); - if ($o) { - - $packet->offset += $object['rdlength']; - } - } else { - - throw new Net_DNS2_Exception( - 'un-implemented resource record type: ' . $object['type'], - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - return $o; - } - - /** - * cleans up some RR data - * - * @param string $data the text string to clean - * - * @return string returns the cleaned string - * - * @access public - * - */ - public function cleanString($data) - { - return strtolower(rtrim($data, '.')); - } - - /** - * parses a standard RR format lines, as defined by rfc1035 (kinda) - * - * In our implementation, the domain *must* be specified- format must be - * - * [] [] - * or - * [] [] - * - * name, title, class and type are parsed by this function, rdata is passed - * to the RR specific classes for parsing. - * - * @param string $line a standard DNS config line - * - * @return mixed returns a new Net_DNS2_RR_* object for the given RR - * @throws Net_DNS2_Exception - * @access public - * - */ - public static function fromString($line) - { - if (strlen($line) == 0) { - throw new Net_DNS2_Exception( - 'empty config line provided.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - $name = ''; - $type = ''; - $class = 'IN'; - $ttl = 86400; - - // - // split the line by spaces - // - $values = preg_split('/[\s]+/', $line); - if (cacti_sizeof($values) < 3) { - - throw new Net_DNS2_Exception( - 'failed to parse config: minimum of name, type and rdata required.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - // - // assume the first value is the name - // - $name = trim(strtolower(array_shift($values)), '.'); - - // - // The next value is either a TTL, Class or Type - // - foreach ($values as $value) { - - switch(true) { - case is_numeric($value): - - $ttl = array_shift($values); - break; - - // - // this is here because of a bug in is_numeric() in certain versions of - // PHP on windows. - // - case ($value === 0): - - $ttl = array_shift($values); - break; - - case isset(Net_DNS2_Lookups::$classes_by_name[strtoupper($value)]): - - $class = strtoupper(array_shift($values)); - break; - - case isset(Net_DNS2_Lookups::$rr_types_by_name[strtoupper($value)]): - - $type = strtoupper(array_shift($values)); - break 2; - break; - - default: - - throw new Net_DNS2_Exception( - 'invalid config line provided: unknown file: ' . $value, - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - } - - // - // lookup the class to use - // - $o = null; - $class_name = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - - if (isset($class_name)) { - - $o = new $class_name; - if (!is_null($o)) { - - // - // set the parsed values - // - $o->name = $name; - $o->class = $class; - $o->ttl = $ttl; - - // - // parse the rdata - // - if ($o->rrFromString($values) === false) { - - throw new Net_DNS2_Exception( - 'failed to parse rdata for config: ' . $line, - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - } else { - - throw new Net_DNS2_Exception( - 'failed to create new RR record for type: ' . $type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - } else { - - throw new Net_DNS2_Exception( - 'un-implemented resource record type: '. $type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - return $o; - } + // The name of the resource record + public $name; + + // The resource record type + public $type; + + // The resource record class + public $class; + + // The time to live for this resource record + public $ttl; + + // The length of the rdata field + public $rdlength; + + // The resource record specific data as a packed binary string + public $rdata; + + /** + * Constructor - builds a new Net_DNS2_RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create + * an empty object + * @param array $rr an array with RR parse values or null to + * create an empty object + * + * @throws Net_DNS2_Exception + */ + public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) + { + if ((!is_null($packet)) && (!is_null($rr))) { + if (false == $this->set($packet, $rr)) { + throw new Net_DNS2_Exception( + 'failed to generate resource record', + Net_DNS2_Lookups::E_RR_INVALID + ); + } + } else { + $class = Net_DNS2_Lookups::$rr_types_class_to_id[get_class($this)]; + if (isset($class)) { + $this->type = Net_DNS2_Lookups::$rr_types_by_id[$class]; + } + + $this->class = 'IN'; + $this->ttl = 86400; + } + } + + /** + * magic __toString() method to return the Net_DNS2_RR object object as a string. + * + * @return string + */ + public function __toString() + { + return $this->name.'. '.$this->ttl.' '.$this->class + .' '.$this->type.' '.$this->rrToString(); + } + + /** + * return the same data as __toString(), but as an array, so each value can be + * used without having to parse the string. + * + * @return array + */ + public function asArray() + { + return [ + 'name' => $this->name, + 'ttl' => $this->ttl, + 'class' => $this->class, + 'type' => $this->type, + 'rdata' => $this->rrToString(), + ]; + } + + /** + * builds a new Net_DNS2_RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create + * an empty object + * @param array $rr an array with RR parse values or null to + * create an empty object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function set(Net_DNS2_Packet &$packet, array $rr) + { + $this->name = $rr['name']; + $this->type = Net_DNS2_Lookups::$rr_types_by_id[$rr['type']]; + + // + // for RR OPT (41), the class value includes the requesters UDP payload size, + // and not a class value + // + if ('OPT' == $this->type) { + $this->class = $rr['class']; + } else { + $this->class = Net_DNS2_Lookups::$classes_by_id[$rr['class']]; + } + + $this->ttl = $rr['ttl']; + $this->rdlength = $rr['rdlength']; + $this->rdata = substr($packet->rdata, $packet->offset, $rr['rdlength']); + + return $this->rrSet($packet); + } + + /** + * returns a binary packed DNS RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for + * compressing names + * + * @return string + * + * @throws Net_DNS2_Exception + */ + public function get(Net_DNS2_Packet &$packet) + { + $data = ''; + $rdata = ''; + + // + // pack the name + // + $data = $packet->compress($this->name, $packet->offset); + + // + // pack the main values + // + if ('OPT' == $this->type) { + // + // pre-build the TTL value + // + $this->preBuild(); + + // + // the class value is different for OPT types + // + $data .= pack( + 'nnN', + Net_DNS2_Lookups::$rr_types_by_name[$this->type], + $this->class, + $this->ttl + ); + } else { + $data .= pack( + 'nnN', + Net_DNS2_Lookups::$rr_types_by_name[$this->type], + Net_DNS2_Lookups::$classes_by_name[$this->class], + $this->ttl + ); + } + + // + // increase the offset, and allow for the rdlength + // + $packet->offset += 10; + + // + // get the RR specific details + // + if (-1 != $this->rdlength) { + $rdata = $this->rrGet($packet); + } + + // + // add the RR + // + $data .= pack('n', strlen($rdata)).$rdata; + + return $data; + } + + /** + * parses a binary packet, and returns the appropriate Net_DNS2_RR object, + * based on the RR type of the binary content. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for + * decompressing names + * + * @return mixed returns a new Net_DNS2_RR_* object for + * the given RR + * + * @throws Net_DNS2_Exception + */ + public static function parse(Net_DNS2_Packet &$packet) + { + $object = []; + + // + // expand the name + // + $object['name'] = $packet->expand($packet, $packet->offset); + if (is_null($object['name'])) { + throw new Net_DNS2_Exception( + 'failed to parse resource record: failed to expand name.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + if ($packet->rdlength < ($packet->offset + 10)) { + throw new Net_DNS2_Exception( + 'failed to parse resource record: packet too small.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + // + // unpack the RR details + // + $object['type'] = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + $object['class'] = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + $object['ttl'] = ord($packet->rdata[$packet->offset++]) << 24 + | ord($packet->rdata[$packet->offset++]) << 16 + | ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + $object['rdlength'] = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + if ($packet->rdlength < ($packet->offset + $object['rdlength'])) { + return null; + } + + // + // lookup the class to use + // + $o = null; + $class = Net_DNS2_Lookups::$rr_types_id_to_class[$object['type']]; + + if (isset($class)) { + $o = new $class($packet, $object); + if ($o) { + $packet->offset += $object['rdlength']; + } + } else { + throw new Net_DNS2_Exception( + 'un-implemented resource record type: '.$object['type'], + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + return $o; + } + + /** + * cleans up some RR data. + * + * @param string $data the text string to clean + * + * @return string returns the cleaned string + */ + public function cleanString($data) + { + return strtolower(rtrim($data, '.')); + } + + /** + * parses a standard RR format lines, as defined by rfc1035 (kinda). + * + * In our implementation, the domain *must* be specified- format must be + * + * [] [] + * or + * [] [] + * + * name, title, class and type are parsed by this function, rdata is passed + * to the RR specific classes for parsing. + * + * @param string $line a standard DNS config line + * + * @return mixed returns a new Net_DNS2_RR_* object for the given RR + * + * @throws Net_DNS2_Exception + */ + public static function fromString($line) + { + if (0 == strlen($line)) { + throw new Net_DNS2_Exception( + 'empty config line provided.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + $name = ''; + $type = ''; + $class = 'IN'; + $ttl = 86400; + + // + // split the line by spaces + // + $values = preg_split('/[\s]+/', $line); + if (cacti_sizeof($values) < 3) { + throw new Net_DNS2_Exception( + 'failed to parse config: minimum of name, type and rdata required.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + // + // assume the first value is the name + // + $name = trim(strtolower(array_shift($values)), '.'); + + // + // The next value is either a TTL, Class or Type + // + foreach ($values as $value) { + switch (true) { + case is_numeric($value): + $ttl = array_shift($values); + + break; + + // + // this is here because of a bug in is_numeric() in certain versions of + // PHP on windows. + // + case 0 === $value: + $ttl = array_shift($values); + + break; + + case isset(Net_DNS2_Lookups::$classes_by_name[strtoupper($value)]): + $class = strtoupper(array_shift($values)); + + break; + + case isset(Net_DNS2_Lookups::$rr_types_by_name[strtoupper($value)]): + $type = strtoupper(array_shift($values)); + + break 2; + + break; + + default: + throw new Net_DNS2_Exception( + 'invalid config line provided: unknown file: '.$value, + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + } + + // + // lookup the class to use + // + $o = null; + $class_name = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + + if (isset($class_name)) { + $o = new $class_name(); + if (!is_null($o)) { + // + // set the parsed values + // + $o->name = $name; + $o->class = $class; + $o->ttl = $ttl; + + // + // parse the rdata + // + if (false === $o->rrFromString($values)) { + throw new Net_DNS2_Exception( + 'failed to parse rdata for config: '.$line, + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + } else { + throw new Net_DNS2_Exception( + 'failed to create new RR record for type: '.$type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + } else { + throw new Net_DNS2_Exception( + 'un-implemented resource record type: '.$type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + return $o; + } + + /** + * abstract definition - method to return a RR as a string; not to + * be confused with the __toString() magic method. + * + * @return string + */ + abstract protected function rrToString(); + + /** + * abstract definition - parses a RR from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + abstract protected function rrFromString(array $rdata); + + /** + * abstract definition - sets a Net_DNS2_RR from a Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + abstract protected function rrSet(Net_DNS2_Packet &$packet); + + /** + * abstract definition - returns a binary packet DNS RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed string or + * null on failure + */ + abstract protected function rrGet(Net_DNS2_Packet &$packet); + + /** + * return a formatted string; if a string has spaces in it, then return + * it with double quotes around it, otherwise, return it as it was passed in. + * + * @param string $string the string to format + * + * @return string + */ + protected function formatString($string) + { + return '"'.str_replace('"', '\"', trim($string, '"')).'"'; + } + + /** + * builds an array of strings from an array of chunks of text split by spaces. + * + * @param array $chunks an array of chunks of text split by spaces + * + * @return array + */ + protected function buildString(array $chunks) + { + $data = []; + $c = 0; + $in = false; + + foreach ($chunks as $r) { + $r = trim($r); + if (0 == strlen($r)) { + continue; + } + + if (('"' == $r[0]) + && ('"' == $r[strlen($r) - 1]) + && ('\\' != $r[strlen($r) - 2]) + ) { + $data[$c] = $r; + ++$c; + $in = false; + } elseif ('"' == $r[0]) { + $data[$c] = $r; + $in = true; + } elseif (('"' == $r[strlen($r) - 1]) + && ('\\' != $r[strlen($r) - 2]) + ) { + $data[$c] .= ' '.$r; + ++$c; + $in = false; + } else { + if (true == $in) { + $data[$c] .= ' '.$r; + } else { + $data[$c++] = $r; + } + } + } + + foreach ($data as $index => $string) { + $data[$index] = str_replace('\"', '"', trim($string, '"')); + } + + return $data; + } } diff --git a/Net/DNS2/RR/A.php b/Net/DNS2/RR/A.php index 020cd42e..c40f1944 100644 --- a/Net/DNS2/RR/A.php +++ b/Net/DNS2/RR/A.php @@ -1,43 +1,38 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * A Resource Record - RFC1035 section 3.4.1 + * A Resource Record - RFC1035 section 3.4.1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | ADDRESS | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_A extends Net_DNS2_RR { - /* - * The IPv4 address in quad-dotted notation - */ + // The IPv4 address in quad-dotted notation public $address; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -45,21 +40,19 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $value = array_shift($rdata); - if (Net_DNS2::isIPv4($value) == true) { - + if (true == Net_DNS2::isIPv4($value)) { $this->address = $value; + return true; } @@ -67,21 +60,17 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $this->address = inet_ntop($this->rdata); - if ($this->address !== false) { - + if (false !== $this->address) { return true; } } @@ -90,19 +79,18 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet - * + * returns the rdata portion of the DNS packet. + * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { $packet->offset += 4; + return inet_pton($this->address); } } diff --git a/Net/DNS2/RR/AAAA.php b/Net/DNS2/RR/AAAA.php index de488f03..e8599acb 100644 --- a/Net/DNS2/RR/AAAA.php +++ b/Net/DNS2/RR/AAAA.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * A Resource Record - RFC1035 section 3.4.1 + * A Resource Record - RFC1035 section 3.4.1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | | @@ -30,100 +30,91 @@ * | | * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_AAAA extends Net_DNS2_RR { - /* - * the IPv6 address in the preferred hexadecimal values of the eight - * 16-bit pieces - * per RFC1884 - * - */ - public $address; + /* + * the IPv6 address in the preferred hexadecimal values of the eight + * 16-bit pieces + * per RFC1884 + * + */ + public $address; - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->address; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->address; + } - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - // - // expand out compressed formats - // - $value = array_shift($rdata); - if (Net_DNS2::isIPv6($value) == true) { + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + // + // expand out compressed formats + // + $value = array_shift($rdata); + if (true == Net_DNS2::isIPv6($value)) { + $this->address = $value; - $this->address = $value; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - // - // must be 8 x 16bit chunks, or 16 x 8bit - // - if ($this->rdlength == 16) { + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + // + // must be 8 x 16bit chunks, or 16 x 8bit + // + if (16 == $this->rdlength) { + // + // PHP's inet_ntop returns IPv6 addresses in their compressed form, + // but we want to keep with the preferred standard, so we'll parse + // it manually. + // + $x = unpack('n8', $this->rdata); + if (8 == cacti_sizeof($x)) { + $this->address = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $x); - // - // PHP's inet_ntop returns IPv6 addresses in their compressed form, - // but we want to keep with the preferred standard, so we'll parse - // it manually. - // - $x = unpack('n8', $this->rdata); - if (cacti_sizeof($x) == 8) { + return true; + } + } - $this->address = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $x); - return true; - } - } + return false; + } - return false; - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + $packet->offset += 16; - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $packet->offset += 16; - return inet_pton($this->address); - } + return inet_pton($this->address); + } } diff --git a/Net/DNS2/RR/AFSDB.php b/Net/DNS2/RR/AFSDB.php index a4e4fe12..e726ad07 100644 --- a/Net/DNS2/RR/AFSDB.php +++ b/Net/DNS2/RR/AFSDB.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * AFSDB Resource Record - RFC1183 section 1 + * AFSDB Resource Record - RFC1183 section 1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | SUBTYPE | @@ -26,69 +26,57 @@ * / HOSTNAME / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_AFSDB extends Net_DNS2_RR { - /* - * The AFSDB sub type - */ + // The AFSDB sub type public $subtype; - /* - * The AFSDB hostname - */ + // The AFSDB hostname public $hostname; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->subtype . ' ' . $this->cleanString($this->hostname) . '.'; + return $this->subtype.' '.$this->cleanString($this->hostname).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->subtype = array_shift($rdata); + $this->subtype = array_shift($rdata); $this->hostname = $this->cleanString(array_shift($rdata)); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the subtype // $x = unpack('nsubtype', $this->rdata); - $this->subtype = $x['subtype']; - $offset = $packet->offset + 2; + $this->subtype = $x['subtype']; + $offset = $packet->offset + 2; $this->hostname = Net_DNS2_Packet::expand($packet, $offset); @@ -99,28 +87,25 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->hostname) > 0) { - $data = pack('n', $this->subtype); $packet->offset += 2; - + $data .= $packet->compress($this->hostname, $packet->offset); return $data; } - - return null; + + return null; } } diff --git a/Net/DNS2/RR/AMTRELAY.php b/Net/DNS2/RR/AMTRELAY.php index db4cf1c0..85019bcd 100644 --- a/Net/DNS2/RR/AMTRELAY.php +++ b/Net/DNS2/RR/AMTRELAY.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.4.5 * + * @see https://netdns2.com/ + * @since File available since Release 1.4.5 */ /** - * AMTRELAY Resource Record - RFC8777 section 4.2 + * AMTRELAY Resource Record - RFC8777 section 4.2. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -26,234 +26,217 @@ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * ~ relay ~ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_AMTRELAY extends Net_DNS2_RR { - /* - * type definitions that match the "type" field below - */ - const AMTRELAY_TYPE_NONE = 0; - const AMTRELAY_TYPE_IPV4 = 1; - const AMTRELAY_TYPE_IPV6 = 2; - const AMTRELAY_TYPE_DOMAIN = 3; - - /* - * the precedence for this record - */ - public $precedence; - - /* - * "Discovery Optional" flag - */ - public $discovery; - - /* - * The type field indicates the format of the information that is stored in the relay field. - */ - public $relay_type; - - /* - * The relay field is the address or domain name of the AMT relay. - */ - public $relay; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - $out = $this->precedence . ' ' . $this->discovery . ' ' . $this->relay_type . ' ' . $this->relay; - - // - // 4.3.1 - If the relay type field is 0, the relay field MUST be ".". - // - if ( ($this->relay_type == self::AMTRELAY_TYPE_NONE) || ($this->relay_type == self::AMTRELAY_TYPE_DOMAIN) ) - { - $out .= '.'; - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - // - // extract the values from the array - // - $this->precedence = array_shift($rdata); - $this->discovery = array_shift($rdata); - $this->relay_type = array_shift($rdata); - $this->relay = trim(strtolower(trim(array_shift($rdata))), '.'); - - // - // if there's anything else other than 0 in the discovery value, then force it to one, so - // that it effectively is either "true" or "false". - // - if ($this->discovery != 0) { - $this->discovery = 1; - } - - // - // validate the type & relay values - // - switch($this->relay_type) { - case self::AMTRELAY_TYPE_NONE: - $this->relay = ''; - break; - - case self::AMTRELAY_TYPE_IPV4: - if (Net_DNS2::isIPv4($this->relay) == false) { - return false; - } - break; - - case self::AMTRELAY_TYPE_IPV6: - if (Net_DNS2::isIPv6($this->relay) == false) { - return false; - } - break; - - case self::AMTRELAY_TYPE_DOMAIN: - ; // do nothing - break; - - default: - - // - // invalid type value - // - return false; - - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - // - // parse off the first two octets - // - $x = unpack('Cprecedence/Csecond', $this->rdata); - - $this->precedence = $x['precedence']; - $this->discovery = ($x['second'] >> 7) & 0x1; - $this->relay_type = $x['second'] & 0xf; - - $offset = 2; - - // - // parse the relay value based on the type - // - switch($this->relay_type) { - case self::AMTRELAY_TYPE_NONE: - $this->relay = ''; - break; - - case self::AMTRELAY_TYPE_IPV4: - $this->relay = inet_ntop(substr($this->rdata, $offset, 4)); - break; - - case self::AMTRELAY_TYPE_IPV6: - - // - // PHP's inet_ntop returns IPv6 addresses in their compressed form, but we want to keep - // with the preferred standard, so we'll parse it manually. - // - $ip = unpack('n8', substr($this->rdata, $offset, 16)); - if (cacti_sizeof($ip) == 8) { - $this->relay = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); - } else - { - return false; - } - break; - - case self::AMTRELAY_TYPE_DOMAIN: - $doffset = $packet->offset + $offset; - $this->relay = Net_DNS2_Packet::label($packet, $doffset); - - break; - - default: - // - // invalid type value - // - return false; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // pack the precedence, discovery, and type - // - $data = pack('CC', $this->precedence, ($this->discovery << 7) | $this->relay_type); - - // - // add the relay data based on the type - // - switch($this->relay_type) { - case self::AMTRELAY_TYPE_NONE: - ; // add nothing - break; - - case self::AMTRELAY_TYPE_IPV4: - case self::AMTRELAY_TYPE_IPV6: - $data .= inet_pton($this->relay); - break; - - case self::AMTRELAY_TYPE_DOMAIN: - $data .= pack('Ca*', strlen($this->relay), $this->relay); - break; - - default: - return null; - } - - $packet->offset += strlen($data); - - return $data; - } + // type definitions that match the "type" field below + public const AMTRELAY_TYPE_NONE = 0; + public const AMTRELAY_TYPE_IPV4 = 1; + public const AMTRELAY_TYPE_IPV6 = 2; + public const AMTRELAY_TYPE_DOMAIN = 3; + + // the precedence for this record + public $precedence; + + // "Discovery Optional" flag + public $discovery; + + // The type field indicates the format of the information that is stored in the relay field. + public $relay_type; + + // The relay field is the address or domain name of the AMT relay. + public $relay; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + $out = $this->precedence.' '.$this->discovery.' '.$this->relay_type.' '.$this->relay; + + // + // 4.3.1 - If the relay type field is 0, the relay field MUST be ".". + // + if ((self::AMTRELAY_TYPE_NONE == $this->relay_type) || (self::AMTRELAY_TYPE_DOMAIN == $this->relay_type)) { + $out .= '.'; + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + // + // extract the values from the array + // + $this->precedence = array_shift($rdata); + $this->discovery = array_shift($rdata); + $this->relay_type = array_shift($rdata); + $this->relay = trim(strtolower(trim(array_shift($rdata))), '.'); + + // + // if there's anything else other than 0 in the discovery value, then force it to one, so + // that it effectively is either "true" or "false". + // + if (0 != $this->discovery) { + $this->discovery = 1; + } + + // + // validate the type & relay values + // + switch ($this->relay_type) { + case self::AMTRELAY_TYPE_NONE: + $this->relay = ''; + + break; + + case self::AMTRELAY_TYPE_IPV4: + if (false == Net_DNS2::isIPv4($this->relay)) { + return false; + } + + break; + + case self::AMTRELAY_TYPE_IPV6: + if (false == Net_DNS2::isIPv6($this->relay)) { + return false; + } + + break; + + case self::AMTRELAY_TYPE_DOMAIN:; // do nothing + + break; + + default: + // + // invalid type value + // + return false; + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + // + // parse off the first two octets + // + $x = unpack('Cprecedence/Csecond', $this->rdata); + + $this->precedence = $x['precedence']; + $this->discovery = ($x['second'] >> 7) & 0x1; + $this->relay_type = $x['second'] & 0xF; + + $offset = 2; + + // + // parse the relay value based on the type + // + switch ($this->relay_type) { + case self::AMTRELAY_TYPE_NONE: + $this->relay = ''; + + break; + + case self::AMTRELAY_TYPE_IPV4: + $this->relay = inet_ntop(substr($this->rdata, $offset, 4)); + + break; + + case self::AMTRELAY_TYPE_IPV6: + // + // PHP's inet_ntop returns IPv6 addresses in their compressed form, but we want to keep + // with the preferred standard, so we'll parse it manually. + // + $ip = unpack('n8', substr($this->rdata, $offset, 16)); + if (8 == cacti_sizeof($ip)) { + $this->relay = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); + } else { + return false; + } + + break; + + case self::AMTRELAY_TYPE_DOMAIN: + $doffset = $packet->offset + $offset; + $this->relay = Net_DNS2_Packet::label($packet, $doffset); + + break; + + default: + // + // invalid type value + // + return false; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + // + // pack the precedence, discovery, and type + // + $data = pack('CC', $this->precedence, ($this->discovery << 7) | $this->relay_type); + + // + // add the relay data based on the type + // + switch ($this->relay_type) { + case self::AMTRELAY_TYPE_NONE:; // add nothing + + break; + + case self::AMTRELAY_TYPE_IPV4: + case self::AMTRELAY_TYPE_IPV6: + $data .= inet_pton($this->relay); + + break; + + case self::AMTRELAY_TYPE_DOMAIN: + $data .= pack('Ca*', strlen($this->relay), $this->relay); + + break; + + default: + return null; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/ANY.php b/Net/DNS2/RR/ANY.php index 3dc603db..95927f1a 100644 --- a/Net/DNS2/RR/ANY.php +++ b/Net/DNS2/RR/ANY.php @@ -1,34 +1,31 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * This is only used for generating an empty ANY RR. - * */ class Net_DNS2_RR_ANY extends Net_DNS2_RR { /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -36,13 +33,11 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -50,13 +45,11 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { @@ -64,15 +57,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { diff --git a/Net/DNS2/RR/APL.php b/Net/DNS2/RR/APL.php index f54da571..7b792324 100644 --- a/Net/DNS2/RR/APL.php +++ b/Net/DNS2/RR/APL.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.0.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.0.0 */ /** - * APL Resource Record - RFC3123 + * APL Resource Record - RFC3123. * * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * | ADDRESSFAMILY | @@ -28,268 +28,262 @@ * / AFDPART / * | | * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - * */ class Net_DNS2_RR_APL extends Net_DNS2_RR { - /* - * a list of all the address prefix list items - */ - public $apl_items = []; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - $out = ''; - - foreach ($this->apl_items as $item) { - - if ($item['n'] == 1) { - - $out .= '!'; - } - - $out .= $item['address_family'] . ':' . - $item['afd_part'] . '/' . $item['prefix'] . ' '; - } - - return trim($out); - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - foreach ($rdata as $item) { - - if (preg_match('/^(!?)([1|2])\:([^\/]*)\/([0-9]{1,3})$/', $item, $m)) { - - $i = [ - - 'address_family' => $m[2], - 'prefix' => $m[4], - 'n' => ($m[1] == '!') ? 1 : 0, - 'afd_part' => strtolower($m[3]) - ]; - - $address = $this->_trimZeros( - $i['address_family'], $i['afd_part'] - ); - - $i['afd_length'] = cacti_sizeof(explode('.', $address)); - - $this->apl_items[] = $i; - } - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - $offset = 0; - - while ($offset < $this->rdlength) { - - // - // unpack the family, prefix, negate and length values - // - $x = unpack( - 'naddress_family/Cprefix/Cextra', substr($this->rdata, $offset) - ); - - $item = [ - - 'address_family' => $x['address_family'], - 'prefix' => $x['prefix'], - 'n' => ($x['extra'] >> 7) & 0x1, - 'afd_length' => $x['extra'] & 0xf - ]; - - switch($item['address_family']) { - - case 1: - $r = unpack( - 'C*', substr($this->rdata, $offset + 4, $item['afd_length']) - ); - if (cacti_sizeof($r) < 4) { - - for ($c=cacti_sizeof($r)+1; $c<4+1; $c++) { - - $r[$c] = 0; - } - } - - $item['afd_part'] = implode('.', $r); - - break; - case 2: - $r = unpack( - 'C*', substr($this->rdata, $offset + 4, $item['afd_length']) - ); - if (cacti_sizeof($r) < 8) { - - for ($c=cacti_sizeof($r)+1; $c<8+1; $c++) { - - $r[$c] = 0; - } - } - - $item['afd_part'] = sprintf( - '%x:%x:%x:%x:%x:%x:%x:%x', - $r[1], $r[2], $r[3], $r[4], $r[5], $r[6], $r[7], $r[8] - ); - - break; - default: - return false; - } - - $this->apl_items[] = $item; - - $offset += 4 + $item['afd_length']; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (cacti_sizeof($this->apl_items) > 0) { - - $data = ''; - - foreach ($this->apl_items as $item) { - - // - // pack the address_family and prefix values - // - $data .= pack( - 'nCC', - $item['address_family'], - $item['prefix'], - ($item['n'] << 7) | $item['afd_length'] - ); - - switch($item['address_family']) { - case 1: - $address = explode( - '.', - $this->_trimZeros($item['address_family'], $item['afd_part']) - ); - - foreach ($address as $b) { - $data .= chr($b); - } - break; - case 2: - $address = explode( - ':', - $this->_trimZeros($item['address_family'], $item['afd_part']) - ); - - foreach ($address as $b) { - $data .= pack('H', $b); - } - break; - default: - return null; - } - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } - - /** - * returns an IP address with the right-hand zero's trimmed - * - * @param integer $family the IP address family from the rdata - * @param string $address the IP address - * - * @return string the trimmed IP addresss. - * - * @access private - * - */ - private function _trimZeros($family, $address) - { - $a = []; - - switch($family) { - case 1: - $a = array_reverse(explode('.', $address)); - break; - case 2: - $a = array_reverse(explode(':', $address)); - break; - default: - return ''; - } - - foreach ($a as $value) { - - if ($value === '0') { - - array_shift($a); - } - } - - $out = ''; - - switch($family) { - case 1: - $out = implode('.', array_reverse($a)); - break; - case 2: - $out = implode(':', array_reverse($a)); - break; - default: - return ''; - } - - return $out; - } + // a list of all the address prefix list items + public $apl_items = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + $out = ''; + + foreach ($this->apl_items as $item) { + if (1 == $item['n']) { + $out .= '!'; + } + + $out .= $item['address_family'].':' + .$item['afd_part'].'/'.$item['prefix'].' '; + } + + return trim($out); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + foreach ($rdata as $item) { + if (preg_match('/^(!?)([1|2])\:([^\/]*)\/([0-9]{1,3})$/', $item, $m)) { + $i = [ + 'address_family' => $m[2], + 'prefix' => $m[4], + 'n' => ('!' == $m[1]) ? 1 : 0, + 'afd_part' => strtolower($m[3]), + ]; + + $address = $this->_trimZeros( + $i['address_family'], + $i['afd_part'] + ); + + $i['afd_length'] = cacti_sizeof(explode('.', $address)); + + $this->apl_items[] = $i; + } + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $offset = 0; + + while ($offset < $this->rdlength) { + // + // unpack the family, prefix, negate and length values + // + $x = unpack( + 'naddress_family/Cprefix/Cextra', + substr($this->rdata, $offset) + ); + + $item = [ + 'address_family' => $x['address_family'], + 'prefix' => $x['prefix'], + 'n' => ($x['extra'] >> 7) & 0x1, + 'afd_length' => $x['extra'] & 0xF, + ]; + + switch ($item['address_family']) { + case 1: + $r = unpack( + 'C*', + substr($this->rdata, $offset + 4, $item['afd_length']) + ); + if (cacti_sizeof($r) < 4) { + for ($c = cacti_sizeof($r) + 1; $c < 4 + 1; ++$c) { + $r[$c] = 0; + } + } + + $item['afd_part'] = implode('.', $r); + + break; + + case 2: + $r = unpack( + 'C*', + substr($this->rdata, $offset + 4, $item['afd_length']) + ); + if (cacti_sizeof($r) < 8) { + for ($c = cacti_sizeof($r) + 1; $c < 8 + 1; ++$c) { + $r[$c] = 0; + } + } + + $item['afd_part'] = sprintf( + '%x:%x:%x:%x:%x:%x:%x:%x', + $r[1], + $r[2], + $r[3], + $r[4], + $r[5], + $r[6], + $r[7], + $r[8] + ); + + break; + + default: + return false; + } + + $this->apl_items[] = $item; + + $offset += 4 + $item['afd_length']; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if (cacti_sizeof($this->apl_items) > 0) { + $data = ''; + + foreach ($this->apl_items as $item) { + // + // pack the address_family and prefix values + // + $data .= pack( + 'nCC', + $item['address_family'], + $item['prefix'], + ($item['n'] << 7) | $item['afd_length'] + ); + + switch ($item['address_family']) { + case 1: + $address = explode( + '.', + $this->_trimZeros($item['address_family'], $item['afd_part']) + ); + + foreach ($address as $b) { + $data .= chr($b); + } + + break; + + case 2: + $address = explode( + ':', + $this->_trimZeros($item['address_family'], $item['afd_part']) + ); + + foreach ($address as $b) { + $data .= pack('H', $b); + } + + break; + + default: + return null; + } + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } + + /** + * returns an IP address with the right-hand zero's trimmed. + * + * @param int $family the IP address family from the rdata + * @param string $address the IP address + * + * @return string the trimmed IP addresss + */ + private function _trimZeros($family, $address) + { + $a = []; + + switch ($family) { + case 1: + $a = array_reverse(explode('.', $address)); + + break; + + case 2: + $a = array_reverse(explode(':', $address)); + + break; + + default: + return ''; + } + + foreach ($a as $value) { + if ('0' === $value) { + array_shift($a); + } + } + + $out = ''; + + switch ($family) { + case 1: + $out = implode('.', array_reverse($a)); + + break; + + case 2: + $out = implode(':', array_reverse($a)); + + break; + + default: + return ''; + } + + return $out; + } } diff --git a/Net/DNS2/RR/ATMA.php b/Net/DNS2/RR/ATMA.php index c8cd553d..460c08ae 100644 --- a/Net/DNS2/RR/ATMA.php +++ b/Net/DNS2/RR/ATMA.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.1.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.1.0 */ /** - * ATMA Resource Record + * ATMA Resource Record. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ @@ -27,28 +27,23 @@ * / ADDRESS / * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_ATMA extends Net_DNS2_RR { /* - * One octet that indicates the format of ADDRESS. The two possible values + * One octet that indicates the format of ADDRESS. The two possible values * for FORMAT are value 0 indicating ATM End System Address (AESA) format * and value 1 indicating E.164 format */ public $format; - /* - * The IPv4 address in quad-dotted notation - */ + // The IPv4 address in quad-dotted notation public $address; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -56,30 +51,23 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $value = array_shift($rdata); - if (ctype_xdigit($value) == true) { - - $this->format = 0; - $this->address = $value; - - } else if (is_numeric($value) == true) { - - $this->format = 1; - $this->address = $value; - + if (true == ctype_xdigit($value)) { + $this->format = 0; + $this->address = $value; + } elseif (true == is_numeric($value)) { + $this->format = 1; + $this->address = $value; } else { - return false; } @@ -87,18 +75,15 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the format // @@ -106,18 +91,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) $this->format = $x['format']; - if ($this->format == 0) { - + if (0 == $this->format) { $a = unpack('@1/H*address', $this->rdata); $this->address = $a['address']; - - } else if ($this->format == 1) { - + } elseif (1 == $this->format) { $this->address = substr($this->rdata, 1, $this->rdlength - 1); - } else { - return false; } @@ -128,35 +108,28 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet - * + * returns the rdata portion of the DNS packet. + * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { $data = chr($this->format); - if ($this->format == 0) { - + if (0 == $this->format) { $data .= pack('H*', $this->address); - - } else if ($this->format == 1) { - + } elseif (1 == $this->format) { $data .= $this->address; - } else { - return null; } $packet->offset += strlen($data); - + return $data; } } diff --git a/Net/DNS2/RR/AVC.php b/Net/DNS2/RR/AVC.php index 1e9cda76..67e1b953 100644 --- a/Net/DNS2/RR/AVC.php +++ b/Net/DNS2/RR/AVC.php @@ -1,27 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.4.2 * + * @see https://netdns2.com/ + * @since File available since Release 1.4.2 */ /** * The AVC RR is implemented exactly like the TXT record, so * for now we just extend the TXT RR and use it. - * */ -class Net_DNS2_RR_AVC extends Net_DNS2_RR_TXT -{ -} +class Net_DNS2_RR_AVC extends Net_DNS2_RR_TXT {} diff --git a/Net/DNS2/RR/CAA.php b/Net/DNS2/RR/CAA.php index bebfd2cc..d9846c8b 100644 --- a/Net/DNS2/RR/CAA.php +++ b/Net/DNS2/RR/CAA.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.0 */ /** - * CAA Resource Record - http://tools.ietf.org/html/draft-ietf-pkix-caa-03 + * CAA Resource Record - http://tools.ietf.org/html/draft-ietf-pkix-caa-03. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | FLAGS | TAG LENGTH | @@ -27,82 +27,68 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / DATA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_CAA extends Net_DNS2_RR { - /* - * The critcal flag - */ + // The critcal flag public $flags; - /* - * The property identifier - */ + // The property identifier public $tag; - /* - * The property value - */ + // The property value public $value; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->flags . ' ' . $this->tag . ' "' . - trim($this->cleanString($this->value), '"') . '"'; + return $this->flags.' '.$this->tag.' "' + .trim($this->cleanString($this->value), '"').'"'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->flags = array_shift($rdata); - $this->tag = array_shift($rdata); + $this->flags = array_shift($rdata); + $this->tag = array_shift($rdata); + + $this->value = trim($this->cleanString(implode(' ', $rdata)), '"'); - $this->value = trim($this->cleanString(implode(' ', $rdata)), '"'); - return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the flags and tag length // $x = unpack('Cflags/Ctag_length', $this->rdata); - $this->flags = $x['flags']; - $offset = 2; + $this->flags = $x['flags']; + $offset = 2; - $this->tag = substr($this->rdata, $offset, $x['tag_length']); - $offset += $x['tag_length']; + $this->tag = substr($this->rdata, $offset, $x['tag_length']); + $offset += $x['tag_length']; - $this->value = substr($this->rdata, $offset); + $this->value = substr($this->rdata, $offset); return true; } @@ -111,22 +97,19 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->value) > 0) { - - $data = chr($this->flags); - $data .= chr(strlen($this->tag)) . $this->tag . $this->value; + $data = chr($this->flags); + $data .= chr(strlen($this->tag)).$this->tag.$this->value; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/CDNSKEY.php b/Net/DNS2/RR/CDNSKEY.php index 625da062..74bcfa84 100644 --- a/Net/DNS2/RR/CDNSKEY.php +++ b/Net/DNS2/RR/CDNSKEY.php @@ -1,20 +1,20 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.4.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.4.0 */ /** @@ -22,8 +22,5 @@ * for now we just extend the DNSKEY RR and use it. * * http://www.rfc-editor.org/rfc/rfc7344.txt - * */ -class Net_DNS2_RR_CDNSKEY extends Net_DNS2_RR_DNSKEY -{ -} +class Net_DNS2_RR_CDNSKEY extends Net_DNS2_RR_DNSKEY {} diff --git a/Net/DNS2/RR/CDS.php b/Net/DNS2/RR/CDS.php index e835368a..5346649e 100644 --- a/Net/DNS2/RR/CDS.php +++ b/Net/DNS2/RR/CDS.php @@ -1,20 +1,20 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.0 */ /** @@ -22,8 +22,5 @@ * for now we just extend the DS RR and use it. * * http://www.rfc-editor.org/rfc/rfc7344.txt - * */ -class Net_DNS2_RR_CDS extends Net_DNS2_RR_DS -{ -} +class Net_DNS2_RR_CDS extends Net_DNS2_RR_DS {} diff --git a/Net/DNS2/RR/CERT.php b/Net/DNS2/RR/CERT.php index 11de6977..45e122c7 100644 --- a/Net/DNS2/RR/CERT.php +++ b/Net/DNS2/RR/CERT.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * CERT Resource Record - RFC4398 section 2 + * CERT Resource Record - RFC4398 section 2. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,59 +28,47 @@ * +---------------+ certificate or CRL / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-| - * */ class Net_DNS2_RR_CERT extends Net_DNS2_RR { - /* - * format's allowed for certificates - */ - const CERT_FORMAT_RES = 0; - const CERT_FORMAT_PKIX = 1; - const CERT_FORMAT_SPKI = 2; - const CERT_FORMAT_PGP = 3; - const CERT_FORMAT_IPKIX = 4; - const CERT_FORMAT_ISPKI = 5; - const CERT_FORMAT_IPGP = 6; - const CERT_FORMAT_ACPKIX = 7; - const CERT_FORMAT_IACPKIX = 8; - const CERT_FORMAT_URI = 253; - const CERT_FORMAT_OID = 254; + // format's allowed for certificates + public const CERT_FORMAT_RES = 0; + public const CERT_FORMAT_PKIX = 1; + public const CERT_FORMAT_SPKI = 2; + public const CERT_FORMAT_PGP = 3; + public const CERT_FORMAT_IPKIX = 4; + public const CERT_FORMAT_ISPKI = 5; + public const CERT_FORMAT_IPGP = 6; + public const CERT_FORMAT_ACPKIX = 7; + public const CERT_FORMAT_IACPKIX = 8; + public const CERT_FORMAT_URI = 253; + public const CERT_FORMAT_OID = 254; public $cert_format_name_to_id = []; public $cert_format_id_to_name = [ - - self::CERT_FORMAT_RES => 'Reserved', - self::CERT_FORMAT_PKIX => 'PKIX', - self::CERT_FORMAT_SPKI => 'SPKI', - self::CERT_FORMAT_PGP => 'PGP', - self::CERT_FORMAT_IPKIX => 'IPKIX', - self::CERT_FORMAT_ISPKI => 'ISPKI', - self::CERT_FORMAT_IPGP => 'IPGP', - self::CERT_FORMAT_ACPKIX => 'ACPKIX', - self::CERT_FORMAT_IACPKIX => 'IACPKIX', - self::CERT_FORMAT_URI => 'URI', - self::CERT_FORMAT_OID => 'OID' + self::CERT_FORMAT_RES => 'Reserved', + self::CERT_FORMAT_PKIX => 'PKIX', + self::CERT_FORMAT_SPKI => 'SPKI', + self::CERT_FORMAT_PGP => 'PGP', + self::CERT_FORMAT_IPKIX => 'IPKIX', + self::CERT_FORMAT_ISPKI => 'ISPKI', + self::CERT_FORMAT_IPGP => 'IPGP', + self::CERT_FORMAT_ACPKIX => 'ACPKIX', + self::CERT_FORMAT_IACPKIX => 'IACPKIX', + self::CERT_FORMAT_URI => 'URI', + self::CERT_FORMAT_OID => 'OID', ]; - /* - * certificate format - */ + // certificate format public $format; - /* - * key tag - */ + // key tag public $keytag; - /* - * The algorithm used for the CERt - */ + // The algorithm used for the CERt public $algorithm; - /* - * certificate - */ + // certificate public $certificate; /** @@ -89,14 +77,11 @@ class Net_DNS2_RR_CERT extends Net_DNS2_RR * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * @param array $rr a array with parsed RR values - * - * @return - * */ - public function __construct(Net_DNS2_Packet &$packet = null, array $rr = null) + public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) { parent::__construct($packet, $rr); - + // // load the lookup values // @@ -104,26 +89,22 @@ public function __construct(Net_DNS2_Packet &$packet = null, array $rr = null) } /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->format . ' ' . $this->keytag . ' ' . $this->algorithm . - ' ' . base64_encode($this->certificate); + return $this->format.' '.$this->keytag.' '.$this->algorithm + .' '.base64_encode($this->certificate); } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -132,22 +113,18 @@ protected function rrFromString(array $rdata) // $this->format = array_shift($rdata); if (!is_numeric($this->format)) { - $mnemonic = strtoupper(trim($this->format)); if (!isset($this->cert_format_name_to_id[$mnemonic])) { - return false; } $this->format = $this->cert_format_name_to_id[$mnemonic]; } else { - if (!isset($this->cert_format_id_to_name[$this->format])) { - return false; } } - + $this->keytag = array_shift($rdata); // @@ -155,10 +132,8 @@ protected function rrFromString(array $rdata) // $this->algorithm = array_shift($rdata); if (!is_numeric($this->algorithm)) { - $mnemonic = strtoupper(trim($this->algorithm)); if (!isset(Net_DNS2_Lookups::$algorithm_name_to_id[$mnemonic])) { - return false; } @@ -166,7 +141,6 @@ protected function rrFromString(array $rdata) $mnemonic ]; } else { - if (!isset(Net_DNS2_Lookups::$algorithm_id_to_name[$this->algorithm])) { return false; } @@ -184,31 +158,28 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the format, keytag and algorithm // $x = unpack('nformat/nkeytag/Calgorithm', $this->rdata); - $this->format = $x['format']; - $this->keytag = $x['keytag']; - $this->algorithm = $x['algorithm']; + $this->format = $x['format']; + $this->keytag = $x['keytag']; + $this->algorithm = $x['algorithm']; // // copy the certificate // - $this->certificate = substr($this->rdata, 5, $this->rdlength - 5); + $this->certificate = substr($this->rdata, 5, $this->rdlength - 5); return true; } @@ -217,21 +188,18 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->certificate) > 0) { - - $data = pack('nnC', $this->format, $this->keytag, $this->algorithm) . $this->certificate; + $data = pack('nnC', $this->format, $this->keytag, $this->algorithm).$this->certificate; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/CNAME.php b/Net/DNS2/RR/CNAME.php index 46c7d8b8..b1ebd63c 100644 --- a/Net/DNS2/RR/CNAME.php +++ b/Net/DNS2/RR/CNAME.php @@ -1,78 +1,69 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * CNAME Resource Record - RFC1035 section 3.3.1 + * CNAME Resource Record - RFC1035 section 3.3.1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / CNAME / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_CNAME extends Net_DNS2_RR { - /* - * The canonical name - */ + // The canonical name public $cname; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->cname) . '.'; + return $this->cleanString($this->cname).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->cname = $this->cleanString(array_shift($rdata)); + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $offset = $packet->offset; $this->cname = Net_DNS2_Packet::expand($packet, $offset); @@ -83,20 +74,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->cname) > 0) { - return $packet->compress($this->cname, $packet->offset); } diff --git a/Net/DNS2/RR/CSYNC.php b/Net/DNS2/RR/CSYNC.php index 994ae731..2782f3db 100644 --- a/Net/DNS2/RR/CSYNC.php +++ b/Net/DNS2/RR/CSYNC.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.4.1 * + * @see https://netdns2.com/ + * @since File available since Release 1.4.1 */ /** - * CSYNC Resource Record - RFC 7477 seciond 2.1.1 + * CSYNC Resource Record - RFC 7477 seciond 2.1.1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | SOA Serial | @@ -28,60 +28,48 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / Type Bit Map / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_CSYNC extends Net_DNS2_RR { - /* - * serial number - */ + // serial number public $serial; - /* - * flags - */ + // flags public $flags; - /* - * array of RR type names - */ + // array of RR type names public $type_bit_maps = []; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - $out = $this->serial . ' ' . $this->flags; + $out = $this->serial.' '.$this->flags; // // show the RR's // foreach ($this->type_bit_maps as $rr) { - - $out .= ' ' . strtoupper($rr); + $out .= ' '.strtoupper($rr); } return $out; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->serial = array_shift($rdata); - $this->flags = array_shift($rdata); + $this->serial = array_shift($rdata); + $this->flags = array_shift($rdata); $this->type_bit_maps = $rdata; @@ -89,28 +77,25 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the serial and flags values // - $x = unpack('@' . $packet->offset . '/Nserial/nflags', $packet->rdata); + $x = unpack('@'.$packet->offset.'/Nserial/nflags', $packet->rdata); - $this->serial = Net_DNS2::expandUint32($x['serial']); - $this->flags = $x['flags']; + $this->serial = Net_DNS2::expandUint32($x['serial']); + $this->flags = $x['flags']; // - // parse out the RR bitmap + // parse out the RR bitmap // $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( substr($this->rdata, 6) @@ -123,15 +108,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { diff --git a/Net/DNS2/RR/DHCID.php b/Net/DNS2/RR/DHCID.php index d42e53f6..7ff54890 100644 --- a/Net/DNS2/RR/DHCID.php +++ b/Net/DNS2/RR/DHCID.php @@ -1,60 +1,50 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * DHCID Resource Record - RFC4701 section 3.1 + * DHCID Resource Record - RFC4701 section 3.1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * | ID Type Code | + * | ID Type Code | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * | Digest Type | / + * | Digest Type | / * +--+--+--+--+--+--+--+--+ / - * / / - * / Digest / - * / / + * / / + * / Digest / + * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_DHCID extends Net_DNS2_RR { - /* - * Identifier type - */ + // Identifier type public $id_type; - /* - * Digest Type - */ + // Digest Type public $digest_type; - /* - * The digest - */ + // The digest public $digest; - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -65,26 +55,23 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $data = base64_decode(array_shift($rdata)); if (strlen($data) > 0) { - // // unpack the id type and digest type // $x = unpack('nid_type/Cdigest_type', $data); - $this->id_type = $x['id_type']; - $this->digest_type = $x['digest_type']; + $this->id_type = $x['id_type']; + $this->digest_type = $x['digest_type']; // // copy out the digest @@ -98,25 +85,22 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the id type and digest type // $x = unpack('nid_type/Cdigest_type', $this->rdata); - $this->id_type = $x['id_type']; - $this->digest_type = $x['digest_type']; + $this->id_type = $x['id_type']; + $this->digest_type = $x['digest_type']; // // copy out the digest @@ -132,28 +116,25 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->digest) > 0) { - - $data = pack('nC', $this->id_type, $this->digest_type) . - base64_decode($this->digest); + $data = pack('nC', $this->id_type, $this->digest_type) + .base64_decode($this->digest); $packet->offset += strlen($data); return $data; } - + return null; } } diff --git a/Net/DNS2/RR/DLV.php b/Net/DNS2/RR/DLV.php index bfe809da..7dbbcfbc 100644 --- a/Net/DNS2/RR/DLV.php +++ b/Net/DNS2/RR/DLV.php @@ -1,27 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * The DLV RR is implemented exactly like the DS RR; so we just extend that - * class, and use all of it's methods - * + * class, and use all of it's methods. */ -class Net_DNS2_RR_DLV extends Net_DNS2_RR_DS -{ -} +class Net_DNS2_RR_DLV extends Net_DNS2_RR_DS {} diff --git a/Net/DNS2/RR/DNAME.php b/Net/DNS2/RR/DNAME.php index 64403e62..2eb07a81 100644 --- a/Net/DNS2/RR/DNAME.php +++ b/Net/DNS2/RR/DNAME.php @@ -1,78 +1,69 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * DNAME Resource Record - RFC2672 section 3 + * DNAME Resource Record - RFC2672 section 3. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / DNAME / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_DNAME extends Net_DNS2_RR { - /* - * The target name - */ + // The target name public $dname; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->dname) . '.'; + return $this->cleanString($this->dname).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->dname = $this->cleanString(array_shift($rdata)); + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $offset = $packet->offset; $this->dname = Net_DNS2_Packet::expand($packet, $offset); @@ -83,20 +74,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->dname) > 0) { - return $packet->compress($this->dname, $packet->offset); } diff --git a/Net/DNS2/RR/DNSKEY.php b/Net/DNS2/RR/DNSKEY.php index 311ba29d..cc3fa8f8 100644 --- a/Net/DNS2/RR/DNSKEY.php +++ b/Net/DNS2/RR/DNSKEY.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * DNSKEY Resource Record - RFC4034 sction 2.1 + * DNSKEY Resource Record - RFC4034 sction 2.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,93 +28,77 @@ * / Public Key / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_DNSKEY extends Net_DNS2_RR { - /* - * flags - */ + // flags public $flags; - /* - * protocol - */ + // protocol public $protocol; - /* - * algorithm used - */ + // algorithm used public $algorithm; - /* - * the public key - */ + // the public key public $key; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->flags . ' ' . $this->protocol . ' ' . - $this->algorithm . ' ' . $this->key; + return $this->flags.' '.$this->protocol.' ' + .$this->algorithm.' '.$this->key; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->flags = array_shift($rdata); - $this->protocol = array_shift($rdata); - $this->algorithm = array_shift($rdata); - $this->key = implode(' ', $rdata); - + $this->flags = array_shift($rdata); + $this->protocol = array_shift($rdata); + $this->algorithm = array_shift($rdata); + $this->key = implode(' ', $rdata); + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the flags, protocol and algorithm // $x = unpack('nflags/Cprotocol/Calgorithm', $this->rdata); // - // TODO: right now we're just displaying what's in DNS; we really + // TODO: right now we're just displaying what's in DNS; we really // should be parsing bit 7 and bit 15 of the flags field, and store // those separately. // // right now the DNSSEC implementation is really just for display, // we don't validate or handle any of the keys // - $this->flags = $x['flags']; - $this->protocol = $x['protocol']; - $this->algorithm = $x['algorithm']; + $this->flags = $x['flags']; + $this->protocol = $x['protocol']; + $this->algorithm = $x['algorithm']; - $this->key = base64_encode(substr($this->rdata, 4)); + $this->key = base64_encode(substr($this->rdata, 4)); return true; } @@ -123,20 +107,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->key) > 0) { - $data = pack('nCC', $this->flags, $this->protocol, $this->algorithm); $data .= base64_decode($this->key); @@ -144,7 +125,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) return $data; } - + return null; } } diff --git a/Net/DNS2/RR/DS.php b/Net/DNS2/RR/DS.php index 401f4837..b4d81621 100644 --- a/Net/DNS2/RR/DS.php +++ b/Net/DNS2/RR/DS.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * DS Resource Record - RFC4034 sction 5.1 + * DS Resource Record - RFC4034 sction 5.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,83 +28,67 @@ * / Digest / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_DS extends Net_DNS2_RR { - /* - * key tag - */ + // key tag public $keytag; - /* - * algorithm number - */ + // algorithm number public $algorithm; - /* - * algorithm used to construct the digest - */ + // algorithm used to construct the digest public $digesttype; - /* - * the digest data - */ + // the digest data public $digest; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->keytag . ' ' . $this->algorithm . ' ' . $this->digesttype . ' ' . $this->digest; + return $this->keytag.' '.$this->algorithm.' '.$this->digesttype.' '.$this->digest; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->keytag = array_shift($rdata); - $this->algorithm = array_shift($rdata); - $this->digesttype = array_shift($rdata); - $this->digest = implode('', $rdata); + $this->keytag = array_shift($rdata); + $this->algorithm = array_shift($rdata); + $this->digesttype = array_shift($rdata); + $this->digest = implode('', $rdata); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the keytag, algorithm and digesttype // $x = unpack('nkeytag/Calgorithm/Cdigesttype/H*digest', $this->rdata); - $this->keytag = $x['keytag']; - $this->algorithm = $x['algorithm']; - $this->digesttype = $x['digesttype']; - $this->digest = $x['digest']; + $this->keytag = $x['keytag']; + $this->algorithm = $x['algorithm']; + $this->digesttype = $x['digesttype']; + $this->digest = $x['digest']; return true; } @@ -113,20 +97,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->digest) > 0) { - $data = pack('nCCH*', $this->keytag, $this->algorithm, $this->digesttype, $this->digest); $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/EID.php b/Net/DNS2/RR/EID.php index 13ea89fc..91466717 100644 --- a/Net/DNS2/RR/EID.php +++ b/Net/DNS2/RR/EID.php @@ -1,35 +1,32 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * EID Resource Record - undefined; the rdata is simply used as-is in it's * binary format, so not process has to be done. - * */ class Net_DNS2_RR_EID extends Net_DNS2_RR { /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -37,13 +34,11 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -51,13 +46,11 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { @@ -65,15 +58,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { diff --git a/Net/DNS2/RR/EUI48.php b/Net/DNS2/RR/EUI48.php index e66b656c..f238e003 100644 --- a/Net/DNS2/RR/EUI48.php +++ b/Net/DNS2/RR/EUI48.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.3.2 * + * @see https://netdns2.com/ + * @since File available since Release 1.3.2 */ /** - * EUI48 Resource Record - RFC7043 section 3.1 + * EUI48 Resource Record - RFC7043 section 3.1. * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 @@ -27,113 +27,100 @@ * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_EUI48 extends Net_DNS2_RR { - /* - * The EUI48 address, in hex format - */ - public $address; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->address; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $value = array_shift($rdata); - - // - // re: RFC 7043, the field must be represented as six two-digit hex numbers - // separated by hyphens. - // - $a = explode('-', $value); - if (cacti_sizeof($a) != 6) { - - return false; - } - - // - // make sure they're all hex values - // - foreach ($a as $i) { - if (ctype_xdigit($i) == false) { - return false; - } - } - - // - // store it - // - $this->address = strtolower($value); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - $x = unpack('C6', $this->rdata); - if (cacti_sizeof($x) == 6) { - - $this->address = vsprintf('%02x-%02x-%02x-%02x-%02x-%02x', $x); - return true; - } - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = ''; - - $a = explode('-', $this->address); - foreach ($a as $b) { - - $data .= chr(hexdec($b)); - } - - $packet->offset += 6; - return $data; - } + // The EUI48 address, in hex format + public $address; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->address; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $value = array_shift($rdata); + + // + // re: RFC 7043, the field must be represented as six two-digit hex numbers + // separated by hyphens. + // + $a = explode('-', $value); + if (6 != cacti_sizeof($a)) { + return false; + } + + // + // make sure they're all hex values + // + foreach ($a as $i) { + if (false == ctype_xdigit($i)) { + return false; + } + } + + // + // store it + // + $this->address = strtolower($value); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $x = unpack('C6', $this->rdata); + if (6 == cacti_sizeof($x)) { + $this->address = vsprintf('%02x-%02x-%02x-%02x-%02x-%02x', $x); + + return true; + } + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + $data = ''; + + $a = explode('-', $this->address); + foreach ($a as $b) { + $data .= chr(hexdec($b)); + } + + $packet->offset += 6; + + return $data; + } } diff --git a/Net/DNS2/RR/EUI64.php b/Net/DNS2/RR/EUI64.php index d129d23a..818aa1f5 100644 --- a/Net/DNS2/RR/EUI64.php +++ b/Net/DNS2/RR/EUI64.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.3.2 * + * @see https://netdns2.com/ + * @since File available since Release 1.3.2 */ /** - * EUI64 Resource Record - RFC7043 section 4.1 + * EUI64 Resource Record - RFC7043 section 4.1. * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 @@ -26,115 +26,103 @@ * | EUI-64 Address | * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_EUI64 extends Net_DNS2_RR { - /* - * The EUI64 address, in hex format - */ - public $address; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->address; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $value = array_shift($rdata); - - // - // re: RFC 7043, the field must be represented as 8 two-digit hex numbers - // separated by hyphens. - // - $a = explode('-', $value); - if (cacti_sizeof($a) != 8) { - - return false; - } - - // - // make sure they're all hex values - // - foreach ($a as $i) { - if (ctype_xdigit($i) == false) { - return false; - } - } - - // - // store it - // - $this->address = strtolower($value); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - $x = unpack('C8', $this->rdata); - if (cacti_sizeof($x) == 8) { - - $this->address = vsprintf( - '%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x', $x - ); - return true; - } - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = ''; - - $a = explode('-', $this->address); - foreach ($a as $b) { - - $data .= chr(hexdec($b)); - } - - $packet->offset += 8; - return $data; - } + // The EUI64 address, in hex format + public $address; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->address; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $value = array_shift($rdata); + + // + // re: RFC 7043, the field must be represented as 8 two-digit hex numbers + // separated by hyphens. + // + $a = explode('-', $value); + if (8 != cacti_sizeof($a)) { + return false; + } + + // + // make sure they're all hex values + // + foreach ($a as $i) { + if (false == ctype_xdigit($i)) { + return false; + } + } + + // + // store it + // + $this->address = strtolower($value); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $x = unpack('C8', $this->rdata); + if (8 == cacti_sizeof($x)) { + $this->address = vsprintf( + '%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x', + $x + ); + + return true; + } + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + $data = ''; + + $a = explode('-', $this->address); + foreach ($a as $b) { + $data .= chr(hexdec($b)); + } + + $packet->offset += 8; + + return $data; + } } diff --git a/Net/DNS2/RR/HINFO.php b/Net/DNS2/RR/HINFO.php index b5a7d8c6..4b3981b7 100644 --- a/Net/DNS2/RR/HINFO.php +++ b/Net/DNS2/RR/HINFO.php @@ -8,118 +8,102 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * HINFO Resource Record - RFC1035 section 3.3.2 + * HINFO Resource Record - RFC1035 section 3.3.2. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / CPU / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / OS / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_HINFO extends Net_DNS2_RR { - /* - * computer informatino - */ - public $cpu; - - /* - * operataing system - */ - public $os; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->formatString($this->cpu) . ' ' . $this->formatString($this->os); - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (cacti_sizeof($data) == 2) { - - $this->cpu = trim($data[0], '"'); - $this->os = trim($data[1], '"'); - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - $offset = $packet->offset; - - $this->cpu = Net_DNS2_Packet::label($packet, $offset); - $this->os = Net_DNS2_Packet::label($packet, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->cpu) > 0) { - - $data = pack('Ca*Ca*', strlen($this->cpu), $this->cpu, strlen($this->os), $this->os); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } + // computer informatino + public $cpu; + + // operataing system + public $os; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->formatString($this->cpu).' '.$this->formatString($this->os); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $data = $this->buildString($rdata); + if (2 == cacti_sizeof($data)) { + $this->cpu = trim($data[0], '"'); + $this->os = trim($data[1], '"'); + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $offset = $packet->offset; + + $this->cpu = Net_DNS2_Packet::label($packet, $offset); + $this->os = Net_DNS2_Packet::label($packet, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if (strlen($this->cpu) > 0) { + $data = pack('Ca*Ca*', strlen($this->cpu), $this->cpu, strlen($this->os), $this->os); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/HIP.php b/Net/DNS2/RR/HIP.php index dccc51af..317f2b48 100644 --- a/Net/DNS2/RR/HIP.php +++ b/Net/DNS2/RR/HIP.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.0.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.0.0 */ /** - * HIP Resource Record - RFC5205 section 5 + * HIP Resource Record - RFC5205 section 5. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -42,198 +42,172 @@ * + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * +-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_HIP extends Net_DNS2_RR { - /* - * The length of the HIT field - */ - public $hit_length; - - /* - * the public key cryptographic algorithm - */ - public $pk_algorithm; - - /* - * the length of the public key field - */ - public $pk_length; - - /* - * The HIT is stored as a binary value in network byte order. - */ - public $hit; - - /* - * The public key - */ - public $public_key; - - /* - * a list of rendezvous servers - */ - public $rendezvous_servers = []; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - $out = $this->pk_algorithm . ' ' . - $this->hit . ' ' . $this->public_key . ' '; - - foreach ($this->rendezvous_servers as $index => $server) { - - $out .= $server . '. '; - } - - return trim($out); - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $this->pk_algorithm = array_shift($rdata); - $this->hit = strtoupper(array_shift($rdata)); - $this->public_key = array_shift($rdata); - - // - // anything left on the array, must be one or more rendezevous servers. add - // them and strip off the trailing dot - // - if (cacti_sizeof($rdata) > 0) { - - $this->rendezvous_servers = preg_replace('/\.$/', '', $rdata); - } - - // - // store the lengths; - // - $this->hit_length = strlen(pack('H*', $this->hit)); - $this->pk_length = strlen(base64_decode($this->public_key)); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - // - // unpack the algorithm and length values - // - $x = unpack('Chit_length/Cpk_algorithm/npk_length', $this->rdata); - - $this->hit_length = $x['hit_length']; - $this->pk_algorithm = $x['pk_algorithm']; - $this->pk_length = $x['pk_length']; - - $offset = 4; - - // - // copy out the HIT value - // - $hit = unpack('H*', substr($this->rdata, $offset, $this->hit_length)); - - $this->hit = strtoupper($hit[1]); - $offset += $this->hit_length; - - // - // copy out the public key - // - $this->public_key = base64_encode( - substr($this->rdata, $offset, $this->pk_length) - ); - $offset += $this->pk_length; - - // - // copy out any possible rendezvous servers - // - $offset = $packet->offset + $offset; - - while ( ($offset - $packet->offset) < $this->rdlength) { - - $this->rendezvous_servers[] = Net_DNS2_Packet::expand( - $packet, $offset - ); - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if ( (strlen($this->hit) > 0) && (strlen($this->public_key) > 0) ) { - - // - // pack the length, algorithm and HIT values - // - $data = pack( - 'CCnH*', - $this->hit_length, - $this->pk_algorithm, - $this->pk_length, - $this->hit - ); - - // - // add the public key - // - $data .= base64_decode($this->public_key); - - // - // add the offset - // - $packet->offset += strlen($data); - - // - // add each rendezvous server - // - foreach ($this->rendezvous_servers as $index => $server) { - - $data .= $packet->compress($server, $packet->offset); - } - - return $data; - } - - return null; - } + // The length of the HIT field + public $hit_length; + + // the public key cryptographic algorithm + public $pk_algorithm; + + // the length of the public key field + public $pk_length; + + // The HIT is stored as a binary value in network byte order. + public $hit; + + // The public key + public $public_key; + + // a list of rendezvous servers + public $rendezvous_servers = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + $out = $this->pk_algorithm.' ' + .$this->hit.' '.$this->public_key.' '; + + foreach ($this->rendezvous_servers as $index => $server) { + $out .= $server.'. '; + } + + return trim($out); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $this->pk_algorithm = array_shift($rdata); + $this->hit = strtoupper(array_shift($rdata)); + $this->public_key = array_shift($rdata); + + // + // anything left on the array, must be one or more rendezevous servers. add + // them and strip off the trailing dot + // + if (cacti_sizeof($rdata) > 0) { + $this->rendezvous_servers = preg_replace('/\.$/', '', $rdata); + } + + // + // store the lengths; + // + $this->hit_length = strlen(pack('H*', $this->hit)); + $this->pk_length = strlen(base64_decode($this->public_key)); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + // + // unpack the algorithm and length values + // + $x = unpack('Chit_length/Cpk_algorithm/npk_length', $this->rdata); + + $this->hit_length = $x['hit_length']; + $this->pk_algorithm = $x['pk_algorithm']; + $this->pk_length = $x['pk_length']; + + $offset = 4; + + // + // copy out the HIT value + // + $hit = unpack('H*', substr($this->rdata, $offset, $this->hit_length)); + + $this->hit = strtoupper($hit[1]); + $offset += $this->hit_length; + + // + // copy out the public key + // + $this->public_key = base64_encode( + substr($this->rdata, $offset, $this->pk_length) + ); + $offset += $this->pk_length; + + // + // copy out any possible rendezvous servers + // + $offset = $packet->offset + $offset; + + while (($offset - $packet->offset) < $this->rdlength) { + $this->rendezvous_servers[] = Net_DNS2_Packet::expand( + $packet, + $offset + ); + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if ((strlen($this->hit) > 0) && (strlen($this->public_key) > 0)) { + // + // pack the length, algorithm and HIT values + // + $data = pack( + 'CCnH*', + $this->hit_length, + $this->pk_algorithm, + $this->pk_length, + $this->hit + ); + + // + // add the public key + // + $data .= base64_decode($this->public_key); + + // + // add the offset + // + $packet->offset += strlen($data); + + // + // add each rendezvous server + // + foreach ($this->rendezvous_servers as $index => $server) { + $data .= $packet->compress($server, $packet->offset); + } + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/IPSECKEY.php b/Net/DNS2/RR/IPSECKEY.php index ae270231..b4b514c3 100644 --- a/Net/DNS2/RR/IPSECKEY.php +++ b/Net/DNS2/RR/IPSECKEY.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * IPSECKEY Resource Record - RFC4025 section 2.1 + * IPSECKEY Resource Record - RFC4025 section 2.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -30,309 +30,310 @@ * / public key / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-| - * */ class Net_DNS2_RR_IPSECKEY extends Net_DNS2_RR { - const GATEWAY_TYPE_NONE = 0; - const GATEWAY_TYPE_IPV4 = 1; - const GATEWAY_TYPE_IPV6 = 2; - const GATEWAY_TYPE_DOMAIN = 3; - - const ALGORITHM_NONE = 0; - const ALGORITHM_DSA = 1; - const ALGORITHM_RSA = 2; - - /* - * Precedence (used the same was as a preference field) - */ - public $precedence; - - /* - * Gateway type - specifies the format of the gataway information - * This can be either: - * - * 0 No Gateway - * 1 IPv4 address - * 2 IPV6 address - * 3 wire-encoded domain name (not compressed) - * - */ - public $gateway_type; - - /* - * The algorithm used - * - * This can be: - * - * 0 No key is present - * 1 DSA key is present - * 2 RSA key is present - * - */ - public $algorithm; - - /* - * The gatway information - */ - public $gateway; - - /* - * the public key - */ - public $key; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - $out = $this->precedence . ' ' . $this->gateway_type . ' ' . - $this->algorithm . ' '; - - switch($this->gateway_type) { - case self::GATEWAY_TYPE_NONE: - $out .= '. '; - break; - - case self::GATEWAY_TYPE_IPV4: - case self::GATEWAY_TYPE_IPV6: - $out .= $this->gateway . ' '; - break; - - case self::GATEWAY_TYPE_DOMAIN: - $out .= $this->gateway . '. '; - break; - } - - $out .= $this->key; - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - // - // load the data - // - $precedence = array_shift($rdata); - $gateway_type = array_shift($rdata); - $algorithm = array_shift($rdata); - $gateway = trim(strtolower(trim(array_shift($rdata))), '.'); - $key = array_shift($rdata); - - // - // validate it - // - switch($gateway_type) { - case self::GATEWAY_TYPE_NONE: - $gateway = ''; - break; - - case self::GATEWAY_TYPE_IPV4: - if (Net_DNS2::isIPv4($gateway) == false) { - return false; - } - break; - - case self::GATEWAY_TYPE_IPV6: - if (Net_DNS2::isIPv6($gateway) == false) { - return false; - } - break; - - case self::GATEWAY_TYPE_DOMAIN: - ; // do nothing - break; - - default: - return false; - } - - // - // check the algorithm and key - // - switch($algorithm) { - case self::ALGORITHM_NONE: - $key = ''; - break; - - case self::ALGORITHM_DSA: - case self::ALGORITHM_RSA: - ; // do nothing - break; - - default: - return false; - } - - // - // store the values - // - $this->precedence = $precedence; - $this->gateway_type = $gateway_type; - $this->algorithm = $algorithm; - $this->gateway = $gateway; - $this->key = $key; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - // - // parse off the precedence, gateway type and algorithm - // - $x = unpack('Cprecedence/Cgateway_type/Calgorithm', $this->rdata); - - $this->precedence = $x['precedence']; - $this->gateway_type = $x['gateway_type']; - $this->algorithm = $x['algorithm']; - - $offset = 3; - - // - // extract the gatway based on the type - // - switch($this->gateway_type) { - case self::GATEWAY_TYPE_NONE: - $this->gateway = ''; - break; - - case self::GATEWAY_TYPE_IPV4: - $this->gateway = inet_ntop(substr($this->rdata, $offset, 4)); - $offset += 4; - break; - - case self::GATEWAY_TYPE_IPV6: - $ip = unpack('n8', substr($this->rdata, $offset, 16)); - if (cacti_sizeof($ip) == 8) { - - $this->gateway = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); - $offset += 16; - } else { - - return false; - } - break; - - case self::GATEWAY_TYPE_DOMAIN: - - $doffset = $offset + $packet->offset; - $this->gateway = Net_DNS2_Packet::expand($packet, $doffset); - $offset = ($doffset - $packet->offset); - break; - - default: - return false; - } - - // - // extract the key - // - switch($this->algorithm) { - case self::ALGORITHM_NONE: - $this->key = ''; - break; - - case self::ALGORITHM_DSA: - case self::ALGORITHM_RSA: - $this->key = base64_encode(substr($this->rdata, $offset)); - break; - - default: - return false; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // pack the precedence, gateway type and algorithm - // - $data = pack( - 'CCC', $this->precedence, $this->gateway_type, $this->algorithm - ); - - // - // add the gateway based on the type - // - switch($this->gateway_type) { - case self::GATEWAY_TYPE_NONE: - ; // add nothing - break; - - case self::GATEWAY_TYPE_IPV4: - case self::GATEWAY_TYPE_IPV6: - $data .= inet_pton($this->gateway); - break; - - case self::GATEWAY_TYPE_DOMAIN: - $data .= chr(strlen($this->gateway)) . $this->gateway; - break; - - default: - return null; - } - - // - // add the key if there's one specified - // - switch($this->algorithm) { - case self::ALGORITHM_NONE: - ; // add nothing - break; - - case self::ALGORITHM_DSA: - case self::ALGORITHM_RSA: - $data .= base64_decode($this->key); - break; - - default: - return null; - } - - $packet->offset += strlen($data); - - return $data; - } + public const GATEWAY_TYPE_NONE = 0; + public const GATEWAY_TYPE_IPV4 = 1; + public const GATEWAY_TYPE_IPV6 = 2; + public const GATEWAY_TYPE_DOMAIN = 3; + + public const ALGORITHM_NONE = 0; + public const ALGORITHM_DSA = 1; + public const ALGORITHM_RSA = 2; + + // Precedence (used the same was as a preference field) + public $precedence; + + /* + * Gateway type - specifies the format of the gataway information + * This can be either: + * + * 0 No Gateway + * 1 IPv4 address + * 2 IPV6 address + * 3 wire-encoded domain name (not compressed) + * + */ + public $gateway_type; + + /* + * The algorithm used + * + * This can be: + * + * 0 No key is present + * 1 DSA key is present + * 2 RSA key is present + * + */ + public $algorithm; + + // The gatway information + public $gateway; + + // the public key + public $key; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + $out = $this->precedence.' '.$this->gateway_type.' ' + .$this->algorithm.' '; + + switch ($this->gateway_type) { + case self::GATEWAY_TYPE_NONE: + $out .= '. '; + + break; + + case self::GATEWAY_TYPE_IPV4: + case self::GATEWAY_TYPE_IPV6: + $out .= $this->gateway.' '; + + break; + + case self::GATEWAY_TYPE_DOMAIN: + $out .= $this->gateway.'. '; + + break; + } + + $out .= $this->key; + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + // + // load the data + // + $precedence = array_shift($rdata); + $gateway_type = array_shift($rdata); + $algorithm = array_shift($rdata); + $gateway = trim(strtolower(trim(array_shift($rdata))), '.'); + $key = array_shift($rdata); + + // + // validate it + // + switch ($gateway_type) { + case self::GATEWAY_TYPE_NONE: + $gateway = ''; + + break; + + case self::GATEWAY_TYPE_IPV4: + if (false == Net_DNS2::isIPv4($gateway)) { + return false; + } + + break; + + case self::GATEWAY_TYPE_IPV6: + if (false == Net_DNS2::isIPv6($gateway)) { + return false; + } + + break; + + case self::GATEWAY_TYPE_DOMAIN:; // do nothing + + break; + + default: + return false; + } + + // + // check the algorithm and key + // + switch ($algorithm) { + case self::ALGORITHM_NONE: + $key = ''; + + break; + + case self::ALGORITHM_DSA: + case self::ALGORITHM_RSA:; // do nothing + + break; + + default: + return false; + } + + // + // store the values + // + $this->precedence = $precedence; + $this->gateway_type = $gateway_type; + $this->algorithm = $algorithm; + $this->gateway = $gateway; + $this->key = $key; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + // + // parse off the precedence, gateway type and algorithm + // + $x = unpack('Cprecedence/Cgateway_type/Calgorithm', $this->rdata); + + $this->precedence = $x['precedence']; + $this->gateway_type = $x['gateway_type']; + $this->algorithm = $x['algorithm']; + + $offset = 3; + + // + // extract the gatway based on the type + // + switch ($this->gateway_type) { + case self::GATEWAY_TYPE_NONE: + $this->gateway = ''; + + break; + + case self::GATEWAY_TYPE_IPV4: + $this->gateway = inet_ntop(substr($this->rdata, $offset, 4)); + $offset += 4; + + break; + + case self::GATEWAY_TYPE_IPV6: + $ip = unpack('n8', substr($this->rdata, $offset, 16)); + if (8 == cacti_sizeof($ip)) { + $this->gateway = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); + $offset += 16; + } else { + return false; + } + + break; + + case self::GATEWAY_TYPE_DOMAIN: + $doffset = $offset + $packet->offset; + $this->gateway = Net_DNS2_Packet::expand($packet, $doffset); + $offset = ($doffset - $packet->offset); + + break; + + default: + return false; + } + + // + // extract the key + // + switch ($this->algorithm) { + case self::ALGORITHM_NONE: + $this->key = ''; + + break; + + case self::ALGORITHM_DSA: + case self::ALGORITHM_RSA: + $this->key = base64_encode(substr($this->rdata, $offset)); + + break; + + default: + return false; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + // + // pack the precedence, gateway type and algorithm + // + $data = pack( + 'CCC', + $this->precedence, + $this->gateway_type, + $this->algorithm + ); + + // + // add the gateway based on the type + // + switch ($this->gateway_type) { + case self::GATEWAY_TYPE_NONE:; // add nothing + + break; + + case self::GATEWAY_TYPE_IPV4: + case self::GATEWAY_TYPE_IPV6: + $data .= inet_pton($this->gateway); + + break; + + case self::GATEWAY_TYPE_DOMAIN: + $data .= chr(strlen($this->gateway)).$this->gateway; + + break; + + default: + return null; + } + + // + // add the key if there's one specified + // + switch ($this->algorithm) { + case self::ALGORITHM_NONE:; // add nothing + + break; + + case self::ALGORITHM_DSA: + case self::ALGORITHM_RSA: + $data .= base64_decode($this->key); + + break; + + default: + return null; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/ISDN.php b/Net/DNS2/RR/ISDN.php index 4f852569..c1438236 100644 --- a/Net/DNS2/RR/ISDN.php +++ b/Net/DNS2/RR/ISDN.php @@ -8,135 +8,115 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * ISDN Resource Record - RFC1183 section 3.2 + * ISDN Resource Record - RFC1183 section 3.2. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / ISDN-address / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / SA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_ISDN extends Net_DNS2_RR { - /* - * ISDN Number - */ - public $isdnaddress; - - /* - * Sub-Address - */ - public $sa; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->formatString($this->isdnaddress) . ' ' . - $this->formatString($this->sa); - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (cacti_sizeof($data) >= 1) { - - $this->isdnaddress = $data[0]; - if (isset($data[1])) { - - $this->sa = $data[1]; - } - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - $this->isdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); - - // - // look for a SA (sub address) - it's optional - // - if ( (strlen($this->isdnaddress) + 1) < $this->rdlength) { - - $this->sa = Net_DNS2_Packet::label($packet, $packet->offset); - } else { - - $this->sa = ''; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->isdnaddress) > 0) { - - $data = chr(strlen($this->isdnaddress)) . $this->isdnaddress; - if (!empty($this->sa)) { - - $data .= chr(strlen($this->sa)); - $data .= $this->sa; - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } + // ISDN Number + public $isdnaddress; + + // Sub-Address + public $sa; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->formatString($this->isdnaddress).' ' + .$this->formatString($this->sa); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $data = $this->buildString($rdata); + if (cacti_sizeof($data) >= 1) { + $this->isdnaddress = $data[0]; + if (isset($data[1])) { + $this->sa = $data[1]; + } + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $this->isdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); + + // + // look for a SA (sub address) - it's optional + // + if ((strlen($this->isdnaddress) + 1) < $this->rdlength) { + $this->sa = Net_DNS2_Packet::label($packet, $packet->offset); + } else { + $this->sa = ''; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if (strlen($this->isdnaddress) > 0) { + $data = chr(strlen($this->isdnaddress)).$this->isdnaddress; + if (!empty($this->sa)) { + $data .= chr(strlen($this->sa)); + $data .= $this->sa; + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/KEY.php b/Net/DNS2/RR/KEY.php index db7060ab..0e124ede 100644 --- a/Net/DNS2/RR/KEY.php +++ b/Net/DNS2/RR/KEY.php @@ -1,20 +1,20 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** @@ -30,8 +30,5 @@ * * We're not doing anything with these flags right now, so duplicating the * class like this is fine. - * */ -class Net_DNS2_RR_KEY extends Net_DNS2_RR_DNSKEY -{ -} +class Net_DNS2_RR_KEY extends Net_DNS2_RR_DNSKEY {} diff --git a/Net/DNS2/RR/KX.php b/Net/DNS2/RR/KX.php index 9414ff91..edf31f57 100644 --- a/Net/DNS2/RR/KX.php +++ b/Net/DNS2/RR/KX.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * KX Resource Record - RFC2230 section 3.1 + * KX Resource Record - RFC2230 section 3.1. * * This class is almost identical to MX, except that the the exchanger * domain is not compressed, it's added as a label @@ -29,62 +29,50 @@ * / EXCHANGER / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_KX extends Net_DNS2_RR { - /* - * the preference for this mail exchanger - */ + // the preference for this mail exchanger public $preference; - - /* - * the hostname of the mail exchanger - */ + + // the hostname of the mail exchanger public $exchange; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->cleanString($this->exchange) . '.'; + return $this->preference.' '.$this->cleanString($this->exchange).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->preference = array_shift($rdata); - $this->exchange = $this->cleanString(array_shift($rdata)); - - return true; + $this->preference = array_shift($rdata); + $this->exchange = $this->cleanString(array_shift($rdata)); + + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // parse the preference // @@ -99,33 +87,30 @@ protected function rrSet(Net_DNS2_Packet &$packet) return true; } - + return false; } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->exchange) > 0) { - - $data = pack('nC', $this->preference, strlen($this->exchange)) . - $this->exchange; + $data = pack('nC', $this->preference, strlen($this->exchange)) + .$this->exchange; $packet->offset += strlen($data); return $data; } - + return null; } } diff --git a/Net/DNS2/RR/L32.php b/Net/DNS2/RR/L32.php index 79b1e55b..d34ac9cc 100644 --- a/Net/DNS2/RR/L32.php +++ b/Net/DNS2/RR/L32.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.3.1 * + * @see https://netdns2.com/ + * @since File available since Release 1.3.1 */ /** - * L32 Resource Record - RFC6742 section 2.2 + * L32 Resource Record - RFC6742 section 2.2. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -26,40 +26,31 @@ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Locator32 (16 LSBs) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_L32 extends Net_DNS2_RR { - /* - * The preference - */ + // The preference public $preference; - /* - * The locator32 field - */ + // The locator32 field public $locator32; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->locator32; + return $this->preference.' '.$this->locator32; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -70,18 +61,15 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the values // @@ -92,8 +80,8 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // build the locator value // - $this->locator32 = $x['locator1'] . '.' . $x['locator2'] . '.' . - $x['locator3'] . '.' . $x['locator4']; + $this->locator32 = $x['locator1'].'.'.$x['locator2'].'.' + .$x['locator3'].'.'.$x['locator4']; return true; } @@ -102,20 +90,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet - * + * returns the rdata portion of the DNS packet. + * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->locator32) > 0) { - // // break out the locator value // diff --git a/Net/DNS2/RR/L64.php b/Net/DNS2/RR/L64.php index 17d69330..9efcba12 100644 --- a/Net/DNS2/RR/L64.php +++ b/Net/DNS2/RR/L64.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.3.1 * + * @see https://netdns2.com/ + * @since File available since Release 1.3.1 */ /** - * L64 Resource Record - RFC6742 section 2.3 + * L64 Resource Record - RFC6742 section 2.3. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,40 +28,31 @@ * + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_L64 extends Net_DNS2_RR { - /* - * The preference - */ + // The preference public $preference; - /* - * The locator64 field - */ + // The locator64 field public $locator64; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->locator64; + return $this->preference.' '.$this->locator64; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -72,65 +63,63 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the values // $x = unpack('npreference/n4locator', $this->rdata); - + $this->preference = $x['preference']; - + // // build the locator64 // - $this->locator64 = dechex($x['locator1']) . ':' . - dechex($x['locator2']) . ':' . - dechex($x['locator3']) . ':' . - dechex($x['locator4']); - + $this->locator64 = dechex($x['locator1']).':' + .dechex($x['locator2']).':' + .dechex($x['locator3']).':' + .dechex($x['locator4']); + return true; } - + return false; } /** - * returns the rdata portion of the DNS packet - * + * returns the rdata portion of the DNS packet. + * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->locator64) > 0) { - // // break out the locator64 // $n = explode(':', $this->locator64); - + // // pack the data // return pack( - 'n5', $this->preference, hexdec($n[0]), hexdec($n[1]), - hexdec($n[2]), hexdec($n[3]) + 'n5', + $this->preference, + hexdec($n[0]), + hexdec($n[1]), + hexdec($n[2]), + hexdec($n[3]) ); } diff --git a/Net/DNS2/RR/LOC.php b/Net/DNS2/RR/LOC.php index 77e0eef4..c025b14c 100644 --- a/Net/DNS2/RR/LOC.php +++ b/Net/DNS2/RR/LOC.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * LOC Resource Record - RFC1876 section 2 + * LOC Resource Record - RFC1876 section 2. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | VERSION | SIZE | @@ -34,138 +34,113 @@ * | ALTITUDE | * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_LOC extends Net_DNS2_RR { - /* - * the LOC version- should only ever be 0 - */ + // some conversion values + public const CONV_SEC = 1000; + public const CONV_MIN = 60000; + public const CONV_DEG = 3600000; + + public const REFERENCE_ALT = 10000000; + public const REFERENCE_LATLON = 2147483648; + // the LOC version- should only ever be 0 public $version; - /* - * The diameter of a sphere enclosing the described entity - */ + // The diameter of a sphere enclosing the described entity public $size; - /* - * The horizontal precision of the data - */ + // The horizontal precision of the data public $horiz_pre; - /* - * The vertical precision of the data - */ + // The vertical precision of the data public $vert_pre; - /* - * The latitude - stored in decimal degrees - */ + // The latitude - stored in decimal degrees public $latitude; - /* - * The longitude - stored in decimal degrees - */ + // The longitude - stored in decimal degrees public $longitude; - /* - * The altitude - stored in decimal - */ + // The altitude - stored in decimal public $altitude; - /* - * used for quick power-of-ten lookups - */ - private $_powerOfTen = [ 1, 10, 100, 1000, 10000, 100000, - 1000000,10000000,100000000,1000000000 ]; - - /* - * some conversion values - */ - const CONV_SEC = 1000; - const CONV_MIN = 60000; - const CONV_DEG = 3600000; - - const REFERENCE_ALT = 10000000; - const REFERENCE_LATLON = 2147483648; + // used for quick power-of-ten lookups + private $_powerOfTen = [1, 10, 100, 1000, 10000, 100000, + 1000000, 10000000, 100000000, 1000000000]; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - if ($this->version == 0) { - - return $this->_d2Dms($this->latitude, 'LAT') . ' ' . - $this->_d2Dms($this->longitude, 'LNG') . ' ' . - sprintf('%.2fm', $this->altitude) . ' ' . - sprintf('%.2fm', $this->size) . ' ' . - sprintf('%.2fm', $this->horiz_pre) . ' ' . - sprintf('%.2fm', $this->vert_pre); + if (0 == $this->version) { + return $this->_d2Dms($this->latitude, 'LAT').' ' + .$this->_d2Dms($this->longitude, 'LNG').' ' + .sprintf('%.2fm', $this->altitude).' ' + .sprintf('%.2fm', $this->size).' ' + .sprintf('%.2fm', $this->horiz_pre).' ' + .sprintf('%.2fm', $this->vert_pre); } - + return ''; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { // // format as defined by RFC1876 section 3 // - // d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] + // d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] // [siz["m"] [hp["m"] [vp["m"]]]] // $res = preg_match( - '/^(\d+) \s+((\d+) \s+)?(([\d.]+) \s+)?(N|S) \s+(\d+) ' . - '\s+((\d+) \s+)?(([\d.]+) \s+)?(E|W) \s+(-?[\d.]+) m?(\s+ ' . - '([\d.]+) m?)?(\s+ ([\d.]+) m?)?(\s+ ([\d.]+) m?)?/ix', - implode(' ', $rdata), $x + '/^(\d+) \s+((\d+) \s+)?(([\d.]+) \s+)?(N|S) \s+(\d+) ' + .'\s+((\d+) \s+)?(([\d.]+) \s+)?(E|W) \s+(-?[\d.]+) m?(\s+ ' + .'([\d.]+) m?)?(\s+ ([\d.]+) m?)?(\s+ ([\d.]+) m?)?/ix', + implode(' ', $rdata), + $x ); if ($res) { - // // latitude // - $latdeg = $x[1]; - $latmin = (isset($x[3])) ? $x[3] : 0; - $latsec = (isset($x[5])) ? $x[5] : 0; - $lathem = strtoupper($x[6]); + $latdeg = $x[1]; + $latmin = (isset($x[3])) ? $x[3] : 0; + $latsec = (isset($x[5])) ? $x[5] : 0; + $lathem = strtoupper($x[6]); $this->latitude = $this->_dms2d($latdeg, $latmin, $latsec, $lathem); // // longitude // - $londeg = $x[7]; - $lonmin = (isset($x[9])) ? $x[9] : 0; - $lonsec = (isset($x[11])) ? $x[11] : 0; - $lonhem = strtoupper($x[12]); + $londeg = $x[7]; + $lonmin = (isset($x[9])) ? $x[9] : 0; + $lonsec = (isset($x[11])) ? $x[11] : 0; + $lonhem = strtoupper($x[12]); $this->longitude = $this->_dms2d($londeg, $lonmin, $lonsec, $lonhem); // // the rest of teh values // - $version = 0; + $version = 0; - $this->size = (isset($x[15])) ? $x[15] : 1; - $this->horiz_pre = ((isset($x[17])) ? $x[17] : 10000); - $this->vert_pre = ((isset($x[19])) ? $x[19] : 10); - $this->altitude = $x[13]; + $this->size = (isset($x[15])) ? $x[15] : 1; + $this->horiz_pre = ((isset($x[17])) ? $x[17] : 10000); + $this->vert_pre = ((isset($x[19])) ? $x[19] : 10); + $this->altitude = $x[13]; return true; } @@ -174,23 +149,20 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack all the values // $x = unpack( - 'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude', + 'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude', $this->rdata ); @@ -198,33 +170,28 @@ protected function rrSet(Net_DNS2_Packet &$packet) // version must be 0 per RFC 1876 section 2 // $this->version = $x['ver']; - if ($this->version == 0) { - - $this->size = $this->_precsizeNtoA($x['size']); - $this->horiz_pre = $this->_precsizeNtoA($x['horiz_pre']); - $this->vert_pre = $this->_precsizeNtoA($x['vert_pre']); + if (0 == $this->version) { + $this->size = $this->_precsizeNtoA($x['size']); + $this->horiz_pre = $this->_precsizeNtoA($x['horiz_pre']); + $this->vert_pre = $this->_precsizeNtoA($x['vert_pre']); // // convert the latitude and longitude to degress in decimal // if ($x['latitude'] < 0) { - - $this->latitude = ($x['latitude'] + - self::REFERENCE_LATLON) / self::CONV_DEG; + $this->latitude = ($x['latitude'] + + self::REFERENCE_LATLON) / self::CONV_DEG; } else { - - $this->latitude = ($x['latitude'] - - self::REFERENCE_LATLON) / self::CONV_DEG; + $this->latitude = ($x['latitude'] + - self::REFERENCE_LATLON) / self::CONV_DEG; } if ($x['longitude'] < 0) { - - $this->longitude = ($x['longitude'] + - self::REFERENCE_LATLON) / self::CONV_DEG; + $this->longitude = ($x['longitude'] + + self::REFERENCE_LATLON) / self::CONV_DEG; } else { - - $this->longitude = ($x['longitude'] - - self::REFERENCE_LATLON) / self::CONV_DEG; + $this->longitude = ($x['longitude'] + - self::REFERENCE_LATLON) / self::CONV_DEG; } // @@ -233,12 +200,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) $this->altitude = ($x['altitude'] - self::REFERENCE_ALT) / 100; return true; - - } else { - - return false; } + return false; + return true; } @@ -246,48 +211,42 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ($this->version == 0) { - + if (0 == $this->version) { $lat = 0; $lng = 0; if ($this->latitude < 0) { - $lat = ($this->latitude * self::CONV_DEG) - self::REFERENCE_LATLON; } else { - $lat = ($this->latitude * self::CONV_DEG) + self::REFERENCE_LATLON; } if ($this->longitude < 0) { - $lng = ($this->longitude * self::CONV_DEG) - self::REFERENCE_LATLON; } else { - $lng = ($this->longitude * self::CONV_DEG) + self::REFERENCE_LATLON; } $packet->offset += 16; return pack( - 'CCCCNNN', + 'CCCCNNN', $this->version, $this->_precsizeAtoN($this->size), $this->_precsizeAtoN($this->horiz_pre), $this->_precsizeAtoN($this->vert_pre), - $lat, $lng, + $lat, + $lng, ($this->altitude * 100) + self::REFERENCE_ALT ); } @@ -297,74 +256,66 @@ protected function rrGet(Net_DNS2_Packet &$packet) /** * takes an XeY precision/size value, returns a string representation. - * shamlessly stolen from RFC1876 Appendix A + * shamlessly stolen from RFC1876 Appendix A. * - * @param integer $prec the value to convert + * @param int $prec the value to convert * * @return string - * @access private - * */ private function _precsizeNtoA($prec) { - $mantissa = (($prec >> 4) & 0x0f) % 10; - $exponent = (($prec >> 0) & 0x0f) % 10; + $mantissa = (($prec >> 4) & 0x0F) % 10; + $exponent = (($prec >> 0) & 0x0F) % 10; return $mantissa * $this->_powerOfTen[$exponent]; } /** * converts ascii size/precision X * 10**Y(cm) to 0xXY. - * shamlessly stolen from RFC1876 Appendix A + * shamlessly stolen from RFC1876 Appendix A. * * @param string $prec the value to convert * - * @return integer - * @access private - * + * @return int */ private function _precsizeAtoN($prec) { $exponent = 0; while ($prec >= 10) { - $prec /= 10; ++$exponent; } - return ($prec << 4) | ($exponent & 0x0f); + return ($prec << 4) | ($exponent & 0x0F); } /** - * convert lat/lng in deg/min/sec/hem to decimal value + * convert lat/lng in deg/min/sec/hem to decimal value. * - * @param integer $deg the degree value - * @param integer $min the minutes value - * @param integer $sec the seconds value - * @param string $hem the hemisphere (N/E/S/W) + * @param int $deg the degree value + * @param int $min the minutes value + * @param int $sec the seconds value + * @param string $hem the hemisphere (N/E/S/W) * * @return float the decinmal value - * @access private - * */ private function _dms2d($deg, $min, $sec, $hem) { $deg = $deg - 0; $min = $min - 0; - $sign = ($hem == 'W' || $hem == 'S') ? -1 : 1; - return ((($sec/60+$min)/60)+$deg) * $sign; + $sign = ('W' == $hem || 'S' == $hem) ? -1 : 1; + + return ((($sec / 60 + $min) / 60) + $deg) * $sign; } /** - * convert lat/lng in decimal to deg/min/sec/hem + * convert lat/lng in decimal to deg/min/sec/hem. * * @param float $data the decimal value * @param string $latlng either LAT or LNG so we can determine the HEM value * * @return string - * @access private - * */ private function _d2Dms($data, $latlng) { @@ -374,7 +325,7 @@ private function _d2Dms($data, $latlng) $msec = 0; $hem = ''; - if ($latlng == 'LAT') { + if ('LAT' == $latlng) { $hem = ($data > 0) ? 'N' : 'S'; } else { $hem = ($data > 0) ? 'E' : 'W'; @@ -382,10 +333,10 @@ private function _d2Dms($data, $latlng) $data = abs($data); - $deg = (int)$data; - $min = (int)(($data - $deg) * 60); - $sec = (int)(((($data - $deg) * 60) - $min) * 60); - $msec = round((((((($data - $deg) * 60) - $min) * 60) - $sec) * 1000)); + $deg = (int) $data; + $min = (int) (($data - $deg) * 60); + $sec = (int) (((($data - $deg) * 60) - $min) * 60); + $msec = round(((((($data - $deg) * 60) - $min) * 60) - $sec) * 1000); return sprintf('%d %02d %02d.%03d %s', $deg, $min, $sec, round($msec), $hem); } diff --git a/Net/DNS2/RR/LP.php b/Net/DNS2/RR/LP.php index ca95ff28..17282c5b 100644 --- a/Net/DNS2/RR/LP.php +++ b/Net/DNS2/RR/LP.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.3.1 * + * @see https://netdns2.com/ + * @since File available since Release 1.3.1 */ /** - * LP Resource Record - RFC6742 section 2.4 + * LP Resource Record - RFC6742 section 2.4. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,40 +28,31 @@ * / FQDN / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_LP extends Net_DNS2_RR { - /* - * The preference - */ + // The preference public $preference; - /* - * The fdqn field - */ + // The fdqn field public $fqdn; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->fqdn . '.'; + return $this->preference.' '.$this->fqdn.'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -72,18 +63,15 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // parse the preference // @@ -98,29 +86,27 @@ protected function rrSet(Net_DNS2_Packet &$packet) return true; } - + return false; } /** - * returns the rdata portion of the DNS packet - * + * returns the rdata portion of the DNS packet. + * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->fqdn) > 0) { - $data = pack('n', $this->preference); $packet->offset += 2; $data .= $packet->compress($this->fqdn, $packet->offset); + return $data; } diff --git a/Net/DNS2/RR/MX.php b/Net/DNS2/RR/MX.php index b1c2a4f6..42dcb452 100644 --- a/Net/DNS2/RR/MX.php +++ b/Net/DNS2/RR/MX.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * MX Resource Record - RFC1035 section 3.3.9 + * MX Resource Record - RFC1035 section 3.3.9. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | PREFERENCE | @@ -26,62 +26,50 @@ * / EXCHANGE / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_MX extends Net_DNS2_RR { - /* - * the preference for this mail exchanger - */ + // the preference for this mail exchanger public $preference; - /* - * the hostname of the mail exchanger - */ + // the hostname of the mail exchanger public $exchange; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->cleanString($this->exchange) . '.'; + return $this->preference.' '.$this->cleanString($this->exchange).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->preference = array_shift($rdata); - $this->exchange = $this->cleanString(array_shift($rdata)); + $this->preference = array_shift($rdata); + $this->exchange = $this->cleanString(array_shift($rdata)); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // parse the preference // @@ -101,24 +89,22 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->exchange) > 0) { - $data = pack('n', $this->preference); $packet->offset += 2; $data .= $packet->compress($this->exchange, $packet->offset); + return $data; } diff --git a/Net/DNS2/RR/NAPTR.php b/Net/DNS2/RR/NAPTR.php index abea6ab8..bd22c6e2 100644 --- a/Net/DNS2/RR/NAPTR.php +++ b/Net/DNS2/RR/NAPTR.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * NAPTR Resource Record - RFC2915 + * NAPTR Resource Record - RFC2915. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ @@ -35,149 +35,129 @@ * / REPLACEMENT / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_NAPTR extends Net_DNS2_RR { - /* - * the order in which the NAPTR records MUST be processed - */ - public $order; - - /* - * specifies the order in which NAPTR records with equal "order" - * values SHOULD be processed - */ - public $preference; - - /* - * rewrite flags - */ - public $flags; - - /* - * Specifies the service(s) available down this rewrite path - */ - public $services; - - /* - * regular expression - */ - public $regexp; - - /* - * The next NAME to query for NAPTR, SRV, or address records - * depending on the value of the flags field - */ - public $replacement; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->order . ' ' . $this->preference . ' ' . - $this->formatString($this->flags) . ' ' . - $this->formatString($this->services) . ' ' . - $this->formatString($this->regexp) . ' ' . - $this->cleanString($this->replacement) . '.'; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $this->order = array_shift($rdata); - $this->preference = array_shift($rdata); - - $data = $this->buildString($rdata); - if (cacti_sizeof($data) == 4) { - - $this->flags = $data[0]; - $this->services = $data[1]; - $this->regexp = $data[2]; - $this->replacement = $this->cleanString($data[3]); - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - // - // unpack the order and preference - // - $x = unpack('norder/npreference', $this->rdata); - - $this->order = $x['order']; - $this->preference = $x['preference']; - - $offset = $packet->offset + 4; - - $this->flags = Net_DNS2_Packet::label($packet, $offset); - $this->services = Net_DNS2_Packet::label($packet, $offset); - $this->regexp = Net_DNS2_Packet::label($packet, $offset); - - $this->replacement = Net_DNS2_Packet::expand($packet, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if ( (isset($this->order)) && (strlen($this->services) > 0) ) { - - $data = pack('nn', $this->order, $this->preference); - - $data .= chr(strlen($this->flags)) . $this->flags; - $data .= chr(strlen($this->services)) . $this->services; - $data .= chr(strlen($this->regexp)) . $this->regexp; - - $packet->offset += strlen($data); - - $data .= $packet->compress($this->replacement, $packet->offset); - - return $data; - } - - return null; - } + // the order in which the NAPTR records MUST be processed + public $order; + + /* + * specifies the order in which NAPTR records with equal "order" + * values SHOULD be processed + */ + public $preference; + + // rewrite flags + public $flags; + + // Specifies the service(s) available down this rewrite path + public $services; + + // regular expression + public $regexp; + + /* + * The next NAME to query for NAPTR, SRV, or address records + * depending on the value of the flags field + */ + public $replacement; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->order.' '.$this->preference.' ' + .$this->formatString($this->flags).' ' + .$this->formatString($this->services).' ' + .$this->formatString($this->regexp).' ' + .$this->cleanString($this->replacement).'.'; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $this->order = array_shift($rdata); + $this->preference = array_shift($rdata); + + $data = $this->buildString($rdata); + if (4 == cacti_sizeof($data)) { + $this->flags = $data[0]; + $this->services = $data[1]; + $this->regexp = $data[2]; + $this->replacement = $this->cleanString($data[3]); + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + // + // unpack the order and preference + // + $x = unpack('norder/npreference', $this->rdata); + + $this->order = $x['order']; + $this->preference = $x['preference']; + + $offset = $packet->offset + 4; + + $this->flags = Net_DNS2_Packet::label($packet, $offset); + $this->services = Net_DNS2_Packet::label($packet, $offset); + $this->regexp = Net_DNS2_Packet::label($packet, $offset); + + $this->replacement = Net_DNS2_Packet::expand($packet, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if ((isset($this->order)) && (strlen($this->services) > 0)) { + $data = pack('nn', $this->order, $this->preference); + + $data .= chr(strlen($this->flags)).$this->flags; + $data .= chr(strlen($this->services)).$this->services; + $data .= chr(strlen($this->regexp)).$this->regexp; + + $packet->offset += strlen($data); + + $data .= $packet->compress($this->replacement, $packet->offset); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/NID.php b/Net/DNS2/RR/NID.php index 8b501377..0f65ca11 100644 --- a/Net/DNS2/RR/NID.php +++ b/Net/DNS2/RR/NID.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.3.1 * + * @see https://netdns2.com/ + * @since File available since Release 1.3.1 */ /** - * NID Resource Record - RFC6742 section 2.1 + * NID Resource Record - RFC6742 section 2.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,40 +28,31 @@ * + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_NID extends Net_DNS2_RR { - /* - * The preference - */ + // The preference public $preference; - /* - * The node ID field - */ + // The node ID field public $nodeid; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->nodeid; + return $this->preference.' '.$this->nodeid; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -72,18 +63,15 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the values // @@ -94,10 +82,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // build the node id // - $this->nodeid = dechex($x['nodeid1']) . ':' . - dechex($x['nodeid2']) . ':' . - dechex($x['nodeid3']) . ':' . - dechex($x['nodeid4']); + $this->nodeid = dechex($x['nodeid1']).':' + .dechex($x['nodeid2']).':' + .dechex($x['nodeid3']).':' + .dechex($x['nodeid4']); return true; } @@ -106,20 +94,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet - * + * returns the rdata portion of the DNS packet. + * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->nodeid) > 0) { - // // break out the node id // @@ -129,8 +114,12 @@ protected function rrGet(Net_DNS2_Packet &$packet) // pack the data // return pack( - 'n5', $this->preference, hexdec($n[0]), hexdec($n[1]), - hexdec($n[2]), hexdec($n[3]) + 'n5', + $this->preference, + hexdec($n[0]), + hexdec($n[1]), + hexdec($n[2]), + hexdec($n[3]) ); } diff --git a/Net/DNS2/RR/NIMLOC.php b/Net/DNS2/RR/NIMLOC.php index 7ee20c3d..f534880e 100644 --- a/Net/DNS2/RR/NIMLOC.php +++ b/Net/DNS2/RR/NIMLOC.php @@ -1,35 +1,32 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * NIMLOC Resource Record - undefined; the rdata is simply used as-is in it's * binary format, so not process has to be done. - * */ class Net_DNS2_RR_NIMLOC extends Net_DNS2_RR { /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -37,13 +34,11 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -51,13 +46,11 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { @@ -65,15 +58,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { diff --git a/Net/DNS2/RR/NS.php b/Net/DNS2/RR/NS.php index 7e9f81a4..fd03d977 100644 --- a/Net/DNS2/RR/NS.php +++ b/Net/DNS2/RR/NS.php @@ -1,78 +1,69 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * NS Resource Record - RFC1035 section 3.3.11 + * NS Resource Record - RFC1035 section 3.3.11. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / NSDNAME / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_NS extends Net_DNS2_RR { - /* - * the hostname of the DNS server - */ + // the hostname of the DNS server public $nsdname; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->nsdname) . '.'; + return $this->cleanString($this->nsdname).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->nsdname = $this->cleanString(array_shift($rdata)); + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $offset = $packet->offset; $this->nsdname = Net_DNS2_Packet::expand($packet, $offset); @@ -83,23 +74,20 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->nsdname) > 0) { - return $packet->compress($this->nsdname, $packet->offset); } - + return null; } } diff --git a/Net/DNS2/RR/NSAP.php b/Net/DNS2/RR/NSAP.php index 09c80a6f..1d4281ac 100644 --- a/Net/DNS2/RR/NSAP.php +++ b/Net/DNS2/RR/NSAP.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * NSAP Resource Record - RFC1706 + * NSAP Resource Record - RFC1706. * * |--------------| * | <-- IDP --> | @@ -29,7 +29,6 @@ * |-----|--------|-----|----|-----|----|-----|----|----| * octets | 1 | 2 | 1 | 3 | 2 | 2 | 2 | 6 | 1 | * |-----|--------|-----|----|-----|----|-----|----|----| - * */ class Net_DNS2_RR_NSAP extends Net_DNS2_RR { @@ -44,33 +43,29 @@ class Net_DNS2_RR_NSAP extends Net_DNS2_RR public $sel; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->afi) . '.' . - $this->cleanString($this->idi) . '.' . - $this->cleanString($this->dfi) . '.' . - $this->cleanString($this->aa) . '.' . - $this->cleanString($this->rsvd) . '.' . - $this->cleanString($this->rd) . '.' . - $this->cleanString($this->area) . '.' . - $this->cleanString($this->id) . '.' . - $this->sel; + return $this->cleanString($this->afi).'.' + .$this->cleanString($this->idi).'.' + .$this->cleanString($this->dfi).'.' + .$this->cleanString($this->aa).'.' + .$this->cleanString($this->rsvd).'.' + .$this->cleanString($this->rd).'.' + .$this->cleanString($this->area).'.' + .$this->cleanString($this->id).'.' + .$this->sel; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -78,30 +73,29 @@ protected function rrFromString(array $rdata) // // there is no real standard for format, so we can't rely on the fact that - // the value will come in with periods separating the values- so strip + // the value will come in with periods separating the values- so strip // them out if they're included, and parse without them. - // - $data = str_replace([ '.', '0x' ], '', $data); + // + $data = str_replace(['.', '0x'], '', $data); // // unpack it as ascii characters // $x = unpack('A2afi/A4idi/A2dfi/A6aa/A4rsvd/A4rd/A4area/A12id/A2sel', $data); - + // // make sure the afi value is 47 // - if ($x['afi'] == '47') { - - $this->afi = '0x' . $x['afi']; - $this->idi = $x['idi']; - $this->dfi = $x['dfi']; - $this->aa = $x['aa']; + if ('47' == $x['afi']) { + $this->afi = '0x'.$x['afi']; + $this->idi = $x['idi']; + $this->dfi = $x['dfi']; + $this->aa = $x['aa']; $this->rsvd = $x['rsvd']; - $this->rd = $x['rd']; + $this->rd = $x['rd']; $this->area = $x['area']; - $this->id = $x['id']; - $this->sel = $x['sel']; + $this->id = $x['id']; + $this->sel = $x['sel']; return true; } @@ -110,18 +104,15 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { - if ($this->rdlength == 20) { - + if (20 == $this->rdlength) { // // get the AFI value // @@ -130,28 +121,28 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // we only support AFI 47- there arent' any others defined. // - if ($this->afi == '47') { - + if ('47' == $this->afi) { // // unpack the rest of the values // $x = unpack( - 'Cafi/nidi/Cdfi/C3aa/nrsvd/nrd/narea/Nidh/nidl/Csel', + 'Cafi/nidi/Cdfi/C3aa/nrsvd/nrd/narea/Nidh/nidl/Csel', $this->rdata ); - $this->afi = sprintf('0x%02x', $x['afi']); - $this->idi = sprintf('%04x', $x['idi']); - $this->dfi = sprintf('%02x', $x['dfi']); - $this->aa = sprintf( - '%06x', $x['aa1'] << 16 | $x['aa2'] << 8 | $x['aa3'] + $this->afi = sprintf('0x%02x', $x['afi']); + $this->idi = sprintf('%04x', $x['idi']); + $this->dfi = sprintf('%02x', $x['dfi']); + $this->aa = sprintf( + '%06x', + $x['aa1'] << 16 | $x['aa2'] << 8 | $x['aa3'] ); $this->rsvd = sprintf('%04x', $x['rsvd']); - $this->rd = sprintf('%04x', $x['rd']); + $this->rd = sprintf('%04x', $x['rd']); $this->area = sprintf('%04x', $x['area']); - $this->id = sprintf('%08x', $x['idh']) . - sprintf('%04x', $x['idl']); - $this->sel = sprintf('%02x', $x['sel']); + $this->id = sprintf('%08x', $x['idh']) + .sprintf('%04x', $x['idl']); + $this->sel = sprintf('%02x', $x['sel']); return true; } @@ -161,20 +152,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ($this->afi == '0x47') { - + if ('0x47' == $this->afi) { // // build the aa field // @@ -185,10 +173,9 @@ protected function rrGet(Net_DNS2_Packet &$packet) // $id = unpack('A8a/A4b', $this->id); - // $data = pack( - 'CnCCCCnnnNnC', - hexdec($this->afi), + 'CnCCCCnnnNnC', + hexdec($this->afi), hexdec($this->idi), hexdec($this->dfi), hexdec($aa['x']), @@ -202,9 +189,9 @@ protected function rrGet(Net_DNS2_Packet &$packet) hexdec($this->sel) ); - if (strlen($data) == 20) { - + if (20 == strlen($data)) { $packet->offset += 20; + return $data; } } diff --git a/Net/DNS2/RR/NSEC.php b/Net/DNS2/RR/NSEC.php index d64735f2..ba7e2524 100644 --- a/Net/DNS2/RR/NSEC.php +++ b/Net/DNS2/RR/NSEC.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * NSEC Resource Record - RFC3845 section 2.1 + * NSEC Resource Record - RFC3845 section 2.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -26,69 +26,56 @@ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * / List of Type Bit Map(s) / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_NSEC extends Net_DNS2_RR { - /* - * The next owner name - */ + // The next owner name public $next_domain_name; - /* - * identifies the RRset types that exist at the NSEC RR's owner name. - */ + // identifies the RRset types that exist at the NSEC RR's owner name. public $type_bit_maps = []; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - $data = $this->cleanString($this->next_domain_name) . '.'; + $data = $this->cleanString($this->next_domain_name).'.'; foreach ($this->type_bit_maps as $rr) { - - $data .= ' ' . $rr; + $data .= ' '.$rr; } return $data; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->next_domain_name = $this->cleanString(array_shift($rdata)); $this->type_bit_maps = $rdata; - + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // expand the next domain name // @@ -109,26 +96,23 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->next_domain_name) > 0) { - $data = $packet->compress($this->next_domain_name, $packet->offset); $bitmap = Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); - + $packet->offset += strlen($bitmap); - return $data . $bitmap; + return $data.$bitmap; } return null; diff --git a/Net/DNS2/RR/NSEC3.php b/Net/DNS2/RR/NSEC3.php index b4d3c085..f8385b3a 100644 --- a/Net/DNS2/RR/NSEC3.php +++ b/Net/DNS2/RR/NSEC3.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * NSEC3 Resource Record - RFC5155 section 3.2 + * NSEC3 Resource Record - RFC5155 section 3.2. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -30,114 +30,88 @@ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * / Type Bit Maps / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_NSEC3 extends Net_DNS2_RR { - /* - * Algorithm to use - */ + // Algorithm to use public $algorithm; - - /* - * flags - */ + + // flags public $flags; - - /* - * defines the number of additional times the hash is performed. - */ + + // defines the number of additional times the hash is performed. public $iterations; - - /* - * the length of the salt- not displayed - */ + + // the length of the salt- not displayed public $salt_length; - - /* - * the salt - */ + + // the salt public $salt; - /* - * the length of the hash value - */ + // the length of the hash value public $hash_length; - /* - * the hashed value of the owner name - */ + // the hashed value of the owner name public $hashed_owner_name; - /* - * array of RR type names - */ + // array of RR type names public $type_bit_maps = []; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - $out = $this->algorithm . ' ' . $this->flags . ' ' . $this->iterations . ' '; - + $out = $this->algorithm.' '.$this->flags.' '.$this->iterations.' '; + // // per RFC5155, the salt_length value isn't displayed, and if the salt // is empty, the salt is displayed as '-' // if ($this->salt_length > 0) { - $out .= $this->salt; - } else { - + } else { $out .= '-'; } // // per RFC5255 the hash length isn't shown // - $out .= ' ' . $this->hashed_owner_name; - + $out .= ' '.$this->hashed_owner_name; + // // show the RR's // foreach ($this->type_bit_maps as $rr) { - - $out .= ' ' . strtoupper($rr); + $out .= ' '.strtoupper($rr); } return $out; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->algorithm = array_shift($rdata); - $this->flags = array_shift($rdata); - $this->iterations = array_shift($rdata); - + $this->algorithm = array_shift($rdata); + $this->flags = array_shift($rdata); + $this->iterations = array_shift($rdata); + // // an empty salt is represented as '-' per RFC5155 section 3.3 // $salt = array_shift($rdata); - if ($salt == '-') { - + if ('-' == $salt) { $this->salt_length = 0; $this->salt = ''; } else { - $this->salt_length = strlen(pack('H*', $salt)); $this->salt = strtoupper($salt); } @@ -151,32 +125,28 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the first values // $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); - - $this->algorithm = $x['algorithm']; - $this->flags = $x['flags']; - $this->iterations = $x['iterations']; - $this->salt_length = $x['salt_length']; + + $this->algorithm = $x['algorithm']; + $this->flags = $x['flags']; + $this->iterations = $x['iterations']; + $this->salt_length = $x['salt_length']; $offset = 5; if ($this->salt_length > 0) { - $x = unpack('H*', substr($this->rdata, $offset, $this->salt_length)); $this->salt = strtoupper($x[1]); $offset += $this->salt_length; @@ -185,15 +155,14 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the hash length // - $x = unpack('@' . $offset . '/Chash_length', $this->rdata); - $offset++; + $x = unpack('@'.$offset.'/Chash_length', $this->rdata); + ++$offset; // // copy out the hash // - $this->hash_length = $x['hash_length']; + $this->hash_length = $x['hash_length']; if ($this->hash_length > 0) { - $this->hashed_owner_name = base64_encode( substr($this->rdata, $offset, $this->hash_length) ); @@ -209,20 +178,18 @@ protected function rrSet(Net_DNS2_Packet &$packet) return true; } - + return false; } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { @@ -231,13 +198,16 @@ protected function rrGet(Net_DNS2_Packet &$packet) // $salt = pack('H*', $this->salt); $this->salt_length = strlen($salt); - + // // pack the algorithm, flags, iterations and salt length // $data = pack( 'CCnC', - $this->algorithm, $this->flags, $this->iterations, $this->salt_length + $this->algorithm, + $this->flags, + $this->iterations, + $this->salt_length ); $data .= $salt; @@ -246,7 +216,6 @@ protected function rrGet(Net_DNS2_Packet &$packet) // $data .= chr($this->hash_length); if ($this->hash_length > 0) { - $data .= base64_decode($this->hashed_owner_name); } @@ -256,7 +225,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) $data .= Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); $packet->offset += strlen($data); - + return $data; } } diff --git a/Net/DNS2/RR/NSEC3PARAM.php b/Net/DNS2/RR/NSEC3PARAM.php index 8bb39bf8..990cb019 100644 --- a/Net/DNS2/RR/NSEC3PARAM.php +++ b/Net/DNS2/RR/NSEC3PARAM.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * NSEC3PARAM Resource Record - RFC5155 section 4.2 + * NSEC3PARAM Resource Record - RFC5155 section 4.2. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -26,7 +26,6 @@ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Salt Length | Salt / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_NSEC3PARAM extends Net_DNS2_RR { @@ -37,103 +36,83 @@ class Net_DNS2_RR_NSEC3PARAM extends Net_DNS2_RR */ public $algorithm; - /* - * flags - */ + // flags public $flags; - /* - * defines the number of additional times the hash is performed. - */ + // defines the number of additional times the hash is performed. public $iterations; - /* - * the length of the salt- not displayed - */ + // the length of the salt- not displayed public $salt_length; - /* - * the salt - */ + // the salt public $salt; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - $out = $this->algorithm . ' ' . $this->flags . ' ' . $this->iterations . ' '; + $out = $this->algorithm.' '.$this->flags.' '.$this->iterations.' '; // - // per RFC5155, the salt_length value isn't displayed, and if the salt + // per RFC5155, the salt_length value isn't displayed, and if the salt // is empty, the salt is displayed as "-" - // + // if ($this->salt_length > 0) { - $out .= $this->salt; } else { - $out .= '-'; } - + return $out; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->algorithm = array_shift($rdata); - $this->flags = array_shift($rdata); - $this->iterations = array_shift($rdata); + $this->algorithm = array_shift($rdata); + $this->flags = array_shift($rdata); + $this->iterations = array_shift($rdata); $salt = array_shift($rdata); - if ($salt == '-') { - + if ('-' == $salt) { $this->salt_length = 0; $this->salt = ''; } else { - $this->salt_length = strlen(pack('H*', $salt)); $this->salt = strtoupper($salt); } - + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); - $this->algorithm = $x['algorithm']; - $this->flags = $x['flags']; - $this->iterations = $x['iterations']; - $this->salt_length = $x['salt_length']; + $this->algorithm = $x['algorithm']; + $this->flags = $x['flags']; + $this->iterations = $x['iterations']; + $this->salt_length = $x['salt_length']; if ($this->salt_length > 0) { - $x = unpack('H*', substr($this->rdata, 5, $this->salt_length)); $this->salt = strtoupper($x[1]); } @@ -145,15 +124,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { @@ -161,9 +138,12 @@ protected function rrGet(Net_DNS2_Packet &$packet) $this->salt_length = strlen($salt); $data = pack( - 'CCnC', - $this->algorithm, $this->flags, $this->iterations, $this->salt_length - ) . $salt; + 'CCnC', + $this->algorithm, + $this->flags, + $this->iterations, + $this->salt_length + ).$salt; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/OPENPGPKEY.php b/Net/DNS2/RR/OPENPGPKEY.php index ee3d36b3..53ea3645 100644 --- a/Net/DNS2/RR/OPENPGPKEY.php +++ b/Net/DNS2/RR/OPENPGPKEY.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.4.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.4.0 */ /** - * OPENPGPKEY Resource Record - https://tools.ietf.org/html/draft-ietf-dane-openpgpkey-01 + * OPENPGPKEY Resource Record - https://tools.ietf.org/html/draft-ietf-dane-openpgpkey-01. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -26,21 +26,16 @@ * / OpenPGP Public KeyRing / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_OPENPGPKEY extends Net_DNS2_RR { - /* - * the public key - */ + // the public key public $key; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -48,13 +43,11 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -64,18 +57,15 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $this->key = base64_encode(substr($this->rdata, 0, $this->rdlength)); return true; @@ -85,27 +75,24 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->key) > 0) { - $data = base64_decode($this->key); $packet->offset += strlen($data); return $data; } - + return null; } } diff --git a/Net/DNS2/RR/OPT.php b/Net/DNS2/RR/OPT.php index 1aafeb44..1d78f89e 100644 --- a/Net/DNS2/RR/OPT.php +++ b/Net/DNS2/RR/OPT.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.0.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.0.0 */ /** - * OPT Resource Record - RFC2929 section 3.1 + * OPT Resource Record - RFC2929 section 3.1. * * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * | OPTION-CODE | @@ -29,48 +29,33 @@ * / OPTION-DATA / * / / * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - * */ class Net_DNS2_RR_OPT extends Net_DNS2_RR { - /* - * option code - assigned by IANA - */ + // option code - assigned by IANA public $option_code; - /* - * the length of the option data - */ + // the length of the option data public $option_length; - /* - * the option data - */ + // the option data public $option_data; - /* - * the extended response code stored in the TTL - */ + // the extended response code stored in the TTL public $extended_rcode; - /* - * the implementation level - */ + // the implementation level public $version; - /* - * the DO bit used for DNSSEC - RFC3225 - */ + // the DO bit used for DNSSEC - RFC3225 public $do; - /* - * the extended flags - */ + // the extended flags public $z; /** * Constructor - builds a new Net_DNS2_RR_OPT object; normally you wouldn't call - * this directly, but OPT RR's are a little different + * this directly, but OPT RR's are a little different. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create * an empty object @@ -78,29 +63,26 @@ class Net_DNS2_RR_OPT extends Net_DNS2_RR * create an empty object * * @throws Net_DNS2_Exception - * @access public - * */ - public function __construct(Net_DNS2_Packet &$packet = null, array $rr = null) + public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) { // // this is for when we're manually building an OPT RR object; we aren't // passing in binary data to parse, we just want a clean/empty object. // - $this->type = 'OPT'; - $this->rdlength = 0; + $this->type = 'OPT'; + $this->rdlength = 0; - $this->option_length = 0; - $this->extended_rcode = 0; - $this->version = 0; - $this->do = 0; - $this->z = 0; + $this->option_length = 0; + $this->extended_rcode = 0; + $this->version = 0; + $this->do = 0; + $this->z = 0; // // everthing else gets passed through to the parent. // - if ( (!is_null($packet)) && (!is_null($rr)) ) { - + if ((!is_null($packet)) && (!is_null($rr))) { parent::__construct($packet, $rr); } } @@ -110,50 +92,44 @@ public function __construct(Net_DNS2_Packet &$packet = null, array $rr = null) * defintion for returning an OPT RR by string- this is just here to validate * the binary parsing / building routines. * - * @return string - * @access protected - * + * @return string */ protected function rrToString() { - return $this->option_code . ' ' . $this->option_data; + return $this->option_code.' '.$this->option_data; } /** - * parses the rdata portion from a standard DNS config line. There is no + * parses the rdata portion from a standard DNS config line. There is no * definition for parsing a OPT RR by string- this is just here to validate * the binary parsing / building routines. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->option_code = array_shift($rdata); - $this->option_data = array_shift($rdata); - $this->option_length = strlen($this->option_data); + $this->option_code = array_shift($rdata); + $this->option_data = array_shift($rdata); + $this->option_length = strlen($this->option_data); $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); - $this->extended_rcode = $x['extended']; - $this->version = $x['version']; - $this->do = ($x['do'] >> 7); - $this->z = $x['z']; + $this->extended_rcode = $x['extended']; + $this->version = $x['version']; + $this->do = ($x['do'] >> 7); + $this->z = $x['z']; return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { @@ -162,28 +138,27 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); - $this->extended_rcode = $x['extended']; - $this->version = $x['version']; - $this->do = ($x['do'] >> 7); - $this->z = $x['z']; + $this->extended_rcode = $x['extended']; + $this->version = $x['version']; + $this->do = ($x['do'] >> 7); + $this->z = $x['z']; // // parse the data, if there is any // if ($this->rdlength > 0) { - // // unpack the code and length // $x = unpack('noption_code/noption_length', $this->rdata); - $this->option_code = $x['option_code']; - $this->option_length = $x['option_length']; + $this->option_code = $x['option_code']; + $this->option_length = $x['option_length']; // // copy out the data based on the length // - $this->option_data = substr($this->rdata, 4); + $this->option_data = substr($this->rdata, 4); } return true; @@ -193,10 +168,6 @@ protected function rrSet(Net_DNS2_Packet &$packet) * pre-builds the TTL value for this record; we needed to separate this out * from the rrGet() function, as the logic in the Net_DNS2_RR packs the TTL * value before it builds the rdata value. - * - * @return void - * @access protected - * */ protected function preBuild() { @@ -204,25 +175,21 @@ protected function preBuild() // build the TTL value based on the local values // $ttl = unpack( - 'N', - pack('CCCC', $this->extended_rcode, $this->version, ($this->do << 7), 0) + 'N', + pack('CCCC', $this->extended_rcode, $this->version, $this->do << 7, 0) ); $this->ttl = $ttl[1]; - - return; } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { @@ -230,9 +197,8 @@ protected function rrGet(Net_DNS2_Packet &$packet) // if there is an option code, then pack that data too // if ($this->option_code) { - - $data = pack('nn', $this->option_code, $this->option_length) . - $this->option_data; + $data = pack('nn', $this->option_code, $this->option_length) + .$this->option_data; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/PTR.php b/Net/DNS2/RR/PTR.php index f6674500..1771e8d2 100644 --- a/Net/DNS2/RR/PTR.php +++ b/Net/DNS2/RR/PTR.php @@ -1,77 +1,68 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * PTR Resource Record - RFC1035 section 3.3.12 + * PTR Resource Record - RFC1035 section 3.3.12. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / PTRDNAME / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_PTR extends Net_DNS2_RR { - /* - * the hostname of the PTR entry - */ + // the hostname of the PTR entry public $ptrdname; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return rtrim($this->ptrdname, '.') . '.'; + return rtrim($this->ptrdname, '.').'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->ptrdname = rtrim(implode(' ', $rdata), '.'); + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $offset = $packet->offset; $this->ptrdname = Net_DNS2_Packet::expand($packet, $offset); @@ -82,20 +73,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->ptrdname) > 0) { - return $packet->compress($this->ptrdname, $packet->offset); } diff --git a/Net/DNS2/RR/PX.php b/Net/DNS2/RR/PX.php index e0f97e5d..ec3a1850 100644 --- a/Net/DNS2/RR/PX.php +++ b/Net/DNS2/RR/PX.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * PX Resource Record - RFC2163 section 4 + * PX Resource Record - RFC2163 section 4. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | PREFERENCE | @@ -29,79 +29,65 @@ * / MAPX400 / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- - * */ class Net_DNS2_RR_PX extends Net_DNS2_RR { - /* - * preference - */ + // preference public $preference; - /* - * the RFC822 part of the MCGAM - */ + // the RFC822 part of the MCGAM public $map822; - /* - * the X.400 part of the MCGAM - */ + // the X.400 part of the MCGAM public $mapx400; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . $this->cleanString($this->map822) . '. ' . - $this->cleanString($this->mapx400) . '.'; + return $this->preference.' '.$this->cleanString($this->map822).'. ' + .$this->cleanString($this->mapx400).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->preference = $rdata[0]; - $this->map822 = $this->cleanString($rdata[1]); - $this->mapx400 = $this->cleanString($rdata[2]); + $this->preference = $rdata[0]; + $this->map822 = $this->cleanString($rdata[1]); + $this->mapx400 = $this->cleanString($rdata[2]); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // parse the preference // $x = unpack('npreference', $this->rdata); $this->preference = $x['preference']; - $offset = $packet->offset + 2; + $offset = $packet->offset + 2; - $this->map822 = Net_DNS2_Packet::expand($packet, $offset); - $this->mapx400 = Net_DNS2_Packet::expand($packet, $offset); + $this->map822 = Net_DNS2_Packet::expand($packet, $offset); + $this->mapx400 = Net_DNS2_Packet::expand($packet, $offset); return true; } @@ -110,20 +96,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->map822) > 0) { - $data = pack('n', $this->preference); $packet->offset += 2; diff --git a/Net/DNS2/RR/RP.php b/Net/DNS2/RR/RP.php index b545ab08..a15dc2ea 100644 --- a/Net/DNS2/RR/RP.php +++ b/Net/DNS2/RR/RP.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * RP Resource Record - RFC1183 section 2.2 + * RP Resource Record - RFC1183 section 2.2. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / mboxdname / @@ -27,66 +27,54 @@ * / txtdname / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_RP extends Net_DNS2_RR { - /* - * mailbox for the responsible person - */ + // mailbox for the responsible person public $mboxdname; - /* - * is a domain name for which TXT RR's exists - */ + // is a domain name for which TXT RR's exists public $txtdname; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->mboxdname) . '. ' . $this->cleanString($this->txtdname) . '.'; + return $this->cleanString($this->mboxdname).'. '.$this->cleanString($this->txtdname).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->mboxdname = $this->cleanString($rdata[0]); - $this->txtdname = $this->cleanString($rdata[1]); + $this->mboxdname = $this->cleanString($rdata[0]); + $this->txtdname = $this->cleanString($rdata[1]); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { + $offset = $packet->offset; - $offset = $packet->offset; - - $this->mboxdname = Net_DNS2_Packet::expand($packet, $offset, true); - $this->txtdname = Net_DNS2_Packet::expand($packet, $offset); + $this->mboxdname = Net_DNS2_Packet::expand($packet, $offset, true); + $this->txtdname = Net_DNS2_Packet::expand($packet, $offset); return true; } @@ -95,22 +83,19 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->mboxdname) > 0) { - - return $packet->compress($this->mboxdname, $packet->offset) . - $packet->compress($this->txtdname, $packet->offset); + return $packet->compress($this->mboxdname, $packet->offset) + .$packet->compress($this->txtdname, $packet->offset); } return null; diff --git a/Net/DNS2/RR/RRSIG.php b/Net/DNS2/RR/RRSIG.php index 13ede630..f13cd897 100644 --- a/Net/DNS2/RR/RRSIG.php +++ b/Net/DNS2/RR/RRSIG.php @@ -1,26 +1,27 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ + * + * @see https://netdns2.com/ * @since File available since Release 0.6.0 * * This file contains code based off the Net::DNS::SEC Perl module by Olaf M. Kolkman * * This is the copyright notice from the PERL Net::DNS::SEC module: * - * Copyright (c) 2001 - 2005 RIPE NCC. Author Olaf M. Kolkman - * Copyright (c) 2007 - 2008 NLnet Labs. Author Olaf M. Kolkman + * Copyright (c) 2001 - 2005 RIPE NCC. Author Olaf M. Kolkman + * Copyright (c) 2007 - 2008 NLnet Labs. Author Olaf M. Kolkman * * * All Rights Reserved @@ -39,11 +40,10 @@ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * */ /** - * RRSIG Resource Record - RFC4034 sction 3.1 + * RRSIG Resource Record - RFC4034 sction 3.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -63,93 +63,69 @@ * / Signature / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_RRSIG extends Net_DNS2_RR { - /* - * the RR type covered by this signature - */ + // the RR type covered by this signature public $typecovered; - /* - * the algorithm used for the signature - */ + // the algorithm used for the signature public $algorithm; - - /* - * the number of labels in the name - */ + + // the number of labels in the name public $labels; - /* - * the original TTL - */ + // the original TTL public $origttl; - /* - * the signature expiration - */ + // the signature expiration public $sigexp; - /* - * the inception of the signature - */ + // the inception of the signature public $sigincep; - /* - * the keytag used - */ + // the keytag used public $keytag; - /* - * the signer's name - */ + // the signer's name public $signname; - /* - * the signature - */ + // the signature public $signature; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->typecovered . ' ' . $this->algorithm . ' ' . - $this->labels . ' ' . $this->origttl . ' ' . - $this->sigexp . ' ' . $this->sigincep . ' ' . - $this->keytag . ' ' . $this->cleanString($this->signname) . '. ' . - $this->signature; + return $this->typecovered.' '.$this->algorithm.' ' + .$this->labels.' '.$this->origttl.' ' + .$this->sigexp.' '.$this->sigincep.' ' + .$this->keytag.' '.$this->cleanString($this->signname).'. ' + .$this->signature; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->typecovered = strtoupper(array_shift($rdata)); - $this->algorithm = array_shift($rdata); - $this->labels = array_shift($rdata); - $this->origttl = array_shift($rdata); - $this->sigexp = array_shift($rdata); - $this->sigincep = array_shift($rdata); - $this->keytag = array_shift($rdata); - $this->signname = $this->cleanString(array_shift($rdata)); + $this->typecovered = strtoupper(array_shift($rdata)); + $this->algorithm = array_shift($rdata); + $this->labels = array_shift($rdata); + $this->origttl = array_shift($rdata); + $this->sigexp = array_shift($rdata); + $this->sigincep = array_shift($rdata); + $this->keytag = array_shift($rdata); + $this->signname = $this->cleanString(array_shift($rdata)); foreach ($rdata as $line) { - $this->signature .= $line; } @@ -159,52 +135,49 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // - // unpack + // unpack // $x = unpack( - 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', + 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', $this->rdata ); - $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; - $this->algorithm = $x['algorithm']; - $this->labels = $x['labels']; - $this->origttl = Net_DNS2::expandUint32($x['origttl']); + $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; + $this->algorithm = $x['algorithm']; + $this->labels = $x['labels']; + $this->origttl = Net_DNS2::expandUint32($x['origttl']); // // the dates are in GM time // - $this->sigexp = gmdate('YmdHis', $x['sigexp']); - $this->sigincep = gmdate('YmdHis', $x['sigincep']); + $this->sigexp = gmdate('YmdHis', $x['sigexp']); + $this->sigincep = gmdate('YmdHis', $x['sigincep']); // // get the keytag // - $this->keytag = $x['keytag']; + $this->keytag = $x['keytag']; // // get teh signers name and signature // - $offset = $packet->offset + 18; - $sigoffset = $offset; + $offset = $packet->offset + 18; + $sigoffset = $offset; - $this->signname = strtolower( + $this->signname = strtolower( Net_DNS2_Packet::expand($packet, $sigoffset) ); - $this->signature = base64_encode( + $this->signature = base64_encode( substr($this->rdata, 18 + ($sigoffset - $offset)) ); @@ -215,35 +188,36 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->signature) > 0) { - // // parse the values out of the dates // preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigexp, $e + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigexp, + $e ); preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigincep, $i + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigincep, + $i ); // // pack the value // $data = pack( - 'nCCNNNn', + 'nCCNNNn', Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], $this->algorithm, $this->labels, @@ -254,12 +228,11 @@ protected function rrGet(Net_DNS2_Packet &$packet) ); // - // the signer name is special; it's not allowed to be compressed + // the signer name is special; it's not allowed to be compressed // (see section 3.1.7) // $names = explode('.', strtolower($this->signname)); foreach ($names as $name) { - $data .= chr(strlen($name)); $data .= $name; } @@ -274,7 +247,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) return $data; } - + return null; } } diff --git a/Net/DNS2/RR/RT.php b/Net/DNS2/RR/RT.php index 08e2b160..7b41eb52 100644 --- a/Net/DNS2/RR/RT.php +++ b/Net/DNS2/RR/RT.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * RT Resource Record - RFC1183 section 3.3 + * RT Resource Record - RFC1183 section 3.3. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | preference | @@ -26,72 +26,60 @@ * / intermediate-host / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_RT extends Net_DNS2_RR { - /* - * the preference of this route - */ + // the preference of this route public $preference; - /* - * host which will servce as an intermediate in reaching the owner host - */ + // host which will servce as an intermediate in reaching the owner host public $intermediatehost; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->preference . ' ' . - $this->cleanString($this->intermediatehost) . '.'; + return $this->preference.' ' + .$this->cleanString($this->intermediatehost).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->preference = $rdata[0]; + $this->preference = $rdata[0]; $this->intermediatehost = $this->cleanString($rdata[1]); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the preference // $x = unpack('npreference', $this->rdata); - $this->preference = $x['preference']; - $offset = $packet->offset + 2; + $this->preference = $x['preference']; + $offset = $packet->offset + 2; - $this->intermediatehost = Net_DNS2_Packet::expand($packet, $offset); + $this->intermediatehost = Net_DNS2_Packet::expand($packet, $offset); return true; } @@ -100,20 +88,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->intermediatehost) > 0) { - $data = pack('n', $this->preference); $packet->offset += 2; diff --git a/Net/DNS2/RR/SIG.php b/Net/DNS2/RR/SIG.php index e681b9e7..58b2dc74 100644 --- a/Net/DNS2/RR/SIG.php +++ b/Net/DNS2/RR/SIG.php @@ -8,11 +8,12 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ + * + * @see https://netdns2.com/ * @since File available since Release 0.6.0 * * This file contains code based off the Net::DNS::SEC Perl module by Olaf M. Kolkman @@ -39,11 +40,10 @@ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * */ /** - * SIG Resource Record - RFC2535 section 4.1 + * SIG Resource Record - RFC2535 section 4.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -63,348 +63,315 @@ * / Signature / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_SIG extends Net_DNS2_RR { - /* - * and instance of a Net_DNS2_PrivateKey object - */ - public $private_key = null; - - /* - * the RR type covered by this signature - */ - public $typecovered; - - /* - * the algorithm used for the signature - */ - public $algorithm; - - /* - * the number of labels in the name - */ - public $labels; - - /* - * the original TTL - */ - public $origttl; - - /* - * the signature expiration - */ - public $sigexp; - - /* - * the inception of the signature - */ - public $sigincep; - - /* - * the keytag used - */ - public $keytag; - - /* - * the signer's name - */ - public $signname; - - /* - * the signature - */ - public $signature; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->typecovered . ' ' . $this->algorithm . ' ' . - $this->labels . ' ' . $this->origttl . ' ' . - $this->sigexp . ' ' . $this->sigincep . ' ' . - $this->keytag . ' ' . $this->cleanString($this->signname) . '. ' . - $this->signature; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $this->typecovered = strtoupper(array_shift($rdata)); - $this->algorithm = array_shift($rdata); - $this->labels = array_shift($rdata); - $this->origttl = array_shift($rdata); - $this->sigexp = array_shift($rdata); - $this->sigincep = array_shift($rdata); - $this->keytag = array_shift($rdata); - $this->signname = $this->cleanString(array_shift($rdata)); - - foreach ($rdata as $line) { - - $this->signature .= $line; - } - - $this->signature = trim($this->signature); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - // - // unpack - // - $x = unpack( - 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', - $this->rdata - ); - - $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; - $this->algorithm = $x['algorithm']; - $this->labels = $x['labels']; - $this->origttl = Net_DNS2::expandUint32($x['origttl']); - - // - // the dates are in GM time - // - $this->sigexp = gmdate('YmdHis', $x['sigexp']); - $this->sigincep = gmdate('YmdHis', $x['sigincep']); - - // - // get the keytag - // - $this->keytag = $x['keytag']; - - // - // get teh signers name and signature - // - $offset = $packet->offset + 18; - $sigoffset = $offset; - - $this->signname = strtolower( - Net_DNS2_Packet::expand($packet, $sigoffset) - ); - $this->signature = base64_encode( - substr($this->rdata, 18 + ($sigoffset - $offset)) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // parse the values out of the dates - // - preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigexp, $e - ); - preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigincep, $i - ); - - // - // pack the value - // - $data = pack( - 'nCCNNNn', - Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], - $this->algorithm, - $this->labels, - $this->origttl, - gmmktime($e[4], $e[5], $e[6], $e[2], $e[3], $e[1]), - gmmktime($i[4], $i[5], $i[6], $i[2], $i[3], $i[1]), - $this->keytag - ); - - // - // the signer name is special; it's not allowed to be compressed - // (see section 3.1.7) - // - $names = explode('.', strtolower($this->signname)); - foreach ($names as $name) { - - $data .= chr(strlen($name)); - $data .= $name; - } - - $data .= chr('0'); - - // - // if the signature is empty, and $this->private_key is an instance of a - // private key object, and we have access to openssl, then assume this - // is a SIG(0), and generate a new signature - // - if ( (strlen($this->signature) == 0) - && ($this->private_key instanceof Net_DNS2_PrivateKey) - && (extension_loaded('openssl') === true) - ) { - - // - // create a new packet for the signature- - // - $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); - - // - // copy the packet data over - // - $new_packet->copy($packet); - - // - // remove the SIG object from the additional list - // - array_pop($new_packet->additional); - $new_packet->header->arcount = cacti_sizeof($new_packet->additional); - - // - // copy out the data - // - $sigdata = $data . $new_packet->get(); - - // - // based on the algorithm - // - $algorithm = 0; - - switch($this->algorithm) { - - // - // MD5 - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - - $algorithm = OPENSSL_ALGO_MD5; - break; - - // - // SHA1 - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - - $algorithm = OPENSSL_ALGO_SHA1; - break; - - // - // SHA256 (PHP 5.4.8 or higher) - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - - if (version_compare(PHP_VERSION, '5.4.8', '<') == true) { - - throw new Net_DNS2_Exception( - 'SHA256 support is only available in PHP >= 5.4.8', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - $algorithm = OPENSSL_ALGO_SHA256; - break; - - // - // SHA512 (PHP 5.4.8 or higher) - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - - if (version_compare(PHP_VERSION, '5.4.8', '<') == true) { - - throw new Net_DNS2_Exception( - 'SHA512 support is only available in PHP >= 5.4.8', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - $algorithm = OPENSSL_ALGO_SHA512; - break; - - // - // unsupported at the moment - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: - case Net_DNS2_Lookups::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSANSEC3SHA1: - default: - throw new Net_DNS2_Exception( - 'invalid or unsupported algorithm', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - break; - } - - // - // sign the data - // - if (openssl_sign($sigdata, $this->signature, $this->private_key->instance, $algorithm) == false) { - - throw new Net_DNS2_Exception( - openssl_error_string(), - Net_DNS2_Lookups::E_OPENSSL_ERROR - ); - } - - // - // build the signature value based - // - switch($this->algorithm) { - - // - // RSA- add it directly - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - - $this->signature = base64_encode($this->signature); - break; - } - } - - // - // add the signature - // - $data .= base64_decode($this->signature); - - $packet->offset += strlen($data); - - return $data; - } + // and instance of a Net_DNS2_PrivateKey object + public $private_key; + + // the RR type covered by this signature + public $typecovered; + + // the algorithm used for the signature + public $algorithm; + + // the number of labels in the name + public $labels; + + // the original TTL + public $origttl; + + // the signature expiration + public $sigexp; + + // the inception of the signature + public $sigincep; + + // the keytag used + public $keytag; + + // the signer's name + public $signname; + + // the signature + public $signature; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->typecovered.' '.$this->algorithm.' ' + .$this->labels.' '.$this->origttl.' ' + .$this->sigexp.' '.$this->sigincep.' ' + .$this->keytag.' '.$this->cleanString($this->signname).'. ' + .$this->signature; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $this->typecovered = strtoupper(array_shift($rdata)); + $this->algorithm = array_shift($rdata); + $this->labels = array_shift($rdata); + $this->origttl = array_shift($rdata); + $this->sigexp = array_shift($rdata); + $this->sigincep = array_shift($rdata); + $this->keytag = array_shift($rdata); + $this->signname = $this->cleanString(array_shift($rdata)); + + foreach ($rdata as $line) { + $this->signature .= $line; + } + + $this->signature = trim($this->signature); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + // + // unpack + // + $x = unpack( + 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', + $this->rdata + ); + + $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; + $this->algorithm = $x['algorithm']; + $this->labels = $x['labels']; + $this->origttl = Net_DNS2::expandUint32($x['origttl']); + + // + // the dates are in GM time + // + $this->sigexp = gmdate('YmdHis', $x['sigexp']); + $this->sigincep = gmdate('YmdHis', $x['sigincep']); + + // + // get the keytag + // + $this->keytag = $x['keytag']; + + // + // get teh signers name and signature + // + $offset = $packet->offset + 18; + $sigoffset = $offset; + + $this->signname = strtolower( + Net_DNS2_Packet::expand($packet, $sigoffset) + ); + $this->signature = base64_encode( + substr($this->rdata, 18 + ($sigoffset - $offset)) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + // + // parse the values out of the dates + // + preg_match( + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigexp, + $e + ); + preg_match( + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigincep, + $i + ); + + // + // pack the value + // + $data = pack( + 'nCCNNNn', + Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], + $this->algorithm, + $this->labels, + $this->origttl, + gmmktime($e[4], $e[5], $e[6], $e[2], $e[3], $e[1]), + gmmktime($i[4], $i[5], $i[6], $i[2], $i[3], $i[1]), + $this->keytag + ); + + // + // the signer name is special; it's not allowed to be compressed + // (see section 3.1.7) + // + $names = explode('.', strtolower($this->signname)); + foreach ($names as $name) { + $data .= chr(strlen($name)); + $data .= $name; + } + + $data .= chr('0'); + + // + // if the signature is empty, and $this->private_key is an instance of a + // private key object, and we have access to openssl, then assume this + // is a SIG(0), and generate a new signature + // + if ((0 == strlen($this->signature)) + && ($this->private_key instanceof Net_DNS2_PrivateKey) + && (true === extension_loaded('openssl')) + ) { + // + // create a new packet for the signature- + // + $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); + + // + // copy the packet data over + // + $new_packet->copy($packet); + + // + // remove the SIG object from the additional list + // + array_pop($new_packet->additional); + $new_packet->header->arcount = cacti_sizeof($new_packet->additional); + + // + // copy out the data + // + $sigdata = $data.$new_packet->get(); + + // + // based on the algorithm + // + $algorithm = 0; + + switch ($this->algorithm) { + // + // MD5 + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + $algorithm = OPENSSL_ALGO_MD5; + + break; + + // + // SHA1 + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + $algorithm = OPENSSL_ALGO_SHA1; + + break; + + // + // SHA256 (PHP 5.4.8 or higher) + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + if (true == version_compare(PHP_VERSION, '5.4.8', '<')) { + throw new Net_DNS2_Exception( + 'SHA256 support is only available in PHP >= 5.4.8', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + $algorithm = OPENSSL_ALGO_SHA256; + + break; + + // + // SHA512 (PHP 5.4.8 or higher) + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + if (true == version_compare(PHP_VERSION, '5.4.8', '<')) { + throw new Net_DNS2_Exception( + 'SHA512 support is only available in PHP >= 5.4.8', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + $algorithm = OPENSSL_ALGO_SHA512; + + break; + + // + // unsupported at the moment + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: + case Net_DNS2_Lookups::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSANSEC3SHA1: + default: + throw new Net_DNS2_Exception( + 'invalid or unsupported algorithm', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + + break; + } + + // + // sign the data + // + if (false == openssl_sign($sigdata, $this->signature, $this->private_key->instance, $algorithm)) { + throw new Net_DNS2_Exception( + openssl_error_string(), + Net_DNS2_Lookups::E_OPENSSL_ERROR + ); + } + + // + // build the signature value based + // + switch ($this->algorithm) { + // + // RSA- add it directly + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + $this->signature = base64_encode($this->signature); + + break; + } + } + + // + // add the signature + // + $data .= base64_decode($this->signature); + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/SMIMEA.php b/Net/DNS2/RR/SMIMEA.php index 96feb67b..e4a55dd9 100644 --- a/Net/DNS2/RR/SMIMEA.php +++ b/Net/DNS2/RR/SMIMEA.php @@ -1,27 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.4.2 * + * @see https://netdns2.com/ + * @since File available since Release 1.4.2 */ /** * The SMIMEA RR is implemented exactly like the TLSA record, so * for now we just extend the TLSA RR and use it. - * */ -class Net_DNS2_RR_SMIMEA extends Net_DNS2_RR_TLSA -{ -} +class Net_DNS2_RR_SMIMEA extends Net_DNS2_RR_TLSA {} diff --git a/Net/DNS2/RR/SOA.php b/Net/DNS2/RR/SOA.php index 36dee536..664ab320 100644 --- a/Net/DNS2/RR/SOA.php +++ b/Net/DNS2/RR/SOA.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * SOA Resource Record - RFC1035 section 3.3.13 + * SOA Resource Record - RFC1035 section 3.3.13. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / MNAME / @@ -41,98 +41,76 @@ * | MINIMUM | * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_SOA extends Net_DNS2_RR { - /* - * The master DNS server - */ + // The master DNS server public $mname; - /* - * mailbox of the responsible person - */ + // mailbox of the responsible person public $rname; - /* - * serial number - */ + // serial number public $serial; - /* - * refresh time - */ + // refresh time public $refresh; - /* - * retry interval - */ + // retry interval public $retry; - /* - * expire time - */ + // expire time public $expire; - /* - * minimum TTL for any RR in this zone - */ + // minimum TTL for any RR in this zone public $minimum; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->mname) . '. ' . - $this->cleanString($this->rname) . '. ' . - $this->serial . ' ' . $this->refresh . ' ' . $this->retry . ' ' . - $this->expire . ' ' . $this->minimum; + return $this->cleanString($this->mname).'. ' + .$this->cleanString($this->rname).'. ' + .$this->serial.' '.$this->refresh.' '.$this->retry.' ' + .$this->expire.' '.$this->minimum; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->mname = $this->cleanString($rdata[0]); - $this->rname = $this->cleanString($rdata[1]); + $this->mname = $this->cleanString($rdata[0]); + $this->rname = $this->cleanString($rdata[1]); - $this->serial = $rdata[2]; - $this->refresh = $rdata[3]; - $this->retry = $rdata[4]; - $this->expire = $rdata[5]; - $this->minimum = $rdata[6]; + $this->serial = $rdata[2]; + $this->refresh = $rdata[3]; + $this->retry = $rdata[4]; + $this->expire = $rdata[5]; + $this->minimum = $rdata[6]; return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // - // parse the + // parse the // $offset = $packet->offset; @@ -143,15 +121,15 @@ protected function rrSet(Net_DNS2_Packet &$packet) // get the SOA values // $x = unpack( - '@' . $offset . '/Nserial/Nrefresh/Nretry/Nexpire/Nminimum/', + '@'.$offset.'/Nserial/Nrefresh/Nretry/Nexpire/Nminimum/', $packet->rdata ); - $this->serial = Net_DNS2::expandUint32($x['serial']); - $this->refresh = Net_DNS2::expandUint32($x['refresh']); - $this->retry = Net_DNS2::expandUint32($x['retry']); - $this->expire = Net_DNS2::expandUint32($x['expire']); - $this->minimum = Net_DNS2::expandUint32($x['minimum']); + $this->serial = Net_DNS2::expandUint32($x['serial']); + $this->refresh = Net_DNS2::expandUint32($x['refresh']); + $this->retry = Net_DNS2::expandUint32($x['retry']); + $this->expire = Net_DNS2::expandUint32($x['expire']); + $this->minimum = Net_DNS2::expandUint32($x['minimum']); return true; } @@ -160,26 +138,27 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->mname) > 0) { - $data = $packet->compress($this->mname, $packet->offset); $data .= $packet->compress($this->rname, $packet->offset); $data .= pack( - 'N5', $this->serial, $this->refresh, $this->retry, - $this->expire, $this->minimum + 'N5', + $this->serial, + $this->refresh, + $this->retry, + $this->expire, + $this->minimum ); $packet->offset += 20; diff --git a/Net/DNS2/RR/SPF.php b/Net/DNS2/RR/SPF.php index 53db98f8..dce2ecbb 100644 --- a/Net/DNS2/RR/SPF.php +++ b/Net/DNS2/RR/SPF.php @@ -1,27 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * The SPF RR is implemented exactly like the TXT record, so * for now we just extend the TXT RR and use it. - * */ -class Net_DNS2_RR_SPF extends Net_DNS2_RR_TXT -{ -} +class Net_DNS2_RR_SPF extends Net_DNS2_RR_TXT {} diff --git a/Net/DNS2/RR/SRV.php b/Net/DNS2/RR/SRV.php index e5cca0c3..b9f78d10 100644 --- a/Net/DNS2/RR/SRV.php +++ b/Net/DNS2/RR/SRV.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * SRV Resource Record - RFC2782 + * SRV Resource Record - RFC2782. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | PRIORITY | @@ -29,109 +29,90 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / TARGET / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_SRV extends Net_DNS2_RR { - /* - * The priority of this target host. - */ + // The priority of this target host. public $priority; - /* - * a relative weight for entries with the same priority - */ + // a relative weight for entries with the same priority public $weight; - /* - * The port on this target host of this service. - */ + // The port on this target host of this service. public $port; - /* - * The domain name of the target host - */ + // The domain name of the target host public $target; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->priority . ' ' . $this->weight . ' ' . - $this->port . ' ' . $this->cleanString($this->target) . '.'; + return $this->priority.' '.$this->weight.' ' + .$this->port.' '.$this->cleanString($this->target).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->priority = $rdata[0]; - $this->weight = $rdata[1]; - $this->port = $rdata[2]; + $this->weight = $rdata[1]; + $this->port = $rdata[2]; + + $this->target = $this->cleanString($rdata[3]); - $this->target = $this->cleanString($rdata[3]); - return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the priority, weight and port // $x = unpack('npriority/nweight/nport', $this->rdata); $this->priority = $x['priority']; - $this->weight = $x['weight']; - $this->port = $x['port']; + $this->weight = $x['weight']; + $this->port = $x['port']; - $offset = $packet->offset + 6; - $this->target = Net_DNS2_Packet::expand($packet, $offset); + $offset = $packet->offset + 6; + $this->target = Net_DNS2_Packet::expand($packet, $offset); return true; } - + return false; } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->target) > 0) { - $data = pack('nnn', $this->priority, $this->weight, $this->port); $packet->offset += 6; diff --git a/Net/DNS2/RR/SSHFP.php b/Net/DNS2/RR/SSHFP.php index 93f77395..f4e019ad 100644 --- a/Net/DNS2/RR/SSHFP.php +++ b/Net/DNS2/RR/SSHFP.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * SSHFP Resource Record - RFC4255 section 3.1 + * SSHFP Resource Record - RFC4255 section 3.1. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,81 +28,64 @@ * / fingerprint / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_SSHFP extends Net_DNS2_RR { - /* - * the algorithm used - */ + // Algorithms + public const SSHFP_ALGORITHM_RES = 0; + public const SSHFP_ALGORITHM_RSA = 1; + public const SSHFP_ALGORITHM_DSS = 2; + public const SSHFP_ALGORITHM_ECDSA = 3; + public const SSHFP_ALGORITHM_ED25519 = 4; + + // Fingerprint Types + public const SSHFP_FPTYPE_RES = 0; + public const SSHFP_FPTYPE_SHA1 = 1; + public const SSHFP_FPTYPE_SHA256 = 2; + // the algorithm used public $algorithm; - /* - * The finger print type - */ + // The finger print type public $fp_type; - /* - * the finger print data - */ + // the finger print data public $fingerprint; - /* - * Algorithms - */ - const SSHFP_ALGORITHM_RES = 0; - const SSHFP_ALGORITHM_RSA = 1; - const SSHFP_ALGORITHM_DSS = 2; - const SSHFP_ALGORITHM_ECDSA = 3; - const SSHFP_ALGORITHM_ED25519 = 4; - - /* - * Fingerprint Types - */ - const SSHFP_FPTYPE_RES = 0; - const SSHFP_FPTYPE_SHA1 = 1; - const SSHFP_FPTYPE_SHA256 = 2; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->algorithm . ' ' . $this->fp_type . ' ' . $this->fingerprint; + return $this->algorithm.' '.$this->fp_type.' '.$this->fingerprint; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { // // "The use of mnemonics instead of numbers is not allowed." - // + // // RFC4255 section 3.2 // - $algorithm = array_shift($rdata); - $fp_type = array_shift($rdata); - $fingerprint = strtolower(implode('', $rdata)); + $algorithm = array_shift($rdata); + $fp_type = array_shift($rdata); + $fingerprint = strtolower(implode('', $rdata)); // - // There are only two algorithm's defined + // There are only two algorithm's defined // - if ( ($algorithm != self::SSHFP_ALGORITHM_RSA) - && ($algorithm != self::SSHFP_ALGORITHM_DSS) - && ($algorithm != self::SSHFP_ALGORITHM_ECDSA) - && ($algorithm != self::SSHFP_ALGORITHM_ED25519) + if ((self::SSHFP_ALGORITHM_RSA != $algorithm) + && (self::SSHFP_ALGORITHM_DSS != $algorithm) + && (self::SSHFP_ALGORITHM_ECDSA != $algorithm) + && (self::SSHFP_ALGORITHM_ED25519 != $algorithm) ) { return false; } @@ -110,47 +93,44 @@ protected function rrFromString(array $rdata) // // there are only two fingerprints defined // - if ( ($fp_type != self::SSHFP_FPTYPE_SHA1) - && ($fp_type != self::SSHFP_FPTYPE_SHA256) + if ((self::SSHFP_FPTYPE_SHA1 != $fp_type) + && (self::SSHFP_FPTYPE_SHA256 != $fp_type) ) { return false; } - $this->algorithm = $algorithm; - $this->fp_type = $fp_type; - $this->fingerprint = $fingerprint; + $this->algorithm = $algorithm; + $this->fp_type = $fp_type; + $this->fingerprint = $fingerprint; return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the algorithm and finger print type // $x = unpack('Calgorithm/Cfp_type', $this->rdata); - $this->algorithm = $x['algorithm']; - $this->fp_type = $x['fp_type']; + $this->algorithm = $x['algorithm']; + $this->fp_type = $x['fp_type']; // - // There are only three algorithm's defined + // There are only three algorithm's defined // - if ( ($this->algorithm != self::SSHFP_ALGORITHM_RSA) - && ($this->algorithm != self::SSHFP_ALGORITHM_DSS) - && ($this->algorithm != self::SSHFP_ALGORITHM_ECDSA) - && ($this->algorithm != self::SSHFP_ALGORITHM_ED25519) + if ((self::SSHFP_ALGORITHM_RSA != $this->algorithm) + && (self::SSHFP_ALGORITHM_DSS != $this->algorithm) + && (self::SSHFP_ALGORITHM_ECDSA != $this->algorithm) + && (self::SSHFP_ALGORITHM_ED25519 != $this->algorithm) ) { return false; } @@ -158,12 +138,12 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // there are only two fingerprints defined // - if ( ($this->fp_type != self::SSHFP_FPTYPE_SHA1) - && ($this->fp_type != self::SSHFP_FPTYPE_SHA256) + if ((self::SSHFP_FPTYPE_SHA1 != $this->fp_type) + && (self::SSHFP_FPTYPE_SHA256 != $this->fp_type) ) { return false; } - + // // parse the finger print; this assumes SHA-1 // @@ -177,22 +157,22 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->fingerprint) > 0) { - $data = pack( - 'CCH*', $this->algorithm, $this->fp_type, $this->fingerprint + 'CCH*', + $this->algorithm, + $this->fp_type, + $this->fingerprint ); $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/TA.php b/Net/DNS2/RR/TA.php index 23138b6f..4e4a2687 100644 --- a/Net/DNS2/RR/TA.php +++ b/Net/DNS2/RR/TA.php @@ -1,27 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.0 */ /** * The TA RR is implemented exactly like the DS record, so * for now we just extend the DS RR and use it. - * */ -class Net_DNS2_RR_TA extends Net_DNS2_RR_DS -{ -} +class Net_DNS2_RR_TA extends Net_DNS2_RR_DS {} diff --git a/Net/DNS2/RR/TALINK.php b/Net/DNS2/RR/TALINK.php index 265aee2b..7bbbd4a6 100644 --- a/Net/DNS2/RR/TALINK.php +++ b/Net/DNS2/RR/TALINK.php @@ -1,22 +1,22 @@ . All rights reserved. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.0 */ /** - * TALINK Resource Record - DNSSEC Trust Anchor + * TALINK Resource Record - DNSSEC Trust Anchor. * * http://tools.ietf.org/id/draft-ietf-dnsop-dnssec-trust-history-00.txt * @@ -25,67 +25,55 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / NEXT / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_TALINK extends Net_DNS2_RR { - /* - * the previous domain name - */ + // the previous domain name public $previous; - /* - * the next domain name - */ + // the next domain name public $next; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cleanString($this->previous) . '. ' . - $this->cleanString($this->next) . '.'; + return $this->cleanString($this->previous).'. ' + .$this->cleanString($this->next).'.'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->previous = $this->cleanString($rdata[0]); - $this->next = $this->cleanString($rdata[1]); + $this->next = $this->cleanString($rdata[1]); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - - $offset = $packet->offset; + $offset = $packet->offset; $this->previous = Net_DNS2_Packet::label($packet, $offset); - $this->next = Net_DNS2_Packet::label($packet, $offset); + $this->next = Net_DNS2_Packet::label($packet, $offset); return true; } @@ -94,22 +82,19 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ( (strlen($this->previous) > 0) || (strlen($this->next) > 0) ) { - - $data = chr(strlen($this->previous)) . $this->previous . - chr(strlen($this->next)) . $this->next; + if ((strlen($this->previous) > 0) || (strlen($this->next) > 0)) { + $data = chr(strlen($this->previous)).$this->previous + .chr(strlen($this->next)).$this->next; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/TKEY.php b/Net/DNS2/RR/TKEY.php index 1563ca99..fc317b3e 100644 --- a/Net/DNS2/RR/TKEY.php +++ b/Net/DNS2/RR/TKEY.php @@ -1,27 +1,27 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * TKEY Resource Record - RFC 2930 section 2 + * TKEY Resource Record - RFC 2930 section 2. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * / ALGORITHM / + * / ALGORITHM / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | INCEPTION | * | | @@ -41,10 +41,16 @@ * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / OTHER DATA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_TKEY extends Net_DNS2_RR { + // TSIG Modes + public const TSIG_MODE_RES = 0; + public const TSIG_MODE_SERV_ASSIGN = 1; + public const TSIG_MODE_DH = 2; + public const TSIG_MODE_GSS_API = 3; + public const TSIG_MODE_RESV_ASSIGN = 4; + public const TSIG_MODE_KEY_DELE = 5; public $algorithm; public $inception; public $expiration; @@ -55,44 +61,27 @@ class Net_DNS2_RR_TKEY extends Net_DNS2_RR public $other_size; public $other_data; - /* - * TSIG Modes - */ - const TSIG_MODE_RES = 0; - const TSIG_MODE_SERV_ASSIGN = 1; - const TSIG_MODE_DH = 2; - const TSIG_MODE_GSS_API = 3; - const TSIG_MODE_RESV_ASSIGN = 4; - const TSIG_MODE_KEY_DELE = 5; - - /* - * map the mod id's to names so we can validate - */ + // map the mod id's to names so we can validate public $tsgi_mode_id_to_name = [ - - self::TSIG_MODE_RES => 'Reserved', - self::TSIG_MODE_SERV_ASSIGN => 'Server Assignment', - self::TSIG_MODE_DH => 'Diffie-Hellman', - self::TSIG_MODE_GSS_API => 'GSS-API', - self::TSIG_MODE_RESV_ASSIGN => 'Resolver Assignment', - self::TSIG_MODE_KEY_DELE => 'Key Deletion' + self::TSIG_MODE_RES => 'Reserved', + self::TSIG_MODE_SERV_ASSIGN => 'Server Assignment', + self::TSIG_MODE_DH => 'Diffie-Hellman', + self::TSIG_MODE_GSS_API => 'GSS-API', + self::TSIG_MODE_RESV_ASSIGN => 'Resolver Assignment', + self::TSIG_MODE_KEY_DELE => 'Key Deletion', ]; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - $out = $this->cleanString($this->algorithm) . '. ' . $this->mode; + $out = $this->cleanString($this->algorithm).'. '.$this->mode; if ($this->key_size > 0) { - - $out .= ' ' . trim($this->key_data, '.') . '.'; + $out .= ' '.trim($this->key_data, '.').'.'; } else { - $out .= ' .'; } @@ -100,68 +89,63 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { // // data passed in is assumed: // - $this->algorithm = $this->cleanString(array_shift($rdata)); - $this->mode = array_shift($rdata); - $this->key_data = trim(array_shift($rdata), '.'); + $this->algorithm = $this->cleanString(array_shift($rdata)); + $this->mode = array_shift($rdata); + $this->key_data = trim(array_shift($rdata), '.'); // // the rest of the data is set manually // - $this->inception = time(); - $this->expiration = time() + 86400; // 1 day - $this->error = 0; - $this->key_size = strlen($this->key_data); - $this->other_size = 0; - $this->other_data = ''; + $this->inception = time(); + $this->expiration = time() + 86400; // 1 day + $this->error = 0; + $this->key_size = strlen($this->key_data); + $this->other_size = 0; + $this->other_data = ''; return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // expand the algorithm // $offset = $packet->offset; $this->algorithm = Net_DNS2_Packet::expand($packet, $offset); - + // // unpack inception, expiration, mode, error and key size // $x = unpack( - '@' . $offset . '/Ninception/Nexpiration/nmode/nerror/nkey_size', + '@'.$offset.'/Ninception/Nexpiration/nmode/nerror/nkey_size', $packet->rdata ); - $this->inception = Net_DNS2::expandUint32($x['inception']); - $this->expiration = Net_DNS2::expandUint32($x['expiration']); - $this->mode = $x['mode']; - $this->error = $x['error']; - $this->key_size = $x['key_size']; + $this->inception = Net_DNS2::expandUint32($x['inception']); + $this->expiration = Net_DNS2::expandUint32($x['expiration']); + $this->mode = $x['mode']; + $this->error = $x['error']; + $this->key_size = $x['key_size']; $offset += 14; @@ -169,7 +153,6 @@ protected function rrSet(Net_DNS2_Packet &$packet) // if key_size > 0, then copy out the key // if ($this->key_size > 0) { - $this->key_data = substr($packet->rdata, $offset, $this->key_size); $offset += $this->key_size; } @@ -177,8 +160,8 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the other length // - $x = unpack('@' . $offset . '/nother_size', $packet->rdata); - + $x = unpack('@'.$offset.'/nother_size', $packet->rdata); + $this->other_size = $x['other_size']; $offset += 2; @@ -186,9 +169,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) // if other_size > 0, then copy out the data // if ($this->other_size > 0) { - $this->other_data = substr( - $packet->rdata, $offset, $this->other_size + $packet->rdata, + $offset, + $this->other_size ); } @@ -199,25 +183,22 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->algorithm) > 0) { - // // make sure the size values are correct // - $this->key_size = strlen($this->key_data); - $this->other_size = strlen($this->other_data); + $this->key_size = strlen($this->key_data); + $this->other_size = strlen($this->other_data); // // add the algorithm without compression @@ -228,15 +209,18 @@ protected function rrGet(Net_DNS2_Packet &$packet) // pack in the inception, expiration, mode, error and key size // $data .= pack( - 'NNnnn', $this->inception, $this->expiration, - $this->mode, 0, $this->key_size + 'NNnnn', + $this->inception, + $this->expiration, + $this->mode, + 0, + $this->key_size ); // // if the key_size > 0, then add the key // if ($this->key_size > 0) { - $data .= $this->key_data; } @@ -245,7 +229,6 @@ protected function rrGet(Net_DNS2_Packet &$packet) // $data .= pack('n', $this->other_size); if ($this->other_size > 0) { - $data .= $this->other_data; } diff --git a/Net/DNS2/RR/TLSA.php b/Net/DNS2/RR/TLSA.php index cf06be7f..9e3a6d6f 100644 --- a/Net/DNS2/RR/TLSA.php +++ b/Net/DNS2/RR/TLSA.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.5 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.5 */ /** - * TLSA Resource Record - RFC 6698 + * TLSA Resource Record - RFC 6698. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,88 +28,72 @@ * / Certificate Association Data / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_TLSA extends Net_DNS2_RR { - /* - * The Certificate Usage Field - */ + // The Certificate Usage Field public $cert_usage; - /* - * The Selector Field - */ + // The Selector Field public $selector; - /* - * The Matching Type Field - */ + // The Matching Type Field public $matching_type; - /* - * The Certificate Association Data Field - */ + // The Certificate Association Data Field public $certificate; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - return $this->cert_usage . ' ' . $this->selector . ' ' . - $this->matching_type . ' ' . base64_encode($this->certificate); + return $this->cert_usage.' '.$this->selector.' ' + .$this->matching_type.' '.base64_encode($this->certificate); } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->cert_usage = array_shift($rdata); - $this->selector = array_shift($rdata); - $this->matching_type = array_shift($rdata); - $this->certificate = base64_decode(implode('', $rdata)); + $this->cert_usage = array_shift($rdata); + $this->selector = array_shift($rdata); + $this->matching_type = array_shift($rdata); + $this->certificate = base64_decode(implode('', $rdata)); return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the format, keytag and algorithm // $x = unpack('Cusage/Cselector/Ctype', $this->rdata); - $this->cert_usage = $x['usage']; - $this->selector = $x['selector']; - $this->matching_type = $x['type']; + $this->cert_usage = $x['usage']; + $this->selector = $x['selector']; + $this->matching_type = $x['type']; // // copy the certificate // - $this->certificate = substr($this->rdata, 3, $this->rdlength - 3); + $this->certificate = substr($this->rdata, 3, $this->rdlength - 3); return true; } @@ -118,23 +102,23 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->certificate) > 0) { - $data = pack( - 'CCC', $this->cert_usage, $this->selector, $this->matching_type - ) . $this->certificate; + 'CCC', + $this->cert_usage, + $this->selector, + $this->matching_type + ).$this->certificate; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/TSIG.php b/Net/DNS2/RR/TSIG.php index 265ff040..fffc7987 100644 --- a/Net/DNS2/RR/TSIG.php +++ b/Net/DNS2/RR/TSIG.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * TSIG Resource Record - RFC 2845 + * TSIG Resource Record - RFC 2845. * * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -39,418 +39,388 @@ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / * / other data / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_TSIG extends Net_DNS2_RR { - /* - * TSIG Algorithm Identifiers - */ - const HMAC_MD5 = 'hmac-md5.sig-alg.reg.int'; // RFC 2845, required - const GSS_TSIG = 'gss-tsig'; // unsupported, optional - const HMAC_SHA1 = 'hmac-sha1'; // RFC 4635, required - const HMAC_SHA224 = 'hmac-sha224'; // RFC 4635, optional - const HMAC_SHA256 = 'hmac-sha256'; // RFC 4635, required - const HMAC_SHA384 = 'hmac-sha384'; // RFC 4635, optional - const HMAC_SHA512 = 'hmac-sha512'; // RFC 4635, optional - - /* - * the map of hash values to names - */ - public static $hash_algorithms = [ - - self::HMAC_MD5 => 'md5', - self::HMAC_SHA1 => 'sha1', - self::HMAC_SHA224 => 'sha224', - self::HMAC_SHA256 => 'sha256', - self::HMAC_SHA384 => 'sha384', - self::HMAC_SHA512 => 'sha512' - ]; - - /* - * algorithm used; only supports HMAC-MD5 - */ - public $algorithm; - - /* - * The time it was signed - */ - public $time_signed; - - /* - * fudge- allowed offset from the time signed - */ - public $fudge; - - /* - * size of the digest - */ - public $mac_size; - - /* - * the digest data - */ - public $mac; - - /* - * the original id of the request - */ - public $original_id; - - /* - * additional error code - */ - public $error; - - /* - * length of the "other" data, should only ever be 0 when there is - * no error, or 6 when there is the error RCODE_BADTIME - */ - public $other_length; - - /* - * the other data; should only ever be a timestamp when there is the - * error RCODE_BADTIME - */ - public $other_data; - - /* - * the key to use for signing - passed in, not included in the rdata - */ - public $key; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - $out = $this->cleanString($this->algorithm) . '. ' . - $this->time_signed . ' ' . - $this->fudge . ' ' . $this->mac_size . ' ' . - base64_encode($this->mac) . ' ' . $this->original_id . ' ' . - $this->error . ' '. $this->other_length; - - if ($this->other_length > 0) { - - $out .= ' ' . $this->other_data; - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - // - // the only value passed in is the key- - // - // this assumes it's passed in base64 encoded. - // - $this->key = preg_replace('/\s+/', '', array_shift($rdata)); - - // - // the rest of the data is set to default - // - $this->algorithm = self::HMAC_MD5; - $this->time_signed = time(); - $this->fudge = 300; - $this->mac_size = 0; - $this->mac = ''; - $this->original_id = 0; - $this->error = 0; - $this->other_length = 0; - $this->other_data = ''; - - // - // per RFC 2845 section 2.3 - // - $this->class = 'ANY'; - $this->ttl = 0; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - // - // expand the algorithm - // - $newoffset = $packet->offset; - $this->algorithm = Net_DNS2_Packet::expand($packet, $newoffset); - $offset = $newoffset - $packet->offset; - - // - // unpack time, fudge and mac_size - // - $x = unpack( - '@' . $offset . '/ntime_high/Ntime_low/nfudge/nmac_size', - $this->rdata - ); - - $this->time_signed = Net_DNS2::expandUint32($x['time_low']); - $this->fudge = $x['fudge']; - $this->mac_size = $x['mac_size']; - - $offset += 10; - - // - // copy out the mac - // - if ($this->mac_size > 0) { - - $this->mac = substr($this->rdata, $offset, $this->mac_size); - $offset += $this->mac_size; - } - - // - // unpack the original id, error, and other_length values - // - $x = unpack( - '@' . $offset . '/noriginal_id/nerror/nother_length', - $this->rdata - ); - - $this->original_id = $x['original_id']; - $this->error = $x['error']; - $this->other_length = $x['other_length']; - - // - // the only time there is actually any "other data", is when there's - // a BADTIME error code. - // - // The other length should be 6, and the other data field includes the - // servers current time - per RFC 2845 section 4.5.2 - // - if ($this->error == Net_DNS2_Lookups::RCODE_BADTIME) { - - if ($this->other_length != 6) { - - return false; - } - - // - // other data is a 48bit timestamp - // - $x = unpack( - 'nhigh/nlow', - substr($this->rdata, $offset + 6, $this->other_length) - ); - $this->other_data = $x['low']; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->key) > 0) { - - // - // create a new packet for the signature- - // - $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); - - // - // copy the packet data over - // - $new_packet->copy($packet); - - // - // remove the TSIG object from the additional list - // - array_pop($new_packet->additional); - $new_packet->header->arcount = cacti_sizeof($new_packet->additional); - - // - // copy out the data - // - $sig_data = $new_packet->get(); - - // - // add the name without compressing - // - $sig_data .= Net_DNS2_Packet::pack($this->name); - - // - // add the class and TTL - // - $sig_data .= pack( - 'nN', Net_DNS2_Lookups::$classes_by_name[$this->class], $this->ttl - ); - - // - // add the algorithm name without compression - // - $sig_data .= Net_DNS2_Packet::pack(strtolower($this->algorithm)); - - // - // add the rest of the values - // - $sig_data .= pack( - 'nNnnn', 0, $this->time_signed, $this->fudge, - $this->error, $this->other_length - ); - if ($this->other_length > 0) { - - $sig_data .= pack('nN', 0, $this->other_data); - } - - // - // sign the data - // - $this->mac = $this->_signHMAC( - $sig_data, base64_decode($this->key), $this->algorithm - ); - $this->mac_size = strlen($this->mac); - - // - // compress the algorithm - // - $data = Net_DNS2_Packet::pack(strtolower($this->algorithm)); - - // - // pack the time, fudge and mac size - // - $data .= pack( - 'nNnn', 0, $this->time_signed, $this->fudge, $this->mac_size - ); - $data .= $this->mac; - - // - // check the error and other_length - // - if ($this->error == Net_DNS2_Lookups::RCODE_BADTIME) { - - $this->other_length = strlen($this->other_data); - if ($this->other_length != 6) { - - return null; - } - } else { - - $this->other_length = 0; - $this->other_data = ''; - } - - // - // pack the id, error and other_length - // - $data .= pack( - 'nnn', $packet->header->id, $this->error, $this->other_length - ); - if ($this->other_length > 0) { - - $data .= pack('nN', 0, $this->other_data); - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } - - /** - * signs the given data with the given key, and returns the result - * - * @param string $data the data to sign - * @param string $key key to use for signing - * @param string $algorithm the algorithm to use; defaults to MD5 - * - * @return string the signed digest - * @throws Net_DNS2_Exception - * @access private - * - */ - private function _signHMAC($data, $key = null, $algorithm = self::HMAC_MD5) - { - // - // use the hash extension; this is included by default in >= 5.1.2 which - // is our dependent version anyway- so it's easy to switch to it. - // - if (extension_loaded('hash')) { - - if (!isset(self::$hash_algorithms[$algorithm])) { - - throw new Net_DNS2_Exception( - 'invalid or unsupported algorithm', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - return hash_hmac(self::$hash_algorithms[$algorithm], $data, $key, true); - } - - // - // if the hash extension isn't loaded, and they selected something other - // than MD5, throw an exception - // - if ($algorithm != self::HMAC_MD5) { - - throw new Net_DNS2_Exception( - 'only HMAC-MD5 supported. please install the php-extension ' . - '"hash" in order to use the sha-family', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - // - // otherwise, do it ourselves - // - if (is_null($key)) { - - return pack('H*', md5($data)); - } - - $key = str_pad($key, 64, chr(0x00)); - if (strlen($key) > 64) { - - $key = pack('H*', md5($key)); - } - - $k_ipad = $key ^ str_repeat(chr(0x36), 64); - $k_opad = $key ^ str_repeat(chr(0x5c), 64); - - return $this->_signHMAC( - $k_opad . pack('H*', md5($k_ipad . $data)), null, $algorithm - ); - } + // TSIG Algorithm Identifiers + public const HMAC_MD5 = 'hmac-md5.sig-alg.reg.int'; // RFC 2845, required + public const GSS_TSIG = 'gss-tsig'; // unsupported, optional + public const HMAC_SHA1 = 'hmac-sha1'; // RFC 4635, required + public const HMAC_SHA224 = 'hmac-sha224'; // RFC 4635, optional + public const HMAC_SHA256 = 'hmac-sha256'; // RFC 4635, required + public const HMAC_SHA384 = 'hmac-sha384'; // RFC 4635, optional + public const HMAC_SHA512 = 'hmac-sha512'; // RFC 4635, optional + + // the map of hash values to names + public static $hash_algorithms = [ + self::HMAC_MD5 => 'md5', + self::HMAC_SHA1 => 'sha1', + self::HMAC_SHA224 => 'sha224', + self::HMAC_SHA256 => 'sha256', + self::HMAC_SHA384 => 'sha384', + self::HMAC_SHA512 => 'sha512', + ]; + + // algorithm used; only supports HMAC-MD5 + public $algorithm; + + // The time it was signed + public $time_signed; + + // fudge- allowed offset from the time signed + public $fudge; + + // size of the digest + public $mac_size; + + // the digest data + public $mac; + + // the original id of the request + public $original_id; + + // additional error code + public $error; + + /* + * length of the "other" data, should only ever be 0 when there is + * no error, or 6 when there is the error RCODE_BADTIME + */ + public $other_length; + + /* + * the other data; should only ever be a timestamp when there is the + * error RCODE_BADTIME + */ + public $other_data; + + // the key to use for signing - passed in, not included in the rdata + public $key; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + $out = $this->cleanString($this->algorithm).'. ' + .$this->time_signed.' ' + .$this->fudge.' '.$this->mac_size.' ' + .base64_encode($this->mac).' '.$this->original_id.' ' + .$this->error.' '.$this->other_length; + + if ($this->other_length > 0) { + $out .= ' '.$this->other_data; + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + // + // the only value passed in is the key- + // + // this assumes it's passed in base64 encoded. + // + $this->key = preg_replace('/\s+/', '', array_shift($rdata)); + + // + // the rest of the data is set to default + // + $this->algorithm = self::HMAC_MD5; + $this->time_signed = time(); + $this->fudge = 300; + $this->mac_size = 0; + $this->mac = ''; + $this->original_id = 0; + $this->error = 0; + $this->other_length = 0; + $this->other_data = ''; + + // + // per RFC 2845 section 2.3 + // + $this->class = 'ANY'; + $this->ttl = 0; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + // + // expand the algorithm + // + $newoffset = $packet->offset; + $this->algorithm = Net_DNS2_Packet::expand($packet, $newoffset); + $offset = $newoffset - $packet->offset; + + // + // unpack time, fudge and mac_size + // + $x = unpack( + '@'.$offset.'/ntime_high/Ntime_low/nfudge/nmac_size', + $this->rdata + ); + + $this->time_signed = Net_DNS2::expandUint32($x['time_low']); + $this->fudge = $x['fudge']; + $this->mac_size = $x['mac_size']; + + $offset += 10; + + // + // copy out the mac + // + if ($this->mac_size > 0) { + $this->mac = substr($this->rdata, $offset, $this->mac_size); + $offset += $this->mac_size; + } + + // + // unpack the original id, error, and other_length values + // + $x = unpack( + '@'.$offset.'/noriginal_id/nerror/nother_length', + $this->rdata + ); + + $this->original_id = $x['original_id']; + $this->error = $x['error']; + $this->other_length = $x['other_length']; + + // + // the only time there is actually any "other data", is when there's + // a BADTIME error code. + // + // The other length should be 6, and the other data field includes the + // servers current time - per RFC 2845 section 4.5.2 + // + if (Net_DNS2_Lookups::RCODE_BADTIME == $this->error) { + if (6 != $this->other_length) { + return false; + } + + // + // other data is a 48bit timestamp + // + $x = unpack( + 'nhigh/nlow', + substr($this->rdata, $offset + 6, $this->other_length) + ); + $this->other_data = $x['low']; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if (strlen($this->key) > 0) { + // + // create a new packet for the signature- + // + $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); + + // + // copy the packet data over + // + $new_packet->copy($packet); + + // + // remove the TSIG object from the additional list + // + array_pop($new_packet->additional); + $new_packet->header->arcount = cacti_sizeof($new_packet->additional); + + // + // copy out the data + // + $sig_data = $new_packet->get(); + + // + // add the name without compressing + // + $sig_data .= Net_DNS2_Packet::pack($this->name); + + // + // add the class and TTL + // + $sig_data .= pack( + 'nN', + Net_DNS2_Lookups::$classes_by_name[$this->class], + $this->ttl + ); + + // + // add the algorithm name without compression + // + $sig_data .= Net_DNS2_Packet::pack(strtolower($this->algorithm)); + + // + // add the rest of the values + // + $sig_data .= pack( + 'nNnnn', + 0, + $this->time_signed, + $this->fudge, + $this->error, + $this->other_length + ); + if ($this->other_length > 0) { + $sig_data .= pack('nN', 0, $this->other_data); + } + + // + // sign the data + // + $this->mac = $this->_signHMAC( + $sig_data, + base64_decode($this->key), + $this->algorithm + ); + $this->mac_size = strlen($this->mac); + + // + // compress the algorithm + // + $data = Net_DNS2_Packet::pack(strtolower($this->algorithm)); + + // + // pack the time, fudge and mac size + // + $data .= pack( + 'nNnn', + 0, + $this->time_signed, + $this->fudge, + $this->mac_size + ); + $data .= $this->mac; + + // + // check the error and other_length + // + if (Net_DNS2_Lookups::RCODE_BADTIME == $this->error) { + $this->other_length = strlen($this->other_data); + if (6 != $this->other_length) { + return null; + } + } else { + $this->other_length = 0; + $this->other_data = ''; + } + + // + // pack the id, error and other_length + // + $data .= pack( + 'nnn', + $packet->header->id, + $this->error, + $this->other_length + ); + if ($this->other_length > 0) { + $data .= pack('nN', 0, $this->other_data); + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } + + /** + * signs the given data with the given key, and returns the result. + * + * @param string $data the data to sign + * @param string $key key to use for signing + * @param string $algorithm the algorithm to use; defaults to MD5 + * + * @return string the signed digest + * + * @throws Net_DNS2_Exception + */ + private function _signHMAC($data, $key = null, $algorithm = self::HMAC_MD5) + { + // + // use the hash extension; this is included by default in >= 5.1.2 which + // is our dependent version anyway- so it's easy to switch to it. + // + if (extension_loaded('hash')) { + if (!isset(self::$hash_algorithms[$algorithm])) { + throw new Net_DNS2_Exception( + 'invalid or unsupported algorithm', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + return hash_hmac(self::$hash_algorithms[$algorithm], $data, $key, true); + } + + // + // if the hash extension isn't loaded, and they selected something other + // than MD5, throw an exception + // + if (self::HMAC_MD5 != $algorithm) { + throw new Net_DNS2_Exception( + 'only HMAC-MD5 supported. please install the php-extension ' + .'"hash" in order to use the sha-family', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + // + // otherwise, do it ourselves + // + if (is_null($key)) { + return pack('H*', md5($data)); + } + + $key = str_pad($key, 64, chr(0x00)); + if (strlen($key) > 64) { + $key = pack('H*', md5($key)); + } + + $k_ipad = $key ^ str_repeat(chr(0x36), 64); + $k_opad = $key ^ str_repeat(chr(0x5C), 64); + + return $this->_signHMAC( + $k_opad.pack('H*', md5($k_ipad.$data)), + null, + $algorithm + ); + } } diff --git a/Net/DNS2/RR/TXT.php b/Net/DNS2/RR/TXT.php index b2b86569..e9d40b45 100644 --- a/Net/DNS2/RR/TXT.php +++ b/Net/DNS2/RR/TXT.php @@ -8,122 +8,106 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * TXT Resource Record - RFC1035 section 3.3.14 + * TXT Resource Record - RFC1035 section 3.3.14. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / TXT-DATA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_TXT extends Net_DNS2_RR { - /* - * an array of the text strings - */ - public $text = []; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - if (cacti_sizeof($this->text) == 0) { - return '""'; - } - - $data = ''; - - foreach ($this->text as $t) { - - $data .= $this->formatString($t) . ' '; - } - - return trim($data); - } - - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (cacti_sizeof($data) > 0) { - - $this->text = $data; - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - - $length = $packet->offset + $this->rdlength; - $offset = $packet->offset; - - while ($length > $offset) { - - $this->text[] = Net_DNS2_Packet::label($packet, $offset); - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = null; - - foreach ($this->text as $t) { - - $data .= chr(strlen($t)) . $t; - } - - $packet->offset += strlen($data); - - return $data; - } + // an array of the text strings + public $text = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + if (0 == cacti_sizeof($this->text)) { + return '""'; + } + + $data = ''; + + foreach ($this->text as $t) { + $data .= $this->formatString($t).' '; + } + + return trim($data); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $data = $this->buildString($rdata); + if (cacti_sizeof($data) > 0) { + $this->text = $data; + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $length = $packet->offset + $this->rdlength; + $offset = $packet->offset; + + while ($length > $offset) { + $this->text[] = Net_DNS2_Packet::label($packet, $offset); + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + $data = null; + + foreach ($this->text as $t) { + $data .= chr(strlen($t)).$t; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/TYPE65534.php b/Net/DNS2/RR/TYPE65534.php index 9722866d..8bcf8d53 100644 --- a/Net/DNS2/RR/TYPE65534.php +++ b/Net/DNS2/RR/TYPE65534.php @@ -1,43 +1,38 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.5 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.5 */ /** - * TYPE65534 - Private space + * TYPE65534 - Private space. * * Since Bind 9.8 beta, it use a private recode as documented - * in the Bind ARM, chapter 4, "Private-type records. + * in the Bind ARM, chapter 4, "Private-type records. * Basically they store signing process state. - * */ class Net_DNS2_RR_TYPE65534 extends Net_DNS2_RR { - /* - * The Private data field - */ + // The Private data field public $private_data; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { @@ -45,13 +40,11 @@ protected function rrToString() } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { @@ -61,18 +54,16 @@ protected function rrFromString(array $rdata) } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $this->private_data = $this->rdata; + $this->private_data = $this->rdata; return true; } @@ -81,20 +72,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->private_data) > 0) { - $data = $this->private_data; $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/URI.php b/Net/DNS2/RR/URI.php index 3be89e98..125081b6 100644 --- a/Net/DNS2/RR/URI.php +++ b/Net/DNS2/RR/URI.php @@ -8,17 +8,17 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.2.0 * + * @see https://netdns2.com/ + * @since File available since Release 1.2.0 */ /** - * URI Resource Record - http://tools.ietf.org/html/draft-faltstrom-uri-06 + * URI Resource Record - http://tools.ietf.org/html/draft-faltstrom-uri-06. * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -28,101 +28,84 @@ * / Target / * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * */ class Net_DNS2_RR_URI extends Net_DNS2_RR { - /* - * The priority of this target host. - */ + // The priority of this target host. public $priority; - /* - * a relative weight for entries with the same priority - */ + // a relative weight for entries with the same priority public $weight; - /* - * The domain name of the target host - */ + // The domain name of the target host public $target; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { // // presentation format has double quotes (") around the target. // - return $this->priority . ' ' . $this->weight . ' "' . $this->target . '"'; + return $this->priority.' '.$this->weight.' "'.$this->target.'"'; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { $this->priority = $rdata[0]; - $this->weight = $rdata[1]; - $this->target = trim(strtolower(trim($rdata[2])), '"'); - + $this->weight = $rdata[1]; + $this->target = trim(strtolower(trim($rdata[2])), '"'); + return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // unpack the priority and weight // $x = unpack('npriority/nweight/a*target', $this->rdata); $this->priority = $x['priority']; - $this->weight = $x['weight']; - $this->target = $x['target']; + $this->weight = $x['weight']; + $this->target = $x['target']; return true; } - + return false; } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->target) > 0) { - $data = pack('nna*', $this->priority, $this->weight, $this->target); $packet->offset += strlen($data); diff --git a/Net/DNS2/RR/WKS.php b/Net/DNS2/RR/WKS.php index 75a94e41..403c1274 100644 --- a/Net/DNS2/RR/WKS.php +++ b/Net/DNS2/RR/WKS.php @@ -1,24 +1,24 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 1.0.1 * + * @see https://netdns2.com/ + * @since File available since Release 1.0.1 */ /** - * WKS Resource Record - RFC1035 section 3.4.2 + * WKS Resource Record - RFC1035 section 3.4.2. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * | ADDRESS | @@ -29,80 +29,66 @@ * / / * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_WKS extends Net_DNS2_RR { - /* - * The IP address of the service - */ + // The IP address of the service public $address; - /* - * The protocol of the service - */ + // The protocol of the service public $protocol; - /* - * bitmap - */ + // bitmap public $bitmap = []; /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected + * method to return the rdata portion of the packet as a string. * + * @return string */ protected function rrToString() { - $data = $this->address . ' ' . $this->protocol; + $data = $this->address.' '.$this->protocol; foreach ($this->bitmap as $port) { - $data .= ' ' . $port; + $data .= ' '.$port; } return $data; } /** - * parses the rdata portion from a standard DNS config line + * parses the rdata portion from a standard DNS config line. * * @param array $rdata a string split line of values for the rdata * - * @return boolean - * @access protected - * + * @return bool */ protected function rrFromString(array $rdata) { - $this->address = strtolower(trim(array_shift($rdata), '.')); + $this->address = strtolower(trim(array_shift($rdata), '.')); $this->protocol = array_shift($rdata); - $this->bitmap = $rdata; + $this->bitmap = $rdata; return true; } /** - * parses the rdata of the Net_DNS2_Packet object + * parses the rdata of the Net_DNS2_Packet object. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from * - * @return boolean - * @access protected - * + * @return bool */ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - // // get the address and protocol value // $x = unpack('Naddress/Cprotocol', $this->rdata); - $this->address = long2ip($x['address']); + $this->address = long2ip($x['address']); $this->protocol = $x['protocol']; // @@ -110,11 +96,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $port = 0; foreach (unpack('@5/C*', $this->rdata) as $set) { - $s = sprintf('%08b', $set); - for ($i=0; $i<8; $i++, $port++) { - if ($s[$i] == '1') { + for ($i = 0; $i < 8; $i++, $port++) { + if ('1' == $s[$i]) { $this->bitmap[] = $port; } } @@ -127,20 +112,17 @@ protected function rrSet(Net_DNS2_Packet &$packet) } /** - * returns the rdata portion of the DNS packet + * returns the rdata portion of the DNS packet. * * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for * compressed names * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * + * @return mixed either returns a binary packed + * string or null on failure */ protected function rrGet(Net_DNS2_Packet &$packet) { if (strlen($this->address) > 0) { - $data = pack('NC', ip2long($this->address), $this->protocol); $ports = []; @@ -153,7 +135,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) $n = $port; } } - for ($i=0; $i * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** - * X25 Resource Record - RFC1183 section 3.1 + * X25 Resource Record - RFC1183 section 3.1. * * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ * / PSDN-address / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - * */ class Net_DNS2_RR_X25 extends Net_DNS2_RR { - /* - * The PSDN address - */ - public $psdnaddress; - - /** - * method to return the rdata portion of the packet as a string - * - * @return string - * @access protected - * - */ - protected function rrToString() - { - return $this->formatString($this->psdnaddress); - } + // The PSDN address + public $psdnaddress; - /** - * parses the rdata portion from a standard DNS config line - * - * @param array $rdata a string split line of values for the rdata - * - * @return boolean - * @access protected - * - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (cacti_sizeof($data) == 1) { + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() + { + return $this->formatString($this->psdnaddress); + } - $this->psdnaddress = $data[0]; - return true; - } + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) + { + $data = $this->buildString($rdata); + if (1 == cacti_sizeof($data)) { + $this->psdnaddress = $data[0]; - return false; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return boolean - * @access protected - * - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { + return false; + } - $this->psdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); - return true; - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) + { + if ($this->rdlength > 0) { + $this->psdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); - return false; - } + return true; + } - /** - * returns the rdata portion of the DNS packet - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - * @access protected - * - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->psdnaddress) > 0) { + return false; + } - $data = chr(strlen($this->psdnaddress)) . $this->psdnaddress; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) + { + if (strlen($this->psdnaddress) > 0) { + $data = chr(strlen($this->psdnaddress)).$this->psdnaddress; - $packet->offset += strlen($data); + $packet->offset += strlen($data); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/Resolver.php b/Net/DNS2/Resolver.php index 0586ec95..1fa1e685 100644 --- a/Net/DNS2/Resolver.php +++ b/Net/DNS2/Resolver.php @@ -8,277 +8,264 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** * This is the main resolver class, providing DNS query functions. - * */ class Net_DNS2_Resolver extends Net_DNS2 { - /** - * Constructor - creates a new Net_DNS2_Resolver object - * - * @param mixed $options either an array with options or null - * - * @access public - * - */ - public function __construct(array $options = null) - { - parent::__construct($options); - } - - /** - * does a basic DNS lookup query - * - * @param string $name the DNS name to loookup - * @param string $type the name of the RR type to lookup - * @param string $class the name of the RR class to lookup - * - * @return Net_DNS2_Packet_Response object - * @throws Net_DNS2_Exception - * @access public - * - */ - public function query($name, $type = 'A', $class = 'IN') - { - // - // make sure we have some name servers set - // - $this->checkServers(Net_DNS2::RESOLV_CONF); - - // - // we don't support incremental zone transfers; so if it's requested, a full - // zone transfer can be returned - // - if ($type == 'IXFR') { - - $type = 'AXFR'; - } - - // - // if the name *looks* too short, then append the domain from the config - // - if ( (strpos($name, '.') === false) && ($type != 'PTR') ) { - - $name .= '.' . strtolower($this->domain); - } - - // - // create a new packet based on the input - // - $packet = new Net_DNS2_Packet_Request($name, $type, $class); - - // - // check for an authentication method; either TSIG or SIG - // - if ( ($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $packet->additional[] = $this->auth_signature; - $packet->header->arcount = cacti_sizeof($packet->additional); - } - - // - // check for the DNSSEC flag, and if it's true, then add an OPT - // RR to the additional section, and set the DO flag to 1. - // - if ($this->dnssec == true) { - - // - // create a new OPT RR - // - $opt = new Net_DNS2_RR_OPT(); - - // - // set the DO flag, and the other values - // - $opt->do = 1; - $opt->class = $this->dnssec_payload_size; - - // - // add the RR to the additional section. - // - $packet->additional[] = $opt; - $packet->header->arcount = cacti_sizeof($packet->additional); - } - - // - // set the DNSSEC AD or CD bits - // - if ($this->dnssec_ad_flag == true) { - - $packet->header->ad = 1; - } - if ($this->dnssec_cd_flag == true) { - - $packet->header->cd = 1; - } - - // - // if caching is turned on, then check then hash the question, and - // do a cache lookup. - // - // don't use the cache for zone transfers - // - $packet_hash = ''; - - if ( ($this->use_cache == true) && ($this->cacheable($type) == true) ) { - - // - // open the cache - // - $this->cache->open( - $this->cache_file, $this->cache_size, $this->cache_serializer - ); - - // - // build the key and check for it in the cache. - // - $packet_hash = md5( - $packet->question[0]->qname . '|' . $packet->question[0]->qtype - ); - - if ($this->cache->has($packet_hash)) { - - return $this->cache->get($packet_hash); - } - } - - // - // set the RD (recursion desired) bit to 1 / 0 depending on the config - // setting. - // - if ($this->recurse == false) { - $packet->header->rd = 0; - } else { - $packet->header->rd = 1; - } - - // - // send the packet and get back the response - // - // *always* use TCP for zone transfers- does this cause any problems? - // - $response = $this->sendPacket( - $packet, ($type == 'AXFR') ? true : $this->use_tcp - ); - - // - // if strict mode is enabled, then make sure that the name that was - // looked up is *actually* in the response object. - // - // only do this is strict_query_mode is turned on, AND we've received - // some answers; no point doing any else if there were no answers. - // - if ( ($this->strict_query_mode == true) - && ($response->header->ancount > 0) - ) { - - $found = false; - - // - // look for the requested name/type/class - // - foreach ($response->answer as $index => $object) { - - if ( (strcasecmp(trim($object->name, '.'), trim($packet->question[0]->qname, '.')) == 0) - && ($object->type == $packet->question[0]->qtype) - && ($object->class == $packet->question[0]->qclass) - ) { - $found = true; - break; - } - } - - // - // if it's not found, then unset the answer section; it's not correct to - // throw an exception here; if the hostname didn't exist, then - // sendPacket() would have already thrown an NXDOMAIN error- so the host - // *exists*, but just not the request type/class. - // - // the correct response in this case, is an empty answer section; the - // authority section may still have usual information, like a SOA record. - // - if ($found == false) { - - $response->answer = []; - $response->header->ancount = 0; - } - } - - // - // cache the response object - // - if ( ($this->use_cache == true) && ($this->cacheable($type) == true) ) { - - $this->cache->put($packet_hash, $response); - } - - return $response; - } - - /** - * does an inverse query for the given RR; most DNS servers do not implement - * inverse queries, but they should be able to return "not implemented" - * - * @param Net_DNS2_RR $rr the RR object to lookup - * - * @return Net_DNS2_RR object - * @throws Net_DNS2_Exception - * @access public - * - */ - public function iquery(Net_DNS2_RR $rr) - { - // - // make sure we have some name servers set - // - $this->checkServers(Net_DNS2::RESOLV_CONF); - - // - // create an empty packet - // - $packet = new Net_DNS2_Packet_Request($rr->name, 'A', 'IN'); - - // - // unset the question - // - $packet->question = []; - $packet->header->qdcount = 0; - - // - // set the opcode to IQUERY - // - $packet->header->opcode = Net_DNS2_Lookups::OPCODE_IQUERY; - - // - // add the given RR as the answer - // - $packet->answer[] = $rr; - $packet->header->ancount = 1; - - // - // check for an authentication method; either TSIG or SIG - // - if ( ($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $packet->additional[] = $this->auth_signature; - $packet->header->arcount = cacti_sizeof($packet->additional); - } - - // - // send the packet and get back the response - // - return $this->sendPacket($packet, $this->use_tcp); - } + /** + * Constructor - creates a new Net_DNS2_Resolver object. + * + * @param mixed $options either an array with options or null + */ + public function __construct(?array $options = null) + { + parent::__construct($options); + } + + /** + * does a basic DNS lookup query. + * + * @param string $name the DNS name to loookup + * @param string $type the name of the RR type to lookup + * @param string $class the name of the RR class to lookup + * + * @return Net_DNS2_Packet_Response object + * + * @throws Net_DNS2_Exception + */ + public function query($name, $type = 'A', $class = 'IN') + { + // + // make sure we have some name servers set + // + $this->checkServers(Net_DNS2::RESOLV_CONF); + + // + // we don't support incremental zone transfers; so if it's requested, a full + // zone transfer can be returned + // + if ('IXFR' == $type) { + $type = 'AXFR'; + } + + // + // if the name *looks* too short, then append the domain from the config + // + if ((false === strpos($name, '.')) && ('PTR' != $type)) { + $name .= '.'.strtolower($this->domain); + } + + // + // create a new packet based on the input + // + $packet = new Net_DNS2_Packet_Request($name, $type, $class); + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $packet->additional[] = $this->auth_signature; + $packet->header->arcount = cacti_sizeof($packet->additional); + } + + // + // check for the DNSSEC flag, and if it's true, then add an OPT + // RR to the additional section, and set the DO flag to 1. + // + if (true == $this->dnssec) { + // + // create a new OPT RR + // + $opt = new Net_DNS2_RR_OPT(); + + // + // set the DO flag, and the other values + // + $opt->do = 1; + $opt->class = $this->dnssec_payload_size; + + // + // add the RR to the additional section. + // + $packet->additional[] = $opt; + $packet->header->arcount = cacti_sizeof($packet->additional); + } + + // + // set the DNSSEC AD or CD bits + // + if (true == $this->dnssec_ad_flag) { + $packet->header->ad = 1; + } + if (true == $this->dnssec_cd_flag) { + $packet->header->cd = 1; + } + + // + // if caching is turned on, then check then hash the question, and + // do a cache lookup. + // + // don't use the cache for zone transfers + // + $packet_hash = ''; + + if ((true == $this->use_cache) && (true == $this->cacheable($type))) { + // + // open the cache + // + $this->cache->open( + $this->cache_file, + $this->cache_size, + $this->cache_serializer + ); + + // + // build the key and check for it in the cache. + // + $packet_hash = md5( + $packet->question[0]->qname.'|'.$packet->question[0]->qtype + ); + + if ($this->cache->has($packet_hash)) { + return $this->cache->get($packet_hash); + } + } + + // + // set the RD (recursion desired) bit to 1 / 0 depending on the config + // setting. + // + if (false == $this->recurse) { + $packet->header->rd = 0; + } else { + $packet->header->rd = 1; + } + + // + // send the packet and get back the response + // + // *always* use TCP for zone transfers- does this cause any problems? + // + $response = $this->sendPacket( + $packet, + ('AXFR' == $type) ? true : $this->use_tcp + ); + + // + // if strict mode is enabled, then make sure that the name that was + // looked up is *actually* in the response object. + // + // only do this is strict_query_mode is turned on, AND we've received + // some answers; no point doing any else if there were no answers. + // + if ((true == $this->strict_query_mode) + && ($response->header->ancount > 0) + ) { + $found = false; + + // + // look for the requested name/type/class + // + foreach ($response->answer as $index => $object) { + if ((0 == strcasecmp(trim($object->name, '.'), trim($packet->question[0]->qname, '.'))) + && ($object->type == $packet->question[0]->qtype) + && ($object->class == $packet->question[0]->qclass) + ) { + $found = true; + + break; + } + } + + // + // if it's not found, then unset the answer section; it's not correct to + // throw an exception here; if the hostname didn't exist, then + // sendPacket() would have already thrown an NXDOMAIN error- so the host + // *exists*, but just not the request type/class. + // + // the correct response in this case, is an empty answer section; the + // authority section may still have usual information, like a SOA record. + // + if (false == $found) { + $response->answer = []; + $response->header->ancount = 0; + } + } + + // + // cache the response object + // + if ((true == $this->use_cache) && (true == $this->cacheable($type))) { + $this->cache->put($packet_hash, $response); + } + + return $response; + } + + /** + * does an inverse query for the given RR; most DNS servers do not implement + * inverse queries, but they should be able to return "not implemented". + * + * @param Net_DNS2_RR $rr the RR object to lookup + * + * @return Net_DNS2_RR object + * + * @throws Net_DNS2_Exception + */ + public function iquery(Net_DNS2_RR $rr) + { + // + // make sure we have some name servers set + // + $this->checkServers(Net_DNS2::RESOLV_CONF); + + // + // create an empty packet + // + $packet = new Net_DNS2_Packet_Request($rr->name, 'A', 'IN'); + + // + // unset the question + // + $packet->question = []; + $packet->header->qdcount = 0; + + // + // set the opcode to IQUERY + // + $packet->header->opcode = Net_DNS2_Lookups::OPCODE_IQUERY; + + // + // add the given RR as the answer + // + $packet->answer[] = $rr; + $packet->header->ancount = 1; + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $packet->additional[] = $this->auth_signature; + $packet->header->arcount = cacti_sizeof($packet->additional); + } + + // + // send the packet and get back the response + // + return $this->sendPacket($packet, $this->use_tcp); + } } diff --git a/Net/DNS2/Socket.php b/Net/DNS2/Socket.php index 953f9a82..fa8b4997 100644 --- a/Net/DNS2/Socket.php +++ b/Net/DNS2/Socket.php @@ -1,38 +1,45 @@ . All rights reserved. * * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ -/* - * check to see if the socket defines exist; if they don't, then define them - */ -if (defined('SOCK_STREAM') == false) { +// check to see if the socket defines exist; if they don't, then define them +if (false == defined('SOCK_STREAM')) { define('SOCK_STREAM', 1); } -if (defined('SOCK_DGRAM') == false) { +if (false == defined('SOCK_DGRAM')) { define('SOCK_DGRAM', 2); } /** - * Socket handling class using the PHP Streams - * + * Socket handling class using the PHP Streams. */ class Net_DNS2_Socket { + // type of sockets + public const SOCK_STREAM = SOCK_STREAM; + public const SOCK_DGRAM = SOCK_DGRAM; + + // the last error message on the object + public $last_error; + + // date the socket connection was created, and the date it was last used + public $date_created; + public $date_last_used; private $sock; private $type; private $host; @@ -40,69 +47,43 @@ class Net_DNS2_Socket private $timeout; private $context; - /* - * the local IP and port we'll send the request from - */ + // the local IP and port we'll send the request from private $local_host; private $local_port; - /* - * the last error message on the object - */ - public $last_error; - - /* - * date the socket connection was created, and the date it was last used - */ - public $date_created; - public $date_last_used; - - /* - * type of sockets - */ - const SOCK_STREAM = SOCK_STREAM; - const SOCK_DGRAM = SOCK_DGRAM; - - /** - * constructor - set the port details - * - * @param integer $type the socket type - * @param string $host the IP address of the DNS server to connect to - * @param integer $port the port of the DNS server to connect to - * @param integer $timeout the timeout value to use for socket functions + /** + * constructor - set the port details. * - * @access public - * + * @param int $type the socket type + * @param string $host the IP address of the DNS server to connect to + * @param int $port the port of the DNS server to connect to + * @param int $timeout the timeout value to use for socket functions */ public function __construct($type, $host, $port, $timeout) { - $this->type = $type; - $this->host = $host; - $this->port = $port; - $this->timeout = $timeout; + $this->type = $type; + $this->host = $host; + $this->port = $port; + $this->timeout = $timeout; $this->date_created = microtime(true); } /** - * destructor - * - * @access public + * destructor. */ public function __destruct() { $this->close(); } - /** - * sets the local address/port for the socket to bind to + /** + * sets the local address/port for the socket to bind to. * * @param string $address the local IP address to bind to * @param mixed $port the local port to bind to, or 0 to let the socket * function select a port * - * @return boolean - * @access public - * + * @return bool */ public function bindAddress($address, $port = 0) { @@ -113,28 +94,24 @@ public function bindAddress($address, $port = 0) } /** - * opens a socket connection to the DNS server - * - * @return boolean - * @access public + * opens a socket connection to the DNS server. * + * @return bool */ public function open() { // - // create a list of options for the context + // create a list of options for the context // - $opts = [ 'socket' => [] ]; - + $opts = ['socket' => []]; + // // bind to a local IP/port if it's set // if (strlen($this->local_host) > 0) { - $opts['socket']['bindto'] = $this->local_host; if ($this->local_port > 0) { - - $opts['socket']['bindto'] .= ':' . $this->local_port; + $opts['socket']['bindto'] .= ':'.$this->local_port; } } @@ -146,66 +123,71 @@ public function open() // // create socket // - $errno; - $errstr; - - switch($this->type) { - case Net_DNS2_Socket::SOCK_STREAM: - if (Net_DNS2::isIPv4($this->host) == true) { + switch ($this->type) { + case Net_DNS2_Socket::SOCK_STREAM: + if (true == Net_DNS2::isIPv4($this->host)) { + $this->sock = @stream_socket_client( + 'tcp://'.$this->host.':'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } elseif (true == Net_DNS2::isIPv6($this->host)) { + $this->sock = @stream_socket_client( + 'tcp://['.$this->host.']:'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } else { + $this->last_error = 'invalid address type: '.$this->host; - $this->sock = @stream_socket_client( - 'tcp://' . $this->host . ':' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->context - ); - } else if (Net_DNS2::isIPv6($this->host) == true) { - - $this->sock = @stream_socket_client( - 'tcp://[' . $this->host . ']:' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->context - ); - } else { - - $this->last_error = 'invalid address type: ' . $this->host; - return false; - } + return false; + } - break; - - case Net_DNS2_Socket::SOCK_DGRAM: + break; + + case Net_DNS2_Socket::SOCK_DGRAM: + if (true == Net_DNS2::isIPv4($this->host)) { + $this->sock = @stream_socket_client( + 'udp://'.$this->host.':'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } elseif (true == Net_DNS2::isIPv6($this->host)) { + $this->sock = @stream_socket_client( + 'udp://['.$this->host.']:'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } else { + $this->last_error = 'invalid address type: '.$this->host; - if (Net_DNS2::isIPv4($this->host) == true) { + return false; + } - $this->sock = @stream_socket_client( - 'udp://' . $this->host . ':' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->context - ); - } else if (Net_DNS2::isIPv6($this->host) == true) { + break; - $this->sock = @stream_socket_client( - 'udp://[' . $this->host . ']:' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->context - ); - } else { + default: + $this->last_error = 'Invalid socket type: '.$this->type; - $this->last_error = 'invalid address type: ' . $this->host; return false; - } - - break; - - default: - $this->last_error = 'Invalid socket type: ' . $this->type; - return false; } - if ($this->sock === false) { - + if (false === $this->sock) { $this->last_error = $errstr; + return false; } @@ -219,41 +201,37 @@ public function open() } /** - * closes a socket connection to the DNS server + * closes a socket connection to the DNS server. * - * @return boolean - * @access public - * + * @return bool */ public function close() { - if (is_resource($this->sock) === true) { - + if (true === is_resource($this->sock)) { @fclose($this->sock); } + return true; } /** - * writes the given string to the DNS server socket + * writes the given string to the DNS server socket. * * @param string $data a binary packed DNS packet - * - * @return boolean - * @access public * + * @return bool */ public function write($data) { $length = strlen($data); - if ($length == 0) { - + if (0 == $length) { $this->last_error = 'empty data on write()'; + return false; } - $read = null; - $write = [ $this->sock ]; + $read = null; + $write = [$this->sock]; $except = null; // @@ -265,28 +243,27 @@ public function write($data) // select on write // $result = stream_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = 'failed on write select()'; - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on write select()'; + return false; } // // if it's a TCP socket, then we need to packet and send the length of the // data as the first 16bit of data. - // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - - $s = chr($length >> 8) . chr($length); - - if (@fwrite($this->sock, $s) === false) { + // + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { + $s = chr($length >> 8).chr($length); + if (false === @fwrite($this->sock, $s)) { $this->last_error = 'failed to fwrite() 16bit length'; + return false; } } @@ -295,29 +272,27 @@ public function write($data) // write the data to the socket // $size = @fwrite($this->sock, $data); - if ( ($size === false) || ($size != $length) ) { - + if ((false === $size) || ($size != $length)) { $this->last_error = 'failed to fwrite() packet'; + return false; } return true; } - /** - * reads a response from a DNS server + /** + * reads a response from a DNS server. * - * @param integer &$size the size of the DNS packet read is passed back - * @param integer $max_size the max data size returned. + * @param int &$size the size of the DNS packet read is passed back + * @param int $max_size the max data size returned * - * @return mixed returns the data on success and false on error - * @access public - * + * @return mixed returns the data on success and false on error */ public function read(&$size, $max_size) { - $read = [ $this->sock ]; - $write = null; + $read = [$this->sock]; + $write = null; $except = null; // @@ -334,14 +309,14 @@ public function read(&$size, $max_size) // select on read // $result = stream_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = 'error on read select()'; - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on read select()'; + return false; } @@ -350,25 +325,23 @@ public function read(&$size, $max_size) // // if it's a TCP socket, then the first two bytes is the length of the DNS - // packet- we need to read that off first, then use that value for the + // packet- we need to read that off first, then use that value for the // packet read. // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { if (($data = fread($this->sock, 2)) === false) { - $this->last_error = 'failed on fread() for data length'; + return false; } - if (strlen($data) == 0) - { + if (0 == strlen($data)) { $this->last_error = 'failed on fread() for data length'; + return false; } $length = ord($data[0]) << 8 | ord($data[1]); if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - return false; } } @@ -390,12 +363,11 @@ public function read(&$size, $max_size) // // the streams socket is weird for TCP sockets; it doesn't seem to always // return all the data properly; but the looping code I added broke UDP - // packets- my fault- + // packets- my fault- // // the sockets library works much better. // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { $chunk = ''; $chunk_size = $length; @@ -403,11 +375,10 @@ public function read(&$size, $max_size) // loop so we make sure we read all the data // while (1) { - $chunk = fread($this->sock, $chunk_size); - if ($chunk === false) { - + if (false === $chunk) { $this->last_error = 'failed on fread() for data'; + return false; } @@ -418,21 +389,19 @@ public function read(&$size, $max_size) break; } } - } else { - // // if it's UDP, it's a single fixed-size frame, and the streams library // doesn't seem to have a problem reading it. // $data = fread($this->sock, $length); - if ($length === false) { - + if (false === $length) { $this->last_error = 'failed on fread() for data'; + return false; } } - + $size = strlen($data); return $data; diff --git a/Net/DNS2/Socket/Sockets.php b/Net/DNS2/Socket/Sockets.php index 707b6532..8977472e 100644 --- a/Net/DNS2/Socket/Sockets.php +++ b/Net/DNS2/Socket/Sockets.php @@ -1,8 +1,9 @@ * @copyright 2010 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * * @version SVN: $Id$ - * @link http://pear.php.net/package/Net_DNS2 - * @since File available since Release 0.6.0 * + * @see http://pear.php.net/package/Net_DNS2 + * @since File available since Release 0.6.0 */ /** - * Socket handling class using the PHP sockets extension + * Socket handling class using the PHP sockets extension. * * The sockets extension is faster than the stream functions in PHP, but it's * not standard. So if the extension is loaded, then this class is used, if * it's not, then the Net_DNS2_Socket_Streams class is used. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link http://pear.php.net/package/Net_DNS2 - * @see Net_DNS2_Socket * + * @see http://pear.php.net/package/Net_DNS2 + * @see Net_DNS2_Socket */ class Net_DNS2_Socket_Sockets extends Net_DNS2_Socket { /** - * opens a socket connection to the DNS server - * - * @return boolean - * @access public + * opens a socket connection to the DNS server. * + * @return bool */ public function open() { // // create the socket // - if (Net_DNS2::isIPv4($this->host) == true) { - + if (true == Net_DNS2::isIPv4($this->host)) { $this->sock = @socket_create( - AF_INET, $this->type, - ($this->type == Net_DNS2_Socket::SOCK_STREAM) ? SOL_TCP : SOL_UDP + AF_INET, + $this->type, + (Net_DNS2_Socket::SOCK_STREAM == $this->type) ? SOL_TCP : SOL_UDP ); - - } else if (Net_DNS2::isIPv6($this->host) == true) { - + } elseif (true == Net_DNS2::isIPv6($this->host)) { $this->sock = @socket_create( - AF_INET6, $this->type, - ($this->type == Net_DNS2_Socket::SOCK_STREAM) ? SOL_TCP : SOL_UDP + AF_INET6, + $this->type, + (Net_DNS2_Socket::SOCK_STREAM == $this->type) ? SOL_TCP : SOL_UDP ); - } else { + $this->last_error = 'invalid address type: '.$this->host; - $this->last_error = 'invalid address type: ' . $this->host; return false; } - if ($this->sock === false) { - + if (false === $this->sock) { $this->last_error = socket_strerror(socket_last_error()); + return false; } @@ -110,14 +108,14 @@ public function open() // bind to a local IP/port if it's set // if (strlen($this->local_host) > 0) { - $result = @socket_bind( - $this->sock, $this->local_host, + $this->sock, + $this->local_host, ($this->local_port > 0) ? $this->local_port : null ); - if ($result === false) { - + if (false === $result) { $this->last_error = socket_strerror(socket_last_error()); + return false; } } @@ -125,9 +123,9 @@ public function open() // // mark the socket as non-blocking // - if (@socket_set_nonblock($this->sock) === false) { - + if (false === @socket_set_nonblock($this->sock)) { $this->last_error = socket_strerror(socket_last_error()); + return false; } @@ -137,22 +135,22 @@ public function open() // @socket_connect($this->sock, $this->host, $this->port); - $read = null; - $write = array($this->sock); + $read = null; + $write = [$this->sock]; $except = null; // // select on write to check if the call to connect worked // $result = @socket_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = socket_strerror(socket_last_error()); - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on write select for connect()'; + return false; } @@ -160,55 +158,51 @@ public function open() } /** - * closes a socket connection to the DNS server - * - * @return boolean - * @access public + * closes a socket connection to the DNS server. * + * @return bool */ public function close() { - if (is_resource($this->sock) === true) { - + if (true === is_resource($this->sock)) { @socket_close($this->sock); } + return true; } /** - * writes the given string to the DNS server socket + * writes the given string to the DNS server socket. * * @param string $data a binary packed DNS packet * - * @return boolean - * @access public - * + * @return bool */ public function write($data) { $length = strlen($data); - if ($length == 0) { - + if (0 == $length) { $this->last_error = 'empty data on write()'; + return false; } - $read = null; - $write = array($this->sock); + $read = null; + $write = [$this->sock]; $except = null; // // select on write // $result = @socket_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = socket_strerror(socket_last_error()); - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on write select()'; + return false; } @@ -216,13 +210,12 @@ public function write($data) // if it's a TCP socket, then we need to packet and send the length of the // data as the first 16bit of data. // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - - $s = chr($length >> 8) . chr($length); - - if (@socket_write($this->sock, $s) === false) { + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { + $s = chr($length >> 8).chr($length); + if (false === @socket_write($this->sock, $s)) { $this->last_error = socket_strerror(socket_last_error()); + return false; } } @@ -231,9 +224,9 @@ public function write($data) // write the data to the socket // $size = @socket_write($this->sock, $data); - if ( ($size === false) || ($size != $length) ) { - + if ((false === $size) || ($size != $length)) { $this->last_error = socket_strerror(socket_last_error()); + return false; } @@ -241,26 +234,25 @@ public function write($data) } /** - * reads a response from a DNS server - * - * @param integer &$size the size of the DNS packet read is passed back + * reads a response from a DNS server. * - * @return mixed returns the data on success and false on error - * @access public + * @param int &$size the size of the DNS packet read is passed back + * @param mixed $max_size * + * @return mixed returns the data on success and false on error */ public function read(&$size, $max_size) { - $read = array($this->sock); - $write = null; + $read = [$this->sock]; + $write = null; $except = null; // // make sure our socket is non-blocking // - if (@socket_set_nonblock($this->sock) === false) { - + if (false === @socket_set_nonblock($this->sock)) { $this->last_error = socket_strerror(socket_last_error()); + return false; } @@ -268,14 +260,14 @@ public function read(&$size, $max_size) // select on read // $result = @socket_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = socket_strerror(socket_last_error()); - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on read select()'; + return false; } @@ -284,20 +276,18 @@ public function read(&$size, $max_size) // // if it's a TCP socket, then the first two bytes is the length of the DNS - // packet- we need to read that off first, then use that value for the + // packet- we need to read that off first, then use that value for the // packet read. // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { if (($size = @socket_recv($this->sock, $data, 2, 0)) === false) { - $this->last_error = socket_strerror(socket_last_error()); + return false; } $length = ord($data[0]) << 8 | ord($data[1]); if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - return false; } } @@ -309,9 +299,9 @@ public function read(&$size, $max_size) // so the easiest thing to do, is just turn off socket blocking, and // wait for the data. // - if (@socket_set_block($this->sock) === false) { - + if (false === @socket_set_block($this->sock)) { $this->last_error = socket_strerror(socket_last_error()); + return false; } @@ -322,19 +312,17 @@ public function read(&$size, $max_size) // MSG_WAITALL properly, so they may return with less data than is available. // // According to M$, XP and below don't support MSG_WAITALL at all; and there - // also seems to be some issue in 2003 and 2008 where the MSG_WAITALL is - // defined as 0, but if you actually pass 8 (which is the correct defined - // value), it works as it's supposed to- so in these cases, it's just the + // also seems to be some issue in 2003 and 2008 where the MSG_WAITALL is + // defined as 0, but if you actually pass 8 (which is the correct defined + // value), it works as it's supposed to- so in these cases, it's just the // define that's incorrect- this is likely a PHP issue. // $data = ''; $size = 0; while (1) { - $chunk_size = @socket_recv($this->sock, $chunk, $length, MSG_WAITALL); - if ($chunk_size === false) { - + if (false === $chunk_size) { $size = $chunk_size; $this->last_error = socket_strerror(socket_last_error()); @@ -345,7 +333,7 @@ public function read(&$size, $max_size) $size += $chunk_size; $length -= $chunk_size; - if ( ($length <= 0) || ($this->type == Net_DNS2_Socket::SOCK_DGRAM) ) { + if (($length <= 0) || (Net_DNS2_Socket::SOCK_DGRAM == $this->type)) { break; } } @@ -361,4 +349,3 @@ public function read(&$size, $max_size) * c-hanging-comment-ender-p: nil * End: */ -?> diff --git a/Net/DNS2/Socket/Streams.php b/Net/DNS2/Socket/Streams.php index 4cd11fd5..a43850fe 100644 --- a/Net/DNS2/Socket/Streams.php +++ b/Net/DNS2/Socket/Streams.php @@ -1,8 +1,9 @@ * @copyright 2010 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * * @version SVN: $Id$ - * @link http://pear.php.net/package/Net_DNS2 - * @since File available since Release 0.6.0 * + * @see http://pear.php.net/package/Net_DNS2 + * @since File available since Release 0.6.0 */ /** - * Socket handling class using the PHP Streams + * Socket handling class using the PHP Streams. * * The sockets extension is faster than the stream functions in PHP, but it's * not standard. So if the extension is loaded, then the Net_DNS2_Socket_Sockets * class it used, otherwise, this class it used. - * + * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link http://pear.php.net/package/Net_DNS2 - * @see Net_DNS2_Socket * + * @see http://pear.php.net/package/Net_DNS2 + * @see Net_DNS2_Socket */ class Net_DNS2_Socket_Streams extends Net_DNS2_Socket { private $_context; /** - * opens a socket connection to the DNS server - * - * @return boolean - * @access public + * opens a socket connection to the DNS server. * + * @return bool */ public function open() { // - // create a list of options for the context + // create a list of options for the context // - $opts = array('socket' => array()); - + $opts = ['socket' => []]; + // // bind to a local IP/port if it's set // if (strlen($this->local_host) > 0) { - $opts['socket']['bindto'] = $this->local_host; if ($this->local_port > 0) { - - $opts['socket']['bindto'] .= ':' . $this->local_port; + $opts['socket']['bindto'] .= ':'.$this->local_port; } } @@ -102,66 +100,71 @@ public function open() // // create socket // - $errno; - $errstr; - - switch($this->type) { - case Net_DNS2_Socket::SOCK_STREAM: - - if (Net_DNS2::isIPv4($this->host) == true) { - - $this->sock = @stream_socket_client( - 'tcp://' . $this->host . ':' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->_context - ); - } else if (Net_DNS2::isIPv6($this->host) == true) { - $this->sock = @stream_socket_client( - 'tcp://[' . $this->host . ']:' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->_context - ); - } else { + switch ($this->type) { + case Net_DNS2_Socket::SOCK_STREAM: + if (true == Net_DNS2::isIPv4($this->host)) { + $this->sock = @stream_socket_client( + 'tcp://'.$this->host.':'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } elseif (true == Net_DNS2::isIPv6($this->host)) { + $this->sock = @stream_socket_client( + 'tcp://['.$this->host.']:'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } else { + $this->last_error = 'invalid address type: '.$this->host; - $this->last_error = 'invalid address type: ' . $this->host; - return false; - } + return false; + } - break; - - case Net_DNS2_Socket::SOCK_DGRAM: + break; + + case Net_DNS2_Socket::SOCK_DGRAM: + if (true == Net_DNS2::isIPv4($this->host)) { + $this->sock = @stream_socket_client( + 'udp://'.$this->host.':'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } elseif (true == Net_DNS2::isIPv6($this->host)) { + $this->sock = @stream_socket_client( + 'udp://['.$this->host.']:'.$this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } else { + $this->last_error = 'invalid address type: '.$this->host; - if (Net_DNS2::isIPv4($this->host) == true) { + return false; + } - $this->sock = @stream_socket_client( - 'udp://' . $this->host . ':' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->_context - ); - } else if (Net_DNS2::isIPv6($this->host) == true) { + break; - $this->sock = @stream_socket_client( - 'udp://[' . $this->host . ']:' . $this->port, - $errno, $errstr, $this->timeout, - STREAM_CLIENT_CONNECT, $this->_context - ); - } else { + default: + $this->last_error = 'Invalid socket type: '.$this->type; - $this->last_error = 'invalid address type: ' . $this->host; return false; - } - - break; - - default: - $this->last_error = 'Invalid socket type: ' . $this->type; - return false; } - if ($this->sock === false) { - + if (false === $this->sock) { $this->last_error = $errstr; + return false; } @@ -175,69 +178,64 @@ public function open() } /** - * closes a socket connection to the DNS server - * - * @return boolean - * @access public + * closes a socket connection to the DNS server. * + * @return bool */ public function close() { - if (is_resource($this->sock) === true) { - + if (true === is_resource($this->sock)) { @fclose($this->sock); } + return true; } /** - * writes the given string to the DNS server socket + * writes the given string to the DNS server socket. * * @param string $data a binary packed DNS packet * - * @return boolean - * @access public - * + * @return bool */ public function write($data) { $length = strlen($data); - if ($length == 0) { - + if (0 == $length) { $this->last_error = 'empty data on write()'; + return false; } - $read = null; - $write = array($this->sock); + $read = null; + $write = [$this->sock]; $except = null; // // select on write // $result = stream_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = 'failed on write select()'; - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on write select()'; + return false; } // // if it's a TCP socket, then we need to packet and send the length of the // data as the first 16bit of data. - // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - - $s = chr($length >> 8) . chr($length); - - if (@fwrite($this->sock, $s) === false) { + // + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { + $s = chr($length >> 8).chr($length); + if (false === @fwrite($this->sock, $s)) { $this->last_error = 'failed to fwrite() 16bit length'; + return false; } } @@ -246,9 +244,9 @@ public function write($data) // write the data to the socket // $size = @fwrite($this->sock, $data); - if ( ($size === false) || ($size != $length) ) { - + if ((false === $size) || ($size != $length)) { $this->last_error = 'failed to fwrite() packet'; + return false; } @@ -256,18 +254,17 @@ public function write($data) } /** - * reads a response from a DNS server - * - * @param integer &$size the size of the DNS packet read is passed back + * reads a response from a DNS server. * - * @return mixed returns the data on success and false on error - * @access public + * @param int &$size the size of the DNS packet read is passed back + * @param mixed $max_size * + * @return mixed returns the data on success and false on error */ public function read(&$size, $max_size) { - $read = array($this->sock); - $write = null; + $read = [$this->sock]; + $write = null; $except = null; // @@ -279,14 +276,14 @@ public function read(&$size, $max_size) // select on read // $result = stream_select($read, $write, $except, $this->timeout); - if ($result === false) { - + if (false === $result) { $this->last_error = 'error on read select()'; - return false; - - } else if ($result == 0) { + return false; + } + if (0 == $result) { $this->last_error = 'timeout on read select()'; + return false; } @@ -295,20 +292,18 @@ public function read(&$size, $max_size) // // if it's a TCP socket, then the first two bytes is the length of the DNS - // packet- we need to read that off first, then use that value for the + // packet- we need to read that off first, then use that value for the // packet read. // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { if (($data = fread($this->sock, 2)) === false) { - $this->last_error = 'failed on fread() for data length'; + return false; } - + $length = ord($data[0]) << 8 | ord($data[1]); if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - return false; } } @@ -330,12 +325,11 @@ public function read(&$size, $max_size) // // the streams socket is weird for TCP sockets; it doesn't seem to always // return all the data properly; but the looping code I added broke UDP - // packets- my fault- + // packets- my fault- // // the sockets library works much better. // - if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { - + if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { $chunk = ''; $chunk_size = $length; @@ -343,11 +337,10 @@ public function read(&$size, $max_size) // loop so we make sure we read all the data // while (1) { - $chunk = fread($this->sock, $chunk_size); - if ($chunk === false) { - + if (false === $chunk) { $this->last_error = 'failed on fread() for data'; + return false; } @@ -358,21 +351,19 @@ public function read(&$size, $max_size) break; } } - } else { - // // if it's UDP, it's a single fixed-size frame, and the streams library // doesn't seem to have a problem reading it. // $data = fread($this->sock, $length); - if ($length === false) { - + if (false === $length) { $this->last_error = 'failed on fread() for data'; + return false; } } - + $size = strlen($data); return $data; @@ -386,4 +377,3 @@ public function read(&$size, $max_size) * c-hanging-comment-ender-p: nil * End: */ -?> diff --git a/Net/DNS2/Updater.php b/Net/DNS2/Updater.php index cecc1d82..0e9eba55 100644 --- a/Net/DNS2/Updater.php +++ b/Net/DNS2/Updater.php @@ -8,13 +8,13 @@ * See LICENSE for more details. * * @category Networking - * @package Net_DNS2 + * * @author Mike Pultz * @copyright 2020 Mike Pultz * @license http://www.opensource.org/licenses/bsd-license.php BSD License - * @link https://netdns2.com/ - * @since File available since Release 0.6.0 * + * @see https://netdns2.com/ + * @since File available since Release 0.6.0 */ /** @@ -28,579 +28,558 @@ * * Generally, query (recursive) lookups are done against caching server, while * update requests are done against authoritative servers. - * */ class Net_DNS2_Updater extends Net_DNS2 { - /* - * a Net_DNS2_Packet_Request object used for the update request - */ - private $_packet; - - /** - * Constructor - builds a new Net_DNS2_Updater objected used for doing - * dynamic DNS updates - * - * @param string $zone the domain name to use for DNS updates - * @param mixed $options an array of config options or null - * - * @throws Net_DNS2_Exception - * @access public - * - */ - public function __construct($zone, array $options = null) - { - parent::__construct($options); - - // - // create the packet - // - $this->_packet = new Net_DNS2_Packet_Request( - strtolower(trim($zone, " \n\r\t.")), 'SOA', 'IN' - ); - - // - // make sure the opcode on the packet is set to UPDATE - // - $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_UPDATE; - } - - /** - * checks that the given name matches the name for the zone we're updating - * - * @param string $name The name to be checked. - * - * @return boolean - * @throws Net_DNS2_Exception - * @access private - * - */ - private function _checkName($name) - { - if (!preg_match('/' . $this->_packet->question[0]->qname . '$/', $name)) { - - throw new Net_DNS2_Exception( - 'name provided (' . $name . ') does not match zone name (' . - $this->_packet->question[0]->qname . ')', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - return true; - } - - /** - * add a signature to the request for authentication - * - * @param string $keyname the key name to use for the TSIG RR - * @param string $signature the key to sign the request. - * - * @return boolean - * @access public - * @see Net_DNS2::signTSIG() - * @deprecated function deprecated in 1.1.0 - * - */ - public function signature($keyname, $signature) - { - return $this->signTSIG($keyname, $signature); - } - - /** - * 2.5.1 - Add To An RRset - * - * RRs are added to the Update Section whose NAME, TYPE, TTL, RDLENGTH - * and RDATA are those being added, and CLASS is the same as the zone - * class. Any duplicate RRs will be silently ignored by the primary - * master. - * - * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be added to the zone - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function add(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.5.4 - Delete An RR From An RRset - * - * RRs to be deleted are added to the Update Section. The NAME, TYPE, - * RDLENGTH and RDATA must match the RR being deleted. TTL must be - * specified as zero (0) and will otherwise be ignored by the primary - * master. CLASS must be specified as NONE to distinguish this from an - * RR addition. If no such RRs exist, then this Update RR will be - * silently ignored by the primary master. - * - * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be deleted from the zone - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function delete(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - - $rr->ttl = 0; - $rr->class = 'NONE'; - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.5.2 - Delete An RRset - * - * One RR is added to the Update Section whose NAME and TYPE are those - * of the RRset to be deleted. TTL must be specified as zero (0) and is - * otherwise not used by the primary master. CLASS must be specified as - * ANY. RDLENGTH must be zero (0) and RDATA must therefore be empty. - * If no such RRset exists, then this Update RR will be silently ignored - * by the primary master - * - * @param string $name the RR name to be removed from the zone - * @param string $type the RR type to be removed from the zone - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function deleteAny($name, $type) - { - $this->_checkName($name); - - $class = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - if (!isset($class)) { - - throw new Net_DNS2_Exception( - 'unknown or un-supported resource record type: ' . $type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - $rr = new $class; - - $rr->name = $name; - $rr->ttl = 0; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.5.3 - Delete All RRsets From A Name - * - * One RR is added to the Update Section whose NAME is that of the name - * to be cleansed of RRsets. TYPE must be specified as ANY. TTL must - * be specified as zero (0) and is otherwise not used by the primary - * master. CLASS must be specified as ANY. RDLENGTH must be zero (0) - * and RDATA must therefore be empty. If no such RRsets exist, then - * this Update RR will be silently ignored by the primary master. - * - * @param string $name the RR name to be removed from the zone - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function deleteAll($name) - { - $this->_checkName($name); - - // - // the Net_DNS2_RR_ANY class is just an empty stub class used for these - // cases only - // - $rr = new Net_DNS2_RR_ANY; - - $rr->name = $name; - $rr->ttl = 0; - $rr->type = 'ANY'; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.4.1 - RRset Exists (Value Independent) - * - * At least one RR with a specified NAME and TYPE (in the zone and class - * specified in the Zone Section) must exist. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME and TYPE are equal to that of the zone RRset whose - * existence is required. RDLENGTH is zero and RDATA is therefore - * empty. CLASS must be specified as ANY to differentiate this - * condition from that of an actual RR whose RDLENGTH is naturally zero - * (0) (e.g., NULL). TTL is specified as zero (0). - * - * @param string $name the RR name for the prerequisite - * @param string $type the RR type for the prerequisite - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function checkExists($name, $type) - { - $this->_checkName($name); - - $class = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - if (!isset($class)) { - - throw new Net_DNS2_Exception( - 'unknown or un-supported resource record type: ' . $type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - $rr = new $class; - - $rr->name = $name; - $rr->ttl = 0; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.2 - RRset Exists (Value Dependent) - * - * A set of RRs with a specified NAME and TYPE exists and has the same - * members with the same RDATAs as the RRset specified here in this - * section. While RRset ordering is undefined and therefore not - * significant to this comparison, the sets be identical in their - * extent. - * - * For this prerequisite, a requester adds to the section an entire - * RRset whose preexistence is required. NAME and TYPE are that of the - * RRset being denoted. CLASS is that of the zone. TTL must be - * specified as zero (0) and is ignored when comparing RRsets for - * identity. - * - * @param Net_DNS2_RR $rr the RR object to be used as a prerequisite - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function checkValueExists(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - - $rr->ttl = 0; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.3 - RRset Does Not Exist - * - * No RRs with a specified NAME and TYPE (in the zone and class denoted - * by the Zone Section) can exist. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME and TYPE are equal to that of the RRset whose nonexistence - * is required. The RDLENGTH of this record is zero (0), and RDATA - * field is therefore empty. CLASS must be specified as NONE in order - * to distinguish this condition from a valid RR whose RDLENGTH is - * naturally zero (0) (for example, the NULL RR). TTL must be specified - * as zero (0). - * - * @param string $name the RR name for the prerequisite - * @param string $type the RR type for the prerequisite - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function checkNotExists($name, $type) - { - $this->_checkName($name); - - $class = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - if (!isset($class)) { - - throw new Net_DNS2_Exception( - 'unknown or un-supported resource record type: ' . $type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - $rr = new $class; - - $rr->name = $name; - $rr->ttl = 0; - $rr->class = 'NONE'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.4 - Name Is In Use - * - * Name is in use. At least one RR with a specified NAME (in the zone - * and class specified by the Zone Section) must exist. Note that this - * prerequisite is NOT satisfied by empty nonterminals. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME is equal to that of the name whose ownership of an RR is - * required. RDLENGTH is zero and RDATA is therefore empty. CLASS must - * be specified as ANY to differentiate this condition from that of an - * actual RR whose RDLENGTH is naturally zero (0) (e.g., NULL). TYPE - * must be specified as ANY to differentiate this case from that of an - * RRset existence test. TTL is specified as zero (0). - * - * @param string $name the RR name for the prerequisite - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function checkNameInUse($name) - { - $this->_checkName($name); - - // - // the Net_DNS2_RR_ANY class is just an empty stub class used for these - // cases only - // - $rr = new Net_DNS2_RR_ANY; - - $rr->name = $name; - $rr->ttl = 0; - $rr->type = 'ANY'; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.5 - Name Is Not In Use - * - * Name is not in use. No RR of any type is owned by a specified NAME. - * Note that this prerequisite IS satisfied by empty nonterminals. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME is equal to that of the name whose nonownership of any RRs - * is required. RDLENGTH is zero and RDATA is therefore empty. CLASS - * must be specified as NONE. TYPE must be specified as ANY. TTL must - * be specified as zero (0). - * - * @param string $name the RR name for the prerequisite - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function checkNameNotInUse($name) - { - $this->_checkName($name); - - // - // the Net_DNS2_RR_ANY class is just an empty stub class used for these - // cases only - // - $rr = new Net_DNS2_RR_ANY; - - $rr->name = $name; - $rr->ttl = 0; - $rr->type = 'ANY'; - $rr->class = 'NONE'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * returns the current internal packet object. - * - * @return Net_DNS2_Packet_Request - * @access public - # - */ - public function packet() - { - // - // take a copy - // - $p = $this->_packet; - - // - // check for an authentication method; either TSIG or SIG - // - if ( ($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $p->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $p->header->qdcount = cacti_sizeof($p->question); - $p->header->ancount = cacti_sizeof($p->answer); - $p->header->nscount = cacti_sizeof($p->authority); - $p->header->arcount = cacti_sizeof($p->additional); - - return $p; - } - - /** - * executes the update request with the object information - * - * @param Net_DNS2_Packet_Response &$response ref to the response object - * - * @return boolean - * @throws Net_DNS2_Exception - * @access public - * - */ - public function update(&$response = null) - { - // - // make sure we have some name servers set - // - $this->checkServers(Net_DNS2::RESOLV_CONF); - - // - // check for an authentication method; either TSIG or SIG - // - if ( ($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $this->_packet->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); - $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); - $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); - $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); - - // - // make sure we have some data to send - // - if ( ($this->_packet->header->qdcount == 0) - || ($this->_packet->header->nscount == 0) - ) { - throw new Net_DNS2_Exception( - 'empty headers- nothing to send!', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - // - // send the packet and get back the response - // - $response = $this->sendPacket($this->_packet, $this->use_tcp); - - // - // clear the internal packet so if we make another request, we don't have - // old data being sent. - // - $this->_packet->reset(); - - // - // for updates, we just need to know it worked- we don't actually need to - // return the response object - // - return true; - } + // a Net_DNS2_Packet_Request object used for the update request + private $_packet; + + /** + * Constructor - builds a new Net_DNS2_Updater objected used for doing + * dynamic DNS updates. + * + * @param string $zone the domain name to use for DNS updates + * @param mixed $options an array of config options or null + * + * @throws Net_DNS2_Exception + */ + public function __construct($zone, ?array $options = null) + { + parent::__construct($options); + + // + // create the packet + // + $this->_packet = new Net_DNS2_Packet_Request( + strtolower(trim($zone, " \n\r\t.")), + 'SOA', + 'IN' + ); + + // + // make sure the opcode on the packet is set to UPDATE + // + $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_UPDATE; + } + + /** + * add a signature to the request for authentication. + * + * @param string $keyname the key name to use for the TSIG RR + * @param string $signature the key to sign the request + * + * @return bool + * + * @see Net_DNS2::signTSIG() + * @deprecated function deprecated in 1.1.0 + */ + public function signature($keyname, $signature) + { + return $this->signTSIG($keyname, $signature); + } + + /** + * 2.5.1 - Add To An RRset. + * + * RRs are added to the Update Section whose NAME, TYPE, TTL, RDLENGTH + * and RDATA are those being added, and CLASS is the same as the zone + * class. Any duplicate RRs will be silently ignored by the primary + * master. + * + * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be added to the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function add(Net_DNS2_RR $rr) + { + $this->_checkName($rr->name); + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.5.4 - Delete An RR From An RRset. + * + * RRs to be deleted are added to the Update Section. The NAME, TYPE, + * RDLENGTH and RDATA must match the RR being deleted. TTL must be + * specified as zero (0) and will otherwise be ignored by the primary + * master. CLASS must be specified as NONE to distinguish this from an + * RR addition. If no such RRs exist, then this Update RR will be + * silently ignored by the primary master. + * + * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be deleted from the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function delete(Net_DNS2_RR $rr) + { + $this->_checkName($rr->name); + + $rr->ttl = 0; + $rr->class = 'NONE'; + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.5.2 - Delete An RRset. + * + * One RR is added to the Update Section whose NAME and TYPE are those + * of the RRset to be deleted. TTL must be specified as zero (0) and is + * otherwise not used by the primary master. CLASS must be specified as + * ANY. RDLENGTH must be zero (0) and RDATA must therefore be empty. + * If no such RRset exists, then this Update RR will be silently ignored + * by the primary master + * + * @param string $name the RR name to be removed from the zone + * @param string $type the RR type to be removed from the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function deleteAny($name, $type) + { + $this->_checkName($name); + + $class = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + if (!isset($class)) { + throw new Net_DNS2_Exception( + 'unknown or un-supported resource record type: '.$type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + $rr = new $class(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.5.3 - Delete All RRsets From A Name. + * + * One RR is added to the Update Section whose NAME is that of the name + * to be cleansed of RRsets. TYPE must be specified as ANY. TTL must + * be specified as zero (0) and is otherwise not used by the primary + * master. CLASS must be specified as ANY. RDLENGTH must be zero (0) + * and RDATA must therefore be empty. If no such RRsets exist, then + * this Update RR will be silently ignored by the primary master. + * + * @param string $name the RR name to be removed from the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function deleteAll($name) + { + $this->_checkName($name); + + // + // the Net_DNS2_RR_ANY class is just an empty stub class used for these + // cases only + // + $rr = new Net_DNS2_RR_ANY(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->type = 'ANY'; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.4.1 - RRset Exists (Value Independent). + * + * At least one RR with a specified NAME and TYPE (in the zone and class + * specified in the Zone Section) must exist. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME and TYPE are equal to that of the zone RRset whose + * existence is required. RDLENGTH is zero and RDATA is therefore + * empty. CLASS must be specified as ANY to differentiate this + * condition from that of an actual RR whose RDLENGTH is naturally zero + * (0) (e.g., NULL). TTL is specified as zero (0). + * + * @param string $name the RR name for the prerequisite + * @param string $type the RR type for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkExists($name, $type) + { + $this->_checkName($name); + + $class = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + if (!isset($class)) { + throw new Net_DNS2_Exception( + 'unknown or un-supported resource record type: '.$type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + $rr = new $class(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.2 - RRset Exists (Value Dependent). + * + * A set of RRs with a specified NAME and TYPE exists and has the same + * members with the same RDATAs as the RRset specified here in this + * section. While RRset ordering is undefined and therefore not + * significant to this comparison, the sets be identical in their + * extent. + * + * For this prerequisite, a requester adds to the section an entire + * RRset whose preexistence is required. NAME and TYPE are that of the + * RRset being denoted. CLASS is that of the zone. TTL must be + * specified as zero (0) and is ignored when comparing RRsets for + * identity. + * + * @param Net_DNS2_RR $rr the RR object to be used as a prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkValueExists(Net_DNS2_RR $rr) + { + $this->_checkName($rr->name); + + $rr->ttl = 0; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.3 - RRset Does Not Exist. + * + * No RRs with a specified NAME and TYPE (in the zone and class denoted + * by the Zone Section) can exist. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME and TYPE are equal to that of the RRset whose nonexistence + * is required. The RDLENGTH of this record is zero (0), and RDATA + * field is therefore empty. CLASS must be specified as NONE in order + * to distinguish this condition from a valid RR whose RDLENGTH is + * naturally zero (0) (for example, the NULL RR). TTL must be specified + * as zero (0). + * + * @param string $name the RR name for the prerequisite + * @param string $type the RR type for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkNotExists($name, $type) + { + $this->_checkName($name); + + $class = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + if (!isset($class)) { + throw new Net_DNS2_Exception( + 'unknown or un-supported resource record type: '.$type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + $rr = new $class(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->class = 'NONE'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.4 - Name Is In Use. + * + * Name is in use. At least one RR with a specified NAME (in the zone + * and class specified by the Zone Section) must exist. Note that this + * prerequisite is NOT satisfied by empty nonterminals. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME is equal to that of the name whose ownership of an RR is + * required. RDLENGTH is zero and RDATA is therefore empty. CLASS must + * be specified as ANY to differentiate this condition from that of an + * actual RR whose RDLENGTH is naturally zero (0) (e.g., NULL). TYPE + * must be specified as ANY to differentiate this case from that of an + * RRset existence test. TTL is specified as zero (0). + * + * @param string $name the RR name for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkNameInUse($name) + { + $this->_checkName($name); + + // + // the Net_DNS2_RR_ANY class is just an empty stub class used for these + // cases only + // + $rr = new Net_DNS2_RR_ANY(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->type = 'ANY'; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.5 - Name Is Not In Use. + * + * Name is not in use. No RR of any type is owned by a specified NAME. + * Note that this prerequisite IS satisfied by empty nonterminals. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME is equal to that of the name whose nonownership of any RRs + * is required. RDLENGTH is zero and RDATA is therefore empty. CLASS + * must be specified as NONE. TYPE must be specified as ANY. TTL must + * be specified as zero (0). + * + * @param string $name the RR name for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkNameNotInUse($name) + { + $this->_checkName($name); + + // + // the Net_DNS2_RR_ANY class is just an empty stub class used for these + // cases only + // + $rr = new Net_DNS2_RR_ANY(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->type = 'ANY'; + $rr->class = 'NONE'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * returns the current internal packet object. + * + * @return Net_DNS2_Packet_Request + */ + public function packet() + { + // + // take a copy + // + $p = $this->_packet; + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $p->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $p->header->qdcount = cacti_sizeof($p->question); + $p->header->ancount = cacti_sizeof($p->answer); + $p->header->nscount = cacti_sizeof($p->authority); + $p->header->arcount = cacti_sizeof($p->additional); + + return $p; + } + + /** + * executes the update request with the object information. + * + * @param Net_DNS2_Packet_Response &$response ref to the response object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function update(&$response = null) + { + // + // make sure we have some name servers set + // + $this->checkServers(Net_DNS2::RESOLV_CONF); + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $this->_packet->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); + $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); + $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); + $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); + + // + // make sure we have some data to send + // + if ((0 == $this->_packet->header->qdcount) + || (0 == $this->_packet->header->nscount) + ) { + throw new Net_DNS2_Exception( + 'empty headers- nothing to send!', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + // + // send the packet and get back the response + // + $response = $this->sendPacket($this->_packet, $this->use_tcp); + + // + // clear the internal packet so if we make another request, we don't have + // old data being sent. + // + $this->_packet->reset(); + + // + // for updates, we just need to know it worked- we don't actually need to + // return the response object + // + return true; + } + + /** + * checks that the given name matches the name for the zone we're updating. + * + * @param string $name the name to be checked + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + private function _checkName($name) + { + if (!preg_match('/'.$this->_packet->question[0]->qname.'$/', $name)) { + throw new Net_DNS2_Exception( + 'name provided ('.$name.') does not match zone name (' + .$this->_packet->question[0]->qname.')', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + return true; + } } diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..5b559865 --- /dev/null +++ b/composer.json @@ -0,0 +1,14 @@ +{ + "name": "cacti/plugin-mactrack", + "description": "MacTrack plugin for Cacti - helper composer file for tooling", + "type": "library", + "require": {}, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0" + }, + "scripts": { + "phpcsfixer": "vendor/bin/php-cs-fixer fix" + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/images/index.php b/images/index.php index 82dac3bb..bc881c79 100644 --- a/images/index.php +++ b/images/index.php @@ -1,4 +1,5 @@ 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(100)', 'NULL' => false]; + $data['primary'] = 'id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Group of SNMP Option Sets'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); + } + + if (!db_table_exists('mac_track_snmp_items')) { + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; + $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; + $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; + $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; + $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; + $data['primary'] = 'id`,`snmp_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Set of SNMP Options'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); + } + + mactrack_add_column( + 'mac_track_snmp_items', + 'snmp_engine_id', + "ALTER TABLE `mac_track_snmp_items` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`" + ); + + if (!db_table_exists('mac_track_interface_graphs')) { + $data = []; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1']; + $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; + $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); + } + + mactrack_add_column( + 'mac_track_interfaces', + 'ifMauAutoNegAdminStatus', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegAdminStatus` integer UNSIGNED NOT NULL default '0' AFTER `ifDuplex`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifMauAutoNegRemoteSignaling', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegRemoteSignaling` integer UNSIGNED NOT NULL default '0' AFTER `ifMauAutoNegAdminStatus`" + ); + + mactrack_add_column( + 'mac_track_device_types', + 'dot1x_scanning_function', + "ALTER TABLE `mac_track_device_types` ADD COLUMN `dot1x_scanning_function` varchar(100) default '' AFTER `ip_scanning_function`" + ); + + mactrack_add_column( + 'mac_track_device_types', + 'serial_number_oid', + "ALTER TABLE `mac_track_device_types` ADD COLUMN `serial_number_oid` varchar(100) default '' AFTER `dot1x_scanning_function`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'customer_contact', + "ALTER TABLE `mac_track_sites` ADD COLUMN `customer_contact` varchar(150) default '' AFTER `site_name`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'netops_contact', + "ALTER TABLE `mac_track_sites` ADD COLUMN `netops_contact` varchar(150) default '' AFTER `customer_contact`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'facilities_contact', + "ALTER TABLE `mac_track_sites` ADD COLUMN `facilities_contact` varchar(150) default '' AFTER `netops_contact`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'site_info', + 'ALTER TABLE `mac_track_sites` ADD COLUMN `site_info` text AFTER `facilities_contact`' + ); + + mactrack_add_column( + 'mac_track_sites', + 'skip_vlans', + "ALTER TABLE `mac_track_sites` ADD COLUMN `skip_vlans` text DEFAULT ''" + ); + + mactrack_add_column( + 'mac_track_sites', + 'scan_vlans', + "ALTER TABLE `mac_track_sites` ADD COLUMN `scan_vlans` text DEFAULT ''" + ); + + mactrack_add_column( + 'mac_track_devices', + 'device_name', + "ALTER TABLE `mac_track_devices` ADD COLUMN `device_name` varchar(100) default '' AFTER `host_id`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'notes', + 'ALTER TABLE `mac_track_devices` ADD COLUMN `notes` text AFTER `hostname`' + ); + + mactrack_add_column( + 'mac_track_devices', + 'scan_trunk_port', + "ALTER TABLE `mac_track_devices` ADD COLUMN `scan_trunk_port` text DEFAULT ''" + ); + + mactrack_add_column( + 'mac_track_scanning_functions', + 'type', + "ALTER TABLE `mac_track_scanning_functions` ADD COLUMN `type` int(10) unsigned NOT NULL default '0' AFTER `scanning_function`" + ); + + mactrack_add_column( + 'mac_track_temp_ports', + 'device_name', + "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" + ); + + mactrack_add_column( + 'mac_track_temp_ports', + 'vendor_mac', + 'ALTER TABLE `mac_track_temp_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`' + ); + + mactrack_add_column( + 'mac_track_temp_ports', + 'authorized', + "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `updated`" + ); + + mactrack_add_column( + 'mac_track_ports', + 'device_name', + "ALTER TABLE `mac_track_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" + ); + + mactrack_add_column( + 'mac_track_ports', + 'vendor_mac', + 'ALTER TABLE `mac_track_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`' + ); + + mactrack_add_column( + 'mac_track_ports', + 'authorized', + "ALTER TABLE `mac_track_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `scan_date`" + ); + + mactrack_add_column( + 'mac_track_ips', + 'device_name', + "ALTER TABLE `mac_track_ips` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" + ); + + $columns = array_rekey( + db_fetch_assoc('SHOW COLUMNS FROM mac_track_ips'), + 'Field', + 'Type' + ); + + if (false !== strpos($columns['port_number'], 'int(10)')) { + db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + } elseif (false !== strpos($columns['port_number'], 'varchar(20)')) { + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + } else { + db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN first_scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN last_rundate TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_max_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_current_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_processes MODIFY COLUMN start_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_scan_dates MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + } + + if (!db_table_exists('mac_track_arp')) { + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'mac_address`, `ip_address'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Table for VRF ARP translation'; + api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); + } - mactrack_add_column('mac_track_interfaces', - 'inBound', - "ALTER TABLE mac_track_interfaces ADD COLUMN `inBound` double NOT NULL default '0' AFTER `ifOutErrors`"); - - mactrack_add_column('mac_track_interfaces', - 'outBound', - "ALTER TABLE mac_track_interfaces ADD COLUMN `outBound` double NOT NULL default '0' AFTER `inBound`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifInOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInOctets` int(10) unsigned NOT NULL default '0' AFTER `outBound`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifOutOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutOctets` int(10) unsigned NOT NULL default '0' AFTER `int_ifInOctets`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifHCInOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifHCInOctets` bigint(20) unsigned NOT NULL default '0' AFTER `int_ifOutOctets`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifHCOutOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifHCOutOctets` bigint(20) unsigned NOT NULL default '0' AFTER `int_ifHCInOctets`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifInUcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifHCOutOctets`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifOutUcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInUcastPkts`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifInMulticastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutUcastPkts`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifOutMulticastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInMulticastPkts`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifInBroadcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutMulticastPkts`"); - - mactrack_add_column('mac_track_interfaces', - 'int_ifOutBroadcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInBroadcastPkts`"); - - if (!mactrack_db_key_exists('mac_track_ports', 'site_id_device_id')) { - db_execute('ALTER TABLE `mac_track_ports` ADD INDEX `site_id_device_id`(`site_id`, `device_id`);'); - } - - # new for 2.1.2 - # SNMP V3 - mactrack_add_column('mac_track_devices', - 'term_type', - "ALTER TABLE `mac_track_devices` ADD COLUMN `term_type` tinyint(11) NOT NULL default '1' AFTER `scan_type`"); - - mactrack_add_column('mac_track_devices', - 'user_name', - "ALTER TABLE `mac_track_devices` ADD COLUMN `user_name` varchar(40) default NULL AFTER `term_type`"); - - mactrack_add_column('mac_track_devices', - 'user_password', - "ALTER TABLE `mac_track_devices` ADD COLUMN `user_password` varchar(40) default NULL AFTER `user_name`"); - - mactrack_add_column('mac_track_devices', - 'private_key_path', - "ALTER TABLE `mac_track_devices` ADD COLUMN `private_key_path` varchar(128) default '' AFTER `user_password`"); - - mactrack_add_column('mac_track_devices', - 'snmp_options', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_options` int(10) unsigned NOT NULL default '0' AFTER `private_key_path`"); - - mactrack_add_column('mac_track_devices', - 'snmp_username', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_username` varchar(50) default NULL AFTER `snmp_status`"); - - mactrack_add_column('mac_track_devices', - 'snmp_password', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_password` varchar(50) default NULL AFTER `snmp_username`"); - - mactrack_add_column('mac_track_devices', - 'snmp_auth_protocol', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_auth_protocol` char(5) default '' AFTER `snmp_password`"); - - mactrack_add_column('mac_track_devices', - 'snmp_priv_passphrase', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_priv_passphrase` varchar(200) default '' AFTER `snmp_auth_protocol`"); - - mactrack_add_column('mac_track_devices', - 'snmp_priv_protocol', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_priv_protocol` char(6) default '' AFTER `snmp_priv_passphrase`"); - - mactrack_add_column('mac_track_devices', - 'snmp_context', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_context` varchar(64) default '' AFTER `snmp_priv_protocol`"); - - mactrack_add_column('mac_track_devices', - 'max_oids', - "ALTER TABLE `mac_track_devices` ADD COLUMN `max_oids` int(12) unsigned default '10' AFTER `snmp_context`"); - - mactrack_add_column('mac_track_devices', - 'snmp_engine_id', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`"); - - mactrack_add_column('mac_track_devices', - 'term_type', - "ALTER TABLE `mac_track_devices` ADD COLUMN `term_type` tinyint(11) NOT NULL default '1' AFTER `scan_type`"); - - mactrack_add_column('mac_track_devices', - 'private_key_path', - "ALTER TABLE `mac_track_devices` ADD COLUMN `private_key_path` varchar(128) default '' AFTER `user_password`"); - - if (!db_table_exists('mac_track_snmp')) { - $data = array(); - $data['columns'][] = array('name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'name', 'type' => 'varchar(100)', 'NULL' => false); - $data['primary'] = 'id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Group of SNMP Option Sets'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); - } - - if (!db_table_exists('mac_track_snmp_items')) { - $data = array(); - $data['columns'][] = array('name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161'); - $data['columns'][] = array('name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500'); - $data['columns'][] = array('name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3'); - $data['columns'][] = array('name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10'); - $data['columns'][] = array('name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true); - $data['primary'] = 'id`,`snmp_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Set of SNMP Options'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); - } - - mactrack_add_column('mac_track_snmp_items', - 'snmp_engine_id', - "ALTER TABLE `mac_track_snmp_items` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`"); - - if (!db_table_exists('mac_track_interface_graphs')) { - $data = array(); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1'); - $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; - $data['keys'][] = array('name' => 'host_id', 'columns' => 'host_id'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); - } - - mactrack_add_column('mac_track_interfaces', - 'ifMauAutoNegAdminStatus', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegAdminStatus` integer UNSIGNED NOT NULL default '0' AFTER `ifDuplex`"); - - mactrack_add_column('mac_track_interfaces', - 'ifMauAutoNegRemoteSignaling', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegRemoteSignaling` integer UNSIGNED NOT NULL default '0' AFTER `ifMauAutoNegAdminStatus`"); - - mactrack_add_column('mac_track_device_types', - 'dot1x_scanning_function', - "ALTER TABLE `mac_track_device_types` ADD COLUMN `dot1x_scanning_function` varchar(100) default '' AFTER `ip_scanning_function`"); - - mactrack_add_column('mac_track_device_types', - 'serial_number_oid', - "ALTER TABLE `mac_track_device_types` ADD COLUMN `serial_number_oid` varchar(100) default '' AFTER `dot1x_scanning_function`"); - - mactrack_add_column('mac_track_sites', - 'customer_contact', - "ALTER TABLE `mac_track_sites` ADD COLUMN `customer_contact` varchar(150) default '' AFTER `site_name`"); - - mactrack_add_column('mac_track_sites', - 'netops_contact', - "ALTER TABLE `mac_track_sites` ADD COLUMN `netops_contact` varchar(150) default '' AFTER `customer_contact`"); - - mactrack_add_column('mac_track_sites', - 'facilities_contact', - "ALTER TABLE `mac_track_sites` ADD COLUMN `facilities_contact` varchar(150) default '' AFTER `netops_contact`"); - - mactrack_add_column('mac_track_sites', - 'site_info', - "ALTER TABLE `mac_track_sites` ADD COLUMN `site_info` text AFTER `facilities_contact`"); - - mactrack_add_column('mac_track_sites', - 'skip_vlans', - "ALTER TABLE `mac_track_sites` ADD COLUMN `skip_vlans` text DEFAULT ''"); - - mactrack_add_column('mac_track_sites', - 'scan_vlans', - "ALTER TABLE `mac_track_sites` ADD COLUMN `scan_vlans` text DEFAULT ''"); - - mactrack_add_column('mac_track_devices', - 'device_name', - "ALTER TABLE `mac_track_devices` ADD COLUMN `device_name` varchar(100) default '' AFTER `host_id`"); - - mactrack_add_column('mac_track_devices', - 'notes', - "ALTER TABLE `mac_track_devices` ADD COLUMN `notes` text AFTER `hostname`"); - - mactrack_add_column('mac_track_devices', - 'scan_trunk_port', - "ALTER TABLE `mac_track_devices` ADD COLUMN `scan_trunk_port` text DEFAULT ''"); - - mactrack_add_column('mac_track_scanning_functions', - 'type', - "ALTER TABLE `mac_track_scanning_functions` ADD COLUMN `type` int(10) unsigned NOT NULL default '0' AFTER `scanning_function`"); - - mactrack_add_column('mac_track_temp_ports', - 'device_name', - "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`"); - - mactrack_add_column('mac_track_temp_ports', - 'vendor_mac', - "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`"); - - mactrack_add_column('mac_track_temp_ports', - 'authorized', - "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `updated`"); - - mactrack_add_column('mac_track_ports', - 'device_name', - "ALTER TABLE `mac_track_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`"); - - mactrack_add_column('mac_track_ports', - 'vendor_mac', - "ALTER TABLE `mac_track_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`"); - - mactrack_add_column('mac_track_ports', - 'authorized', - "ALTER TABLE `mac_track_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `scan_date`"); - - mactrack_add_column('mac_track_ips', - 'device_name', - "ALTER TABLE `mac_track_ips` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`"); - - $columns = array_rekey( - db_fetch_assoc('SHOW COLUMNS FROM mac_track_ips'), - 'Field', 'Type' - ); - - if (strpos($columns['port_number'], 'int(10)') !== false) { - db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - } elseif (strpos($columns['port_number'], 'varchar(20)') !== false) { - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - } else { - db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN first_scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN last_rundate TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_max_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_current_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_processes MODIFY COLUMN start_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_scan_dates MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - } - - if (!db_table_exists('mac_track_arp')) { - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'mac_address`, `ip_address'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Table for VRF ARP translation'; - api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); - } - - $tables = db_fetch_assoc("SELECT DISTINCT TABLE_NAME + $tables = db_fetch_assoc("SELECT DISTINCT TABLE_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME LIKE 'mac_track%'"); - if (cacti_sizeof($tables)) { - foreach ($tables as $table) { - $columns = db_fetch_assoc("SELECT * + if (cacti_sizeof($tables)) { + foreach ($tables as $table) { + $columns = db_fetch_assoc("SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=SCHEMA() - AND TABLE_NAME='" . $table['TABLE_NAME'] . "' + AND TABLE_NAME='".$table['TABLE_NAME']."' AND DATA_TYPE LIKE '%char%' AND COLUMN_DEFAULT IS NULL"); - if (cacti_sizeof($columns)) { - $alter = 'ALTER TABLE `' . $table['TABLE_NAME'] . '` '; + if (cacti_sizeof($columns)) { + $alter = 'ALTER TABLE `'.$table['TABLE_NAME'].'` '; - $i = 0; - foreach($columns as $column) { - $alter .= ($i == 0 ? '': ', ') . ' MODIFY COLUMN `' . $column['COLUMN_NAME'] . '` ' . $column['COLUMN_TYPE'] . ($column['IS_NULLABLE'] == 'NO' ? ' NOT NULL' : '') . ' DEFAULT ""'; - $i++; - } + $i = 0; + foreach ($columns as $column) { + $alter .= (0 == $i ? '' : ', ').' MODIFY COLUMN `'.$column['COLUMN_NAME'].'` '.$column['COLUMN_TYPE'].('NO' == $column['IS_NULLABLE'] ? ' NOT NULL' : '').' DEFAULT ""'; + ++$i; + } - db_execute($alter); - } - } - } + db_execute($alter); + } + } + } - // new for 4.6 - mactrack_add_column('mac_track_device_types', - 'disabled', - "ALTER TABLE `mac_track_device_types` ADD COLUMN `disabled` varchar(2) default '' AFTER `highPort`"); + // new for 4.6 + mactrack_add_column( + 'mac_track_device_types', + 'disabled', + "ALTER TABLE `mac_track_device_types` ADD COLUMN `disabled` varchar(2) default '' AFTER `highPort`" + ); - // add few device types examples if does not exist - $count = db_fetch_cell("SELECT COUNT(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); + // add few device types examples if does not exist + $count = db_fetch_cell("SELECT COUNT(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); - if ($count == 0) { - db_execute("INSERT INTO mac_track_device_types + if (0 == $count) { + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5130-default','H3C','2','','.1.3.6.1.4.1.25506.11.1.18*','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6300-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.109','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6200-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.300','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 1920-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.164','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5140-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.297','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2530 8p-default','HPE','2','','.1.3.6.1.4.1.11.2.3.7.11.141','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2930 8p-default','Aruba','2','','.1.3.6.1.4.1.11.2.3.7.11.181.16','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2600 Router-default','Cisco','3','*C2600*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960S Switch-default','Cisco','2','*C2960S*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3550 Switch-default','Cisco','2','*C3550*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3750 Switch-default','Cisco','2','*C3750*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*cat4000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2900 Router-default','Cisco','3','*C2900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ASR Router-default','Cisco','3','*ASR1000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('6513 Switch/Router-default','Cisco','2','*s72033_rp*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CE500 Switch-default','Cisco','1','*CE500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2950 Switch-default','Cisco','2','*C2950*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2800 Router-default','Cisco','3','*C2800*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('BladeCenter2 10G-default','Cisco','2','*CBS31X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('DellBladeCenter-default','Dell','2','*Ethernet Switch*','','get_dell_dot1q_switch_ports','get_CTAlias_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG224-default','Cisco','3','*vg224*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C870 Router-default','Cisco','3','*C870*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Cisco ASA-default','Cisco','3','*Adaptive Security Appliance*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3x50 Switch-default','Cisco','2','*CAT3K*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3900 Router-default','Cisco','3','*C3900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Blade Center 10/100-default','Cisco','2','*CIGESM-I6K2L2Q4-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT4500-default','Cisco','2','*cat4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3560 Switch-default','Cisco','2','*C3560*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ProCurve Switch-default','HP','2','*ProCurve Switch*','','get_procurve_ngi_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT3K_CAA-UNIVERSALK9-M-default','Cisco','2','*CAT3K_CAA-UNIVERSALK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('IBM Flex System Fabric-default','IBM','2','*IBM Flex System Fabric*','','get_generic_dot1q_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960X Switch-default','Cisco','2','*C2960X*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Lite-default','Cisco','2','*C2960-LANLITEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Base-default','Cisco','2','*C2960-LANBASEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG3X0-default','Cisco','3','*VG3X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('93xx + 94xx Switch-default','Cisco','2','*CAT9K_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('43xx Router-default','Cisco','3','*ISR Software*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus Generic-default','Cisco','2','*nxos*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 7K-default','Cisco','2','*n7000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','.1.3.6.1.4.1.9.12.3.1.3.932',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 5K-default','Cisco','2','*n5000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('92xx Switch-default','Cisco','1','*CAT9K_LITE_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - } + } - db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN scan_trunk_port text NULL default ''"); + db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN scan_trunk_port text NULL default ''"); - // Change old realm names - if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Viewer'")) { - db_fetch_cell("UPDATE plugin_realms set display='Mactrack Viewer' WHERE plugin = 'mactrack' and display='Device Tracking Viewer'"); - } - if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Administrator'")) { - db_fetch_cell("UPDATE plugin_realms set display='Mactrack Administrator' WHERE plugin = 'mactrack' and display='Device Tracking Administrator'"); - } + // Change old realm names + if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Viewer'")) { + db_fetch_cell("UPDATE plugin_realms set display='Mactrack Viewer' WHERE plugin = 'mactrack' and display='Device Tracking Viewer'"); + } + if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Administrator'")) { + db_fetch_cell("UPDATE plugin_realms set display='Mactrack Administrator' WHERE plugin = 'mactrack' and display='Device Tracking Administrator'"); + } - // 4.9 - $keys = db_fetch_assoc('SHOW INDEXES FROM mac_track_aggregated_ports WHERE KEY_NAME="port_number"'); + // 4.9 + $keys = db_fetch_assoc('SHOW INDEXES FROM mac_track_aggregated_ports WHERE KEY_NAME="port_number"'); - if ($keys != 7) { - db_execute("ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number"); + if (7 != $keys) { + db_execute('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number'); - db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("ALTER TABLE mac_track_aggregated_ports ADD INDEX `port_number` (`port_number`, `mac_address`, `ip_address`, `device_id`, `site_id`, `vlan_id`, `authorized`)"); + db_execute('ALTER TABLE mac_track_aggregated_ports ADD INDEX `port_number` (`port_number`, `mac_address`, `ip_address`, `device_id`, `site_id`, `vlan_id`, `authorized`)'); - db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); - } + db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); + } - // default site must exist - if (!db_fetch_cell("SELECT count(*) FROM mac_track_sites")) { - db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); - } + // default site must exist + if (!db_fetch_cell('SELECT count(*) FROM mac_track_sites')) { + db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); + } } -function mactrack_setup_database() { - $data = array(); - $data['columns'][] = array('name' => 'row_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A'); - $data['columns'][] = array('name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'date_last', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP'); - $data['columns'][] = array('name' => 'first_scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'count_rec', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'active_last', 'unsigned' => true, 'type' => 'tinyint(1)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['primary'] = 'row_id'; - $data['unique_keys'][] = array('name' => 'port_number', 'columns' => 'port_number`,`mac_address`,`ip_address`,`device_id`,`site_id`,`vlan_id`,`authorized'); - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['keys'][] = array('name' => 'device_name', 'columns' => 'device_name'); - $data['keys'][] = array('name' => 'mac', 'columns' => 'mac_address'); - $data['keys'][] = array('name' => 'hostname', 'columns' => 'hostname'); - $data['keys'][] = array('name' => 'vlan_name', 'columns' => 'vlan_name'); - $data['keys'][] = array('name' => 'vlan_id', 'columns' => 'vlan_id'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['keys'][] = array('name' => 'ip_address', 'columns' => 'ip_address'); - $data['keys'][] = array('name' => 'port_name', 'columns' => 'port_name'); - $data['keys'][] = array('name' => 'dns_hostname', 'columns' => 'dns_hostname'); - $data['keys'][] = array('name' => 'vendor_mac', 'columns' => 'vendor_mac'); - $data['keys'][] = array('name' => 'authorized', 'columns' => 'authorized'); - $data['keys'][] = array('name' => 'site_id_device_id', 'columns' => 'site_id`,`device_id'); - $data['type'] = 'InnoDB'; - $data['comment'] = 'Database for aggregated date for Tracking Device MACs'; - api_plugin_db_table_create('mactrack', 'mac_track_aggregated_ports', $data); - - $data = array(); - $data['columns'][] = array('name' => 'mac_prefix', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => ''); - $data['primary'] = 'mac_prefix'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_approved_macs', $data); - - $data = array(); - $data['columns'][] = array('name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'device_type', 'type' => 'varchar(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'sysDescr_match', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'sysObjectID_match', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ip_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'dot1x_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'serial_number_oid', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'lowPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'highPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'disabled', 'type' => 'varchar(2)', 'NULL' => false, 'default' => ''); - $data['primary'] = 'device_type_id'; - $data['unique_keys'][] = array('name' => 'snmp_info', 'columns' => 'sysDescr_match`,`sysObjectID_match`,`device_type'); - $data['keys'][] = array('name' => 'device_type', 'columns' => 'device_type'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_device_types', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'host_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0'); - $data['columns'][] = array('name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'notes', 'type' => 'text', 'NULL' => true); - $data['columns'][] = array('name' => 'disabled', 'type' => 'char(2)', 'NULL' => true); - $data['columns'][] = array('name' => 'ignorePorts', 'type' => 'varchar(255)', 'NULL' => true); - $data['columns'][] = array('name' => 'ips_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'vlans_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ports_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ports_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ports_trunk', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'macs_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'scan_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1'); - $data['columns'][] = array('name' => 'term_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1'); - $data['columns'][] = array('name' => 'user_name', 'type' => 'varchar(40)', 'NULL' => true); - $data['columns'][] = array('name' => 'user_password', 'type' => 'varchar(40)', 'NULL' => true); - $data['columns'][] = array('name' => 'private_key_path', 'type' => 'varchar(128)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_options', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'snmp_readstrings', 'type' => 'varchar(255)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161'); - $data['columns'][] = array('name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500'); - $data['columns'][] = array('name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3'); - $data['columns'][] = array('name' => 'snmp_sysName', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_sysLocation', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_sysContact', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_sysObjectID', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_sysDescr', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_sysUptime', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true); - $data['columns'][] = array('name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10'); - $data['columns'][] = array('name' => 'last_runmessage', 'type' => 'varchar(100)', 'NULL' => true); - $data['columns'][] = array('name' => 'last_rundate', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'last_runduration', 'type' => 'decimal(10,5)', 'NULL' => false, 'default' => '0.00000'); - $data['columns'][] = array('name' => 'scan_trunk_port', 'type' => 'text', 'NULL' => true, 'default' => ''); - $data['primary'] = 'device_id'; - $data['unique_keys'][] = array('name' => 'hostname_snmp_port_site_id', 'columns' => 'hostname`,`snmp_port`,`site_id'); - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['keys'][] = array('name' => 'host_id', 'columns' => 'host_id'); - $data['keys'][] = array('name' => 'snmp_sysDescr', 'columns' => 'snmp_sysDescr'); - $data['keys'][] = array('name' => 'snmp_sysObjectID', 'columns' => 'snmp_sysObjectID'); - $data['keys'][] = array('name' => 'device_type_id', 'columns' => 'device_type_id'); - $data['keys'][] = array('name' => 'device_name', 'columns' => 'device_name'); - $data['type'] = 'InnoDB'; - $data['comment'] = 'Devices to be scanned for MAC addresses'; - api_plugin_db_table_create('mactrack', 'mac_track_devices', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'username', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'domain', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; - $data['keys'][] = array('name' => 'ip', 'columns' => 'ip_address'); - $data['keys'][] = array('name' => 'port_number', 'columns' => 'port_number'); - $data['keys'][] = array('name' => 'mac', 'columns' => 'mac_address'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['keys'][] = array('name' => 'username', 'columns' => 'username'); - $data['keys'][] = array('name' => 'hostname', 'columns' => 'hostname'); - $data['keys'][] = array('name' => 'scan_date', 'columns' => 'scan_date'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_dot1x', $data); - - $data = array(); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1'); - $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; - $data['keys'][] = array('name' => 'host_id', 'columns' => 'host_id'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'sysUptime', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifName', 'type' => 'varchar(128)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ifAlias', 'type' => 'varchar(255)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ifDescr', 'type' => 'varchar(128)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ifType', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifMtu', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifHighSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifDuplex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifMauAutoNegAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifMauAutoNegRemoteSignaling', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifPhysAddress', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ifAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOperStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifLastChange', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'linkPort', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vlan_trunk', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false); - $data['columns'][] = array('name' => 'vlan_trunk_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifInDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifInErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifInUnknownProtos', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOutDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0'); - $data['columns'][] = array('name' => 'ifOutErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0'); - $data['columns'][] = array('name' => 'inBound', 'type' => 'double', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'outBound', 'type' => 'double', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInDiscards', 'unsigned' => true, 'type' => "float", 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInErrors', 'unsigned' => true, 'type' => "float", 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifInUnknownProtos', 'unsigned' => true, 'type' => "float", 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutDiscards', 'unsigned' => true, 'type' => "float", 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_ifOutErrors', 'unsigned' => true, 'type' => "float", 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'last_up_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'last_down_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'stateChanges', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_discards_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'int_errors_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['primary'] = 'site_id`,`device_id`,`ifIndex'; - $data['keys'][] = array('name' => 'ifDescr', 'columns' => 'ifDescr'); - $data['keys'][] = array('name' => 'ifType', 'columns' => 'ifType'); - $data['keys'][] = array('name' => 'ifSpeed', 'columns' => 'ifSpeed'); - $data['keys'][] = array('name' => 'ifMTU', 'columns' => 'ifMtu'); - $data['keys'][] = array('name' => 'ifAdminStatus', 'columns' => 'ifAdminStatus'); - $data['keys'][] = array('name' => 'ifOperStatus', 'columns' => 'ifOperStatus'); - $data['keys'][] = array('name' => 'ifInDiscards', 'columns' => 'ifInUnknownProtos'); - $data['keys'][] = array('name' => 'ifInErrors', 'columns' => 'ifInUnknownProtos'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_interfaces', $data); - - $data = array(); - $data['columns'][] = array('name' => 'ip_range', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ips_max', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ips_current', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'ips_max_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'ips_current_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'ip_range`,`site_id'; - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_ip_ranges', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; - $data['keys'][] = array('name' => 'ip', 'columns' => 'ip_address'); - $data['keys'][] = array('name' => 'port_number', 'columns' => 'port_number'); - $data['keys'][] = array('name' => 'mac', 'columns' => 'mac_address'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['keys'][] = array('name' => 'hostname', 'columns' => 'hostname'); - $data['keys'][] = array('name' => 'scan_date', 'columns' => 'scan_date'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_ips', $data); - - $data = array(); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'added_date', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP'); - $data['columns'][] = array('name' => 'added_by', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['primary'] = 'mac_address'; - $data['keys'][] = array('name' => 'mac_id', 'columns' => 'mac_id'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_macauth', $data); - - $data = array(); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'name', 'type' => 'varchar(45)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'ticket_number', 'type' => 'varchar(45)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'notify_schedule', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false); - $data['columns'][] = array('name' => 'email_addresses', 'type' => 'varchar(255)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'discovered', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false); - $data['columns'][] = array('name' => 'date_first_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'date_last_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'date_last_notif', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'mac_address'; - $data['keys'][] = array('name' => 'mac_id', 'columns' => 'mac_id'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_macwatch', $data); - - $data = array(); - $data['columns'][] = array('name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor_address', 'type' => 'text', 'NULL' => false); - $data['columns'][] = array('name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1'); - $data['primary'] = 'vendor_mac'; - $data['keys'][] = array('name' => 'vendor_name', 'columns' => 'vendor_name'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_oui_database', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A'); - $data['columns'][] = array('name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true, 'default' => ''); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['keys'][] = array('name' => 'scan_date', 'columns' => 'scan_date'); - $data['keys'][] = array('name' => 'description', 'columns' => 'device_name'); - $data['keys'][] = array('name' => 'mac', 'columns' => 'mac_address'); - $data['keys'][] = array('name' => 'hostname', 'columns' => 'hostname'); - $data['keys'][] = array('name' => 'vlan_name', 'columns' => 'vlan_name'); - $data['keys'][] = array('name' => 'vlan_id', 'columns' => 'vlan_id'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['keys'][] = array('name' => 'ip_address', 'columns' => 'ip_address'); - $data['keys'][] = array('name' => 'port_name', 'columns' => 'port_name'); - $data['keys'][] = array('name' => 'dns_hostname', 'columns' => 'dns_hostname'); - $data['keys'][] = array('name' => 'vendor_mac', 'columns' => 'vendor_mac'); - $data['keys'][] = array('name' => 'authorized', 'columns' => 'authorized'); - $data['type'] = 'InnoDB'; - $data['comment'] = 'Database for Tracking Device MACs'; - api_plugin_db_table_create('mactrack', 'mac_track_ports', $data); - - $data = array(); - $data['columns'][] = array('name' => 'device_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'process_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true); - $data['columns'][] = array('name' => 'status', 'type' => 'varchar(20)', 'NULL' => false, 'default' => 'Queued'); - $data['columns'][] = array('name' => 'start_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'device_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_processes', $data); - - $data = array(); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'scan_date'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_scan_dates', $data); - - $data = array(); - $data['columns'][] = array('name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false); - $data['columns'][] = array('name' => 'type', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'description', 'type' => 'varchar(200)', 'NULL' => false); - $data['primary'] = 'scanning_function'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Registered Scanning Functions'; - api_plugin_db_table_create('mactrack', 'mac_track_scanning_functions', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'site_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'customer_contact', 'type' => 'varchar(150)', 'NULL' => true); - $data['columns'][] = array('name' => 'netops_contact', 'type' => 'varchar(150)', 'NULL' => true); - $data['columns'][] = array('name' => 'facilities_contact', 'type' => 'varchar(150)', 'NULL' => true); - $data['columns'][] = array('name' => 'site_info', 'type' => 'text', 'NULL' => true); - $data['columns'][] = array('name' => 'total_devices', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'total_device_errors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'total_macs', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'total_ips', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'total_user_ports', 'type' => 'int(11)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'total_oper_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'total_trunk_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'skip_vlans', 'type' => 'text', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'scan_vlans', 'type' => 'text', 'NULL' => false, 'default' => ''); - $data['primary'] = 'site_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_sites', $data); - - // default site must exist - db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); - - - $data = array(); - $data['columns'][] = array('name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['primary'] = 'id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Group of SNMP Option Sets'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); - - $data = array(); - $data['columns'][] = array('name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true); - $data['columns'][] = array('name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161'); - $data['columns'][] = array('name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500'); - $data['columns'][] = array('name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3'); - $data['columns'][] = array('name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10'); - $data['columns'][] = array('name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true); - $data['columns'][] = array('name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true); - $data['primary'] = 'id`,`snmp_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Set of SNMP Options'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A'); - $data['columns'][] = array('name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true); - $data['columns'][] = array('name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['columns'][] = array('name' => 'updated', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['columns'][] = array('name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'); - $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; - $data['keys'][] = array('name' => 'site_id', 'columns' => 'site_id'); - $data['keys'][] = array('name' => 'device_name', 'columns' => 'device_name'); - $data['keys'][] = array('name' => 'ip_address', 'columns' => 'ip_address'); - $data['keys'][] = array('name' => 'hostname', 'columns' => 'hostname'); - $data['keys'][] = array('name' => 'vlan_name', 'columns' => 'vlan_name'); - $data['keys'][] = array('name' => 'vlan_id', 'columns' => 'vlan_id'); - $data['keys'][] = array('name' => 'device_id', 'columns' => 'device_id'); - $data['keys'][] = array('name' => 'mac', 'columns' => 'mac_address'); - $data['keys'][] = array('name' => 'updated', 'columns' => 'updated'); - $data['keys'][] = array('name' => 'vendor_mac', 'columns' => 'vendor_mac'); - $data['keys'][] = array('name' => 'authorized', 'columns' => 'authorized'); - $data['type'] = 'InnoDB'; - $data['comment'] = 'Database for Storing Temporary Results for Tracking Device MACS'; - api_plugin_db_table_create('mactrack', 'mac_track_temp_ports', $data); - - $data = array(); - $data['columns'][] = array('name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1'); - $data['primary'] = 'vlan_id`,`site_id`,`device_id'; - $data['keys'][] = array('name' => 'vlan_name', 'columns' => 'vlan_name'); - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_vlans', $data); - - $data = array(); - $data['columns'][] = array('name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false); - $data['columns'][] = array('name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => ''); - $data['columns'][] = array('name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => ''); - $data['columns'][] = array('name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00'); - $data['primary'] = 'mac_address`, `ip_address'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Table for VRF ARP translation'; - api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); - - - // add few device types examples if does not exist - $count = db_fetch_cell("SELECT count(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); - if ($count == 0) { - - db_execute("INSERT INTO mac_track_device_types +function mactrack_setup_database() +{ + $data = []; + $data['columns'][] = ['name' => 'row_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'date_last', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP']; + $data['columns'][] = ['name' => 'first_scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'count_rec', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'active_last', 'unsigned' => true, 'type' => 'tinyint(1)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'row_id'; + $data['unique_keys'][] = ['name' => 'port_number', 'columns' => 'port_number`,`mac_address`,`ip_address`,`device_id`,`site_id`,`vlan_id`,`authorized']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_name', 'columns' => 'port_name']; + $data['keys'][] = ['name' => 'dns_hostname', 'columns' => 'dns_hostname']; + $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; + $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; + $data['keys'][] = ['name' => 'site_id_device_id', 'columns' => 'site_id`,`device_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Database for aggregated date for Tracking Device MACs'; + api_plugin_db_table_create('mactrack', 'mac_track_aggregated_ports', $data); + + $data = []; + $data['columns'][] = ['name' => 'mac_prefix', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'mac_prefix'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_approved_macs', $data); + + $data = []; + $data['columns'][] = ['name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_type', 'type' => 'varchar(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sysDescr_match', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'sysObjectID_match', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ip_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dot1x_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'serial_number_oid', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'lowPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'highPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'disabled', 'type' => 'varchar(2)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'device_type_id'; + $data['unique_keys'][] = ['name' => 'snmp_info', 'columns' => 'sysDescr_match`,`sysObjectID_match`,`device_type']; + $data['keys'][] = ['name' => 'device_type', 'columns' => 'device_type']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_device_types', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'host_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'notes', 'type' => 'text', 'NULL' => true]; + $data['columns'][] = ['name' => 'disabled', 'type' => 'char(2)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ignorePorts', 'type' => 'varchar(255)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ips_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'vlans_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ports_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ports_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ports_trunk', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'macs_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'scan_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1']; + $data['columns'][] = ['name' => 'term_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1']; + $data['columns'][] = ['name' => 'user_name', 'type' => 'varchar(40)', 'NULL' => true]; + $data['columns'][] = ['name' => 'user_password', 'type' => 'varchar(40)', 'NULL' => true]; + $data['columns'][] = ['name' => 'private_key_path', 'type' => 'varchar(128)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_options', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_readstrings', 'type' => 'varchar(255)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; + $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; + $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; + $data['columns'][] = ['name' => 'snmp_sysName', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysLocation', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysContact', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysObjectID', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysDescr', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysUptime', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; + $data['columns'][] = ['name' => 'last_runmessage', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'last_rundate', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'last_runduration', 'type' => 'decimal(10,5)', 'NULL' => false, 'default' => '0.00000']; + $data['columns'][] = ['name' => 'scan_trunk_port', 'type' => 'text', 'NULL' => true, 'default' => '']; + $data['primary'] = 'device_id'; + $data['unique_keys'][] = ['name' => 'hostname_snmp_port_site_id', 'columns' => 'hostname`,`snmp_port`,`site_id']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; + $data['keys'][] = ['name' => 'snmp_sysDescr', 'columns' => 'snmp_sysDescr']; + $data['keys'][] = ['name' => 'snmp_sysObjectID', 'columns' => 'snmp_sysObjectID']; + $data['keys'][] = ['name' => 'device_type_id', 'columns' => 'device_type_id']; + $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Devices to be scanned for MAC addresses'; + api_plugin_db_table_create('mactrack', 'mac_track_devices', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'username', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'domain', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; + $data['keys'][] = ['name' => 'ip', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'username', 'columns' => 'username']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_dot1x', $data); + + $data = []; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1']; + $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; + $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sysUptime', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifAlias', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifDescr', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifType', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifMtu', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifHighSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifDuplex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifMauAutoNegAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifMauAutoNegRemoteSignaling', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifPhysAddress', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOperStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifLastChange', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'linkPort', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_trunk', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; + $data['columns'][] = ['name' => 'vlan_trunk_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInUnknownProtos', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; + $data['columns'][] = ['name' => 'inBound', 'type' => 'double', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'outBound', 'type' => 'double', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInDiscards', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInErrors', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInUnknownProtos', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutDiscards', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutErrors', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'last_up_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'last_down_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'stateChanges', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_discards_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_errors_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'site_id`,`device_id`,`ifIndex'; + $data['keys'][] = ['name' => 'ifDescr', 'columns' => 'ifDescr']; + $data['keys'][] = ['name' => 'ifType', 'columns' => 'ifType']; + $data['keys'][] = ['name' => 'ifSpeed', 'columns' => 'ifSpeed']; + $data['keys'][] = ['name' => 'ifMTU', 'columns' => 'ifMtu']; + $data['keys'][] = ['name' => 'ifAdminStatus', 'columns' => 'ifAdminStatus']; + $data['keys'][] = ['name' => 'ifOperStatus', 'columns' => 'ifOperStatus']; + $data['keys'][] = ['name' => 'ifInDiscards', 'columns' => 'ifInUnknownProtos']; + $data['keys'][] = ['name' => 'ifInErrors', 'columns' => 'ifInUnknownProtos']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_interfaces', $data); + + $data = []; + $data['columns'][] = ['name' => 'ip_range', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ips_max', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ips_current', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ips_max_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'ips_current_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'ip_range`,`site_id'; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_ip_ranges', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; + $data['keys'][] = ['name' => 'ip', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_ips', $data); + + $data = []; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'added_date', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP']; + $data['columns'][] = ['name' => 'added_by', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'mac_address'; + $data['keys'][] = ['name' => 'mac_id', 'columns' => 'mac_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_macauth', $data); + + $data = []; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(45)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ticket_number', 'type' => 'varchar(45)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'notify_schedule', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; + $data['columns'][] = ['name' => 'email_addresses', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'discovered', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; + $data['columns'][] = ['name' => 'date_first_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'date_last_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'date_last_notif', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'mac_address'; + $data['keys'][] = ['name' => 'mac_id', 'columns' => 'mac_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_macwatch', $data); + + $data = []; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_address', 'type' => 'text', 'NULL' => false]; + $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1']; + $data['primary'] = 'vendor_mac'; + $data['keys'][] = ['name' => 'vendor_name', 'columns' => 'vendor_name']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_oui_database', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true, 'default' => '']; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; + $data['keys'][] = ['name' => 'description', 'columns' => 'device_name']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_name', 'columns' => 'port_name']; + $data['keys'][] = ['name' => 'dns_hostname', 'columns' => 'dns_hostname']; + $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; + $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Database for Tracking Device MACs'; + api_plugin_db_table_create('mactrack', 'mac_track_ports', $data); + + $data = []; + $data['columns'][] = ['name' => 'device_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'process_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true]; + $data['columns'][] = ['name' => 'status', 'type' => 'varchar(20)', 'NULL' => false, 'default' => 'Queued']; + $data['columns'][] = ['name' => 'start_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'device_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_processes', $data); + + $data = []; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'scan_date'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_scan_dates', $data); + + $data = []; + $data['columns'][] = ['name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false]; + $data['columns'][] = ['name' => 'type', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(200)', 'NULL' => false]; + $data['primary'] = 'scanning_function'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Registered Scanning Functions'; + api_plugin_db_table_create('mactrack', 'mac_track_scanning_functions', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'site_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'customer_contact', 'type' => 'varchar(150)', 'NULL' => true]; + $data['columns'][] = ['name' => 'netops_contact', 'type' => 'varchar(150)', 'NULL' => true]; + $data['columns'][] = ['name' => 'facilities_contact', 'type' => 'varchar(150)', 'NULL' => true]; + $data['columns'][] = ['name' => 'site_info', 'type' => 'text', 'NULL' => true]; + $data['columns'][] = ['name' => 'total_devices', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_device_errors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_macs', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_ips', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_user_ports', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_oper_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_trunk_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'skip_vlans', 'type' => 'text', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_vlans', 'type' => 'text', 'NULL' => false, 'default' => '']; + $data['primary'] = 'site_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_sites', $data); + + // default site must exist + db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); + + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Group of SNMP Option Sets'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); + + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; + $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; + $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; + $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; + $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; + $data['primary'] = 'id`,`snmp_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Set of SNMP Options'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'updated', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; + $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'updated', 'columns' => 'updated']; + $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; + $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Database for Storing Temporary Results for Tracking Device MACS'; + api_plugin_db_table_create('mactrack', 'mac_track_temp_ports', $data); + + $data = []; + $data['columns'][] = ['name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1']; + $data['primary'] = 'vlan_id`,`site_id`,`device_id'; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_vlans', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'mac_address`, `ip_address'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Table for VRF ARP translation'; + api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); + + // add few device types examples if does not exist + $count = db_fetch_cell("SELECT count(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); + if (0 == $count) { + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5130-default','H3C','2','','.1.3.6.1.4.1.25506.11.1.18*','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6300-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.109','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6200-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.300','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 1920-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.164','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5140-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.297','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2530 8p-default','HPE','2','','.1.3.6.1.4.1.11.2.3.7.11.141','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2930 8p-default','Aruba','2','','.1.3.6.1.4.1.11.2.3.7.11.181.16','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2600 Router-default','Cisco','3','*C2600*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960S Switch-default','Cisco','2','*C2960S*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3550 Switch-default','Cisco','2','*C3550*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3750 Switch-default','Cisco','2','*C3750*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*cat4000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2900 Router-default','Cisco','3','*C2900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ASR Router-default','Cisco','3','*ASR1000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('6513 Switch/Router-default','Cisco','2','*s72033_rp*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CE500 Switch-default','Cisco','1','*CE500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2950 Switch-default','Cisco','2','*C2950*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2800 Router-default','Cisco','3','*C2800*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('BladeCenter2 10G-default','Cisco','2','*CBS31X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('DellBladeCenter-default','Dell','2','*Ethernet Switch*','','get_dell_dot1q_switch_ports','get_CTAlias_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG224-default','Cisco','3','*vg224*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C870 Router-default','Cisco','3','*C870*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Cisco ASA-default','Cisco','3','*Adaptive Security Appliance*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3x50 Switch-default','Cisco','2','*CAT3K*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3900 Router-default','Cisco','3','*C3900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Blade Center 10/100-default','Cisco','2','*CIGESM-I6K2L2Q4-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT4500-default','Cisco','2','*cat4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3560 Switch-default','Cisco','2','*C3560*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ProCurve Switch-default','HP','2','*ProCurve Switch*','','get_procurve_ngi_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT3K_CAA-UNIVERSALK9-M-default','Cisco','2','*CAT3K_CAA-UNIVERSALK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('IBM Flex System Fabric-default','IBM','2','*IBM Flex System Fabric*','','get_generic_dot1q_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960X Switch-default','Cisco','2','*C2960X*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Lite-default','Cisco','2','*C2960-LANLITEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Base-default','Cisco','2','*C2960-LANBASEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG3X0-default','Cisco','3','*VG3X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('93xx + 94xx Switch-default','Cisco','2','*CAT9K_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('43xx Router-default','Cisco','3','*ISR Software*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus Generic-default','Cisco','2','*nxos*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 7K-default','Cisco','2','*n7000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','.1.3.6.1.4.1.9.12.3.1.3.932',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 5K-default','Cisco','2','*n5000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('92xx Switch-default','Cisco','1','*CAT9K_LITE_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - } + } } - diff --git a/index.php b/index.php index 4f8fcac3..bc881c79 100644 --- a/index.php +++ b/index.php @@ -1,4 +1,5 @@ $ifd) { - if ($ifIndexes[$key]['ifName'] == '') { - $ifdesc = $device_descr_array[$key] ; - $ifdesc = preg_replace($pattern, $replacement, $ifdesc); - $ifdesc = preg_replace($pattern2, $replacement2, $ifdesc); - $ifdesc = preg_replace($pattern3, $replacement3, $ifdesc); - $ifIndexes[$key]['ifName'] = $ifdesc ; - - db_execute_prepared('UPDATE mac_track_interfaces + [$device['device_id']] + ); + + sort($local_graph_id); + + // Get ifDescr and Format it + $i = 0; + $device_descr_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); + if (cacti_sizeof($device_descr_array)) { + foreach ($device_descr_array as $key => $ifd) { + if ('' == $ifIndexes[$key]['ifName']) { + $ifdesc = $device_descr_array[$key]; + $ifdesc = preg_replace($pattern, $replacement, $ifdesc); + $ifdesc = preg_replace($pattern2, $replacement2, $ifdesc); + $ifdesc = preg_replace($pattern3, $replacement3, $ifdesc); + $ifIndexes[$key]['ifName'] = $ifdesc; + + db_execute_prepared( + 'UPDATE mac_track_interfaces SET ifName = ? WHERE device_id = ? AND ifIndex = ?', - array($ifdesc, $device['device_id'], $key)); + [$ifdesc, $device['device_id'], $key] + ); - if ($i 0) { - /* get bridge port to ifIndex mapping */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - /* get device active port numbers */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - /* get the ignore ports list from device */ - //$device['ignorePorts'] = $device['ignorePorts'].':Port1/50'; - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - foreach ($port_numbers as $key => $port_number) { - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort))) { - $ifname = $ifInterfaces[$bridgePortIfIndexes[$port_number]]['ifName']; - if (!in_array($ifname, $ignore_ports)) { - if (isset($port_status[$key]) && $port_status[$key] == '3') { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - $i++; - } - } - } - } - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes) != 0) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - } else { - $brPortIfIndex = isset($port_key['port_number']) ? $port_key['port_number'] : ''; - } - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if (((($brPortIfType >= 6) && - ($brPortIfType <= 9)) || $brPortIfType == 117 ) && - (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $new_port_key_array[$i]['port_name'] = $ifInterfaces[$brPortIfIndex]['ifName']; - - $i++; - } - } - } - mactrack_debug('Port number information collected.'); - - /* map mac address */ - /* only continue if there were user ports defined */ - if (cacti_sizeof($new_port_key_array) > 0) { - /* get the bridges active MAC addresses */ - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_3Com_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + mactrack_debug('Start get_3Com_base_dot1dTpFdbEntry_ports'); + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_descr = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + // get the console port + $link_ports = get_link_port_status($device); + + $i = 0; + foreach ($active_ports_array as $port_info) { + if ((6 == $ifInterfaces[$indexes[$i]]['ifType']) && (1 != $ifInterfaces[$indexes[$i]]['linkPort'])) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + // get the ignore ports list from device + // $device['ignorePorts'] = $device['ignorePorts'].':Port1/50'; + $ignore_ports = port_list_to_array($device['ignorePorts']); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + foreach ($port_numbers as $key => $port_number) { + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + $ifname = $ifInterfaces[$bridgePortIfIndexes[$port_number]]['ifName']; + if (!in_array($ifname, $ignore_ports)) { + if (isset($port_status[$key]) && '3' == $port_status[$key]) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + ++$i; + } + } + } + } + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (0 != cacti_sizeof($bridgePortIfIndexes)) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + } else { + $brPortIfIndex = isset($port_key['port_number']) ? $port_key['port_number'] : ''; + } + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if (((($brPortIfType >= 6) + && ($brPortIfType <= 9)) || 117 == $brPortIfType) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + $new_port_key_array[$i]['port_name'] = $ifInterfaces[$brPortIfIndex]['ifName']; + + ++$i; + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array) > 0) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } - diff --git a/lib/mactrack_aruba_oscx.php b/lib/mactrack_aruba_oscx.php index 554340f2..a85441b8 100644 --- a/lib/mactrack_aruba_oscx.php +++ b/lib/mactrack_aruba_oscx.php @@ -1,4 +1,5 @@ $value) { - $vlan_ids[$key] = $key; - } - - $device['vlans_total'] = cacti_sizeof($vlan_names); - mactrack_debug('There are ' . (cacti_sizeof($vlan_names)) . ' VLANS.'); - - /* - vlan_ids: - array(8) { - [1]=> - string(1) "1" - [102]=> - string(3) "102" - [103]=> - string(3) "103" - [122]=> - string(3) "122" - - vlan_names: - array(8) { - [1]=> - string(9) "VLAN 0001" - [102]=> - string(6) "kamery" - [103]=> - string(8) "technici" - [122]=> - string(10) "vlan122-pc" - [144]=> - string(11) "test 802.1x" - */ - - /* - ports vlan membership - .1.3.6.1.2.1.17.7.1.2.2 - tady je i cislo vlany, je to prvni kousek indexu, pak je mac adresa - last six - mac address, before - vlanid - .1.3.6.1.2.1.17.7.1.2.2.1.2.11.0.12.41.5.138.209 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.9.15.9.0.18 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.5.138.209 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.48.235.60 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.30.193.124.199.1 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.80.86.175.58.24 = INTEGER: 52 - */ - - $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); - $port_vlan_data = array(); - - foreach ($xdata as $key=>$value) { - $keys = explode('.', $key); - // it doesn't work for trunk ports. It If port has more vlans, last is used - if (!isset($port_vlan_data[$value])) { - $port_vlan_data[$value] = $keys[0]; - } - } - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete: ' . cacti_sizeof($ifIndexes)); - - // get and store the interfaces table - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - - foreach($ifIndexes as $ifIndex) { - if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { - $device['ports_total']++; - } - } - mactrack_debug('ifInterfaces assembly complete: ' . cacti_sizeof($ifIndexes)); - - // map vlans to bridge ports - if (cacti_sizeof($vlan_ids) > 0) { - // get the port status information - - $port_results = get_aruba_oscx_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); - - // get the ifIndexes for the device - $i = 0; - $j = 0; - $port_array = array(); - foreach($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - - $ifType = $ifInterfaces[$ifIndex]['ifType']; - - /* only output legitimate end user ports */ - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); - $port_array[$i]['vlan_name'] = isset($vlan_names[$port_array[$i]['vlan_id']]) ? $vlan_names[$port_array[$i]['vlan_id']] : ''; - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' . - 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' . - 'PORT: ' . $ifInterfaces[$ifIndex]['ifName'] . ', ' . - 'NAME: ' . $port_array[$i]['port_name'] . ', ' . - 'MAC: ' . $port_array[$i]['mac_address']); - - $i++; - } - - $j++; - } - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . trim(substr($device['snmp_sysDescr'],0,40)) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - mactrack_debug('macs active on this switch:' . $device['macs_active']); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_aruba_oscx_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + + /* + get VLAN information + .1.3.6.1.2.1.47.1.2.1.1.2 + .1.3.6.1.2.1.47.1.2.1.1.2.1 = STRING: "DEFAULT_VLAN_1" + .1.3.6.1.2.1.47.1.2.1.1.2.11 = STRING: "guest" + .1.3.6.1.2.1.47.1.2.1.1.2.199 = STRING: "management" + .1.3.6.1.2.1.47.1.2.1.1.2.215 = STRING: "x" + */ + + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); + + foreach ($vlan_names as $key => $value) { + $vlan_ids[$key] = $key; + } + + $device['vlans_total'] = cacti_sizeof($vlan_names); + mactrack_debug('There are '.cacti_sizeof($vlan_names).' VLANS.'); + + /* + vlan_ids: + array(8) { + [1]=> + string(1) "1" + [102]=> + string(3) "102" + [103]=> + string(3) "103" + [122]=> + string(3) "122" + + vlan_names: + array(8) { + [1]=> + string(9) "VLAN 0001" + [102]=> + string(6) "kamery" + [103]=> + string(8) "technici" + [122]=> + string(10) "vlan122-pc" + [144]=> + string(11) "test 802.1x" + */ + + /* + ports vlan membership + .1.3.6.1.2.1.17.7.1.2.2 - tady je i cislo vlany, je to prvni kousek indexu, pak je mac adresa + last six - mac address, before - vlanid + .1.3.6.1.2.1.17.7.1.2.2.1.2.11.0.12.41.5.138.209 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.9.15.9.0.18 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.5.138.209 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.48.235.60 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.30.193.124.199.1 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.80.86.175.58.24 = INTEGER: 52 + */ + + $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); + $port_vlan_data = []; + + foreach ($xdata as $key => $value) { + $keys = explode('.', $key); + // it doesn't work for trunk ports. It If port has more vlans, last is used + if (!isset($port_vlan_data[$value])) { + $port_vlan_data[$value] = $keys[0]; + } + } + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete: '.cacti_sizeof($ifIndexes)); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + + foreach ($ifIndexes as $ifIndex) { + if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { + ++$device['ports_total']; + } + } + mactrack_debug('ifInterfaces assembly complete: '.cacti_sizeof($ifIndexes)); + + // map vlans to bridge ports + if (cacti_sizeof($vlan_ids) > 0) { + // get the port status information + + $port_results = get_aruba_oscx_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); + + // get the ifIndexes for the device + $i = 0; + $j = 0; + $port_array = []; + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + + $ifType = $ifInterfaces[$ifIndex]['ifType']; + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); + $port_array[$i]['vlan_name'] = isset($vlan_names[$port_array[$i]['vlan_id']]) ? $vlan_names[$port_array[$i]['vlan_id']] : ''; + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' + .'NAME: '.$port_array[$i]['vlan_name'].', ' + .'PORT: '.$ifInterfaces[$ifIndex]['ifName'].', ' + .'NAME: '.$port_array[$i]['port_name'].', ' + .'MAC: '.$port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.trim(substr($device['snmp_sysDescr'], 0, 40)).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + mactrack_debug('macs active on this switch:'.$device['macs_active']); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_base_dot1dTpFdbEntry_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. This is a foundational function for all vendor data collection functions. */ -function get_aruba_oscx_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { - global $debug, $scan_date; - mactrack_debug('FUNCTION: get_aruba_oscx_dot1dTpFdbEntry_ports started'); - - /* initialize variables */ - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_key_array = array(); - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - /* cisco uses a hybrid read string, if one is not defined, use the default */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* get the operational status of the ports */ - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - mactrack_debug('get active ports: ' . cacti_sizeof($active_ports_array)); - $indexes = array_keys($active_ports_array); - - $i = 0; - foreach($active_ports_array as $port_info) { - if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { - if ($port_info == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 - where - table index = bridge port (dot1dBasePort) and - table value = ifIndex */ - /* -------------------------------------------- */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('get bridgePortIfIndexes: ' . cacti_sizeof($bridgePortIfIndexes)); - - /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ - /* -------------------------------------------- */ - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - mactrack_debug('get port_status: ' . cacti_sizeof($port_status)); - - /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = bridge port */ - /* -------------------------------------------- */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - mactrack_debug('get port_numbers: ' . cacti_sizeof($port_numbers)); - - /* get VLAN information */ - /* -------------------------------------------- */ - - $vlan_ids = array(); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); - foreach ($vlan_names as $key=>$value) { - $vlan_ids[$key] = $key; - } - - mactrack_debug('get vlan_ids: ' . cacti_sizeof($vlan_ids)); - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); - $port_vlan_data = array(); - - foreach ($xdata as $key=>$value) { - $keys = explode('.', $key); - $port_vlan_data[$value] = $keys[0]; - } - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - foreach ($port_numbers as $key => $port_number) { - /* key = MAC Address from dot1dTpFdbTable */ - /* value = bridge port */ - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort))) { - - if (!in_array($port_number, $ignore_ports)) { - if (isset($port_status[$key]) && $port_status[$key] == '3') { - $port_key_array[$i]['key'] = substr($key,1); - $port_key_array[$i]['port_number'] = $port_number; - $i++; - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - - $i = 0; - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes) != 0) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - mactrack_debug('Searching Bridge Port: ' . $port_key['port_number'] . ', Bridge: ' . $bridgePortIfIndexes[$port_key['port_number']]); - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - } else { - $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); - } - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if (($brPortIfType >= 6) && - ($brPortIfType <= 9) && - (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); - $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; - $new_port_key_array[$i]['port_name'] = mactrack_arr_key($ifInterfaces, $port_key['port_number']); - $new_port_key_array[$i]['mac_address'] = oscx_mac($port_key['key']); - $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $brPortIfIndex); - $new_port_key_array[$i]['vlan_name'] = isset ($brPortIfIndex) ? mactrack_arr_key($vlan_names, $port_vlan_data[$brPortIfIndex]) : ''; - - $i++; - } - } - } - mactrack_debug('Port number information collected: ' . cacti_sizeof($new_port_key_array)); - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } - +function get_aruba_oscx_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + mactrack_debug('FUNCTION: get_aruba_oscx_dot1dTpFdbEntry_ports started'); + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + mactrack_debug('get active ports: '.cacti_sizeof($active_ports_array)); + $indexes = array_keys($active_ports_array); + + $i = 0; + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 + where + table index = bridge port (dot1dBasePort) and + table value = ifIndex */ + // -------------------------------------------- + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('get bridgePortIfIndexes: '.cacti_sizeof($bridgePortIfIndexes)); + + /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ + // -------------------------------------------- + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + mactrack_debug('get port_status: '.cacti_sizeof($port_status)); + + /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = bridge port */ + // -------------------------------------------- + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + mactrack_debug('get port_numbers: '.cacti_sizeof($port_numbers)); + + // get VLAN information + // -------------------------------------------- + + $vlan_ids = []; + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); + foreach ($vlan_names as $key => $value) { + $vlan_ids[$key] = $key; + } + + mactrack_debug('get vlan_ids: '.cacti_sizeof($vlan_ids)); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); + $port_vlan_data = []; + + foreach ($xdata as $key => $value) { + $keys = explode('.', $key); + $port_vlan_data[$value] = $keys[0]; + } + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + foreach ($port_numbers as $key => $port_number) { + // key = MAC Address from dot1dTpFdbTable + // value = bridge port + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports)) { + if (isset($port_status[$key]) && '3' == $port_status[$key]) { + $port_key_array[$i]['key'] = substr($key, 1); + $port_key_array[$i]['port_number'] = $port_number; + ++$i; + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + + $i = 0; + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (0 != cacti_sizeof($bridgePortIfIndexes)) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + mactrack_debug('Searching Bridge Port: '.$port_key['port_number'].', Bridge: '.$bridgePortIfIndexes[$port_key['port_number']]); + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + } else { + $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); + } + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if (($brPortIfType >= 6) + && ($brPortIfType <= 9) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); + $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; + $new_port_key_array[$i]['port_name'] = mactrack_arr_key($ifInterfaces, $port_key['port_number']); + $new_port_key_array[$i]['mac_address'] = oscx_mac($port_key['key']); + $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $brPortIfIndex); + $new_port_key_array[$i]['vlan_name'] = isset($brPortIfIndex) ? mactrack_arr_key($vlan_names, $port_vlan_data[$brPortIfIndex]) : ''; + + ++$i; + } + } + } + mactrack_debug('Port number information collected: '.cacti_sizeof($new_port_key_array)); + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } - /* get_aruba_oscx_arp_table - This function reads a devices CTAlias table for a site and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_aruba_oscx_arp_table($site, &$device) { - global $debug, $scan_date; - - mactrack_debug('FUNCTION: get_aruba_oscx_arp_table started'); - -/* -joining mac = port with ip = mac -1.3.6.1.2.1.17.7.1.2.2.1.2 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.2.209.50.110.192 = INTEGER: 28 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.9.15.9.0.18 = INTEGER: 28 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.11.134.101.90.128 = INTEGER: 28 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.12.41.187.210.4 = INTEGER: 28 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.16.116.104.90.49 = INTEGER: 28 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.17.50.44.9.137 = INTEGER: 28 -.1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.22.108.186.185.185 = INTEGER: 28 - -.1.3.6.1.2.1.4.35.1.4 -.1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.95 = STRING: 4c:ae:a3:64:5a:cb -.1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.96 = STRING: 4c:ae:a3:64:50:ab -.1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.97 = STRING: 40:b9:3c:4b:9c:de -.1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.98 = STRING: ec:9b:8b:78:9b:d7 -*/ - - $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 6); - $port_vlan_data = array(); - - foreach ($xdata as $key=>$value) { - $mac_port[oscx_mac($key)] = $value; - } - - $xdata = xform_indexed_data('.1.3.6.1.2.1.4.35.1.4', $device, 4); - foreach ($xdata as $key=>$value) { - $ip_mac[$key] = strtr($value, ' ', ':'); - } - - $result = array(); - - foreach($ip_mac as $key=>$value) { - if (isset($mac_port[$value])) { - $result[$key]['port'] = $mac_port[$value]; - $result[$key]['mac'] = $value; - } - } - - mactrack_debug('arp assembly complete.'); - - // output details to database - if (cacti_sizeof($result)) { - $sql = array(); - - foreach($result as $key=>$value) { - $sql[] = '(' . - $device['site_id'] . ', ' . - $device['device_id'] . ', ' . - db_qstr($device['hostname']) . ', ' . - db_qstr($device['device_name']) . ', ' . - db_qstr($value['port']) . ', ' . - db_qstr($value['mac']) . ', ' . - db_qstr($key) . ', ' . - db_qstr($scan_date) . ')'; - } - - if (cacti_sizeof($sql)) { - db_execute('REPLACE INTO mac_track_ips +function get_aruba_oscx_arp_table($site, &$device) +{ + global $debug, $scan_date; + + mactrack_debug('FUNCTION: get_aruba_oscx_arp_table started'); + + /* + joining mac = port with ip = mac + 1.3.6.1.2.1.17.7.1.2.2.1.2 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.2.209.50.110.192 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.9.15.9.0.18 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.11.134.101.90.128 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.12.41.187.210.4 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.16.116.104.90.49 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.17.50.44.9.137 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.22.108.186.185.185 = INTEGER: 28 + + .1.3.6.1.2.1.4.35.1.4 + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.95 = STRING: 4c:ae:a3:64:5a:cb + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.96 = STRING: 4c:ae:a3:64:50:ab + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.97 = STRING: 40:b9:3c:4b:9c:de + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.98 = STRING: ec:9b:8b:78:9b:d7 + */ + + $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 6); + $port_vlan_data = []; + + foreach ($xdata as $key => $value) { + $mac_port[oscx_mac($key)] = $value; + } + + $xdata = xform_indexed_data('.1.3.6.1.2.1.4.35.1.4', $device, 4); + foreach ($xdata as $key => $value) { + $ip_mac[$key] = strtr($value, ' ', ':'); + } + + $result = []; + + foreach ($ip_mac as $key => $value) { + if (isset($mac_port[$value])) { + $result[$key]['port'] = $mac_port[$value]; + $result[$key]['mac'] = $value; + } + } + + mactrack_debug('arp assembly complete.'); + + // output details to database + if (cacti_sizeof($result)) { + $sql = []; + + foreach ($result as $key => $value) { + $sql[] = '(' + .$device['site_id'].', ' + .$device['device_id'].', ' + .db_qstr($device['hostname']).', ' + .db_qstr($device['device_name']).', ' + .db_qstr($value['port']).', ' + .db_qstr($value['mac']).', ' + .db_qstr($key).', ' + .db_qstr($scan_date).')'; + } + + if (cacti_sizeof($sql)) { + db_execute('REPLACE INTO mac_track_ips (site_id, device_id, hostname, device_name, port_number, mac_address,ip_address,scan_date) - VALUES ' . implode(', ', $sql)); - } - } + VALUES '.implode(', ', $sql)); + } + } - // save ip information for the device - $device['ips_total'] = cacti_sizeof($result); + // save ip information for the device + $device['ips_total'] = cacti_sizeof($result); - db_execute_prepared('UPDATE mac_track_devices + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - array($device['ips_total'], $device['device_id'])); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete. IP=' . cacti_sizeof($result) . '.'); + mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete. IP='.cacti_sizeof($result).'.'); } - diff --git a/lib/mactrack_cabletron.php b/lib/mactrack_cabletron.php index b8536404..6555d3a3 100644 --- a/lib/mactrack_cabletron.php +++ b/lib/mactrack_cabletron.php @@ -1,4 +1,5 @@ = 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { - if ($port_info == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - } - - /* now obtain securefast port information */ - $sfps_A_ports = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.6', $device, 3); - $sfps_A_mac_addresses = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.8', $device, 3, true); - - $sfps_A_keys = array_keys($sfps_A_ports); - $sfps_A_size = cacti_sizeof($sfps_A_ports); - - $j = 0; - $i = 0; - while($j < $sfps_A_size) { - $port_number = $sfps_A_ports[$sfps_A_keys[$j]]; - $mac_address = $sfps_A_mac_addresses[$sfps_A_keys[$j]]; - - if (($port_number >= $lowPort) && ($port_number <= $highPort)) { - if (!in_array($port_number, $ignore_ports)) { - $temp_port_A_array[$i]['port_number'] = $port_number; - $temp_port_A_array[$i]['mac_address'] = xform_mac_address($mac_address); - $i++; - } - } - $j++; - } - - $j = 0; - $port_array = array(); - for ($i=0;$i < cacti_sizeof($temp_port_A_array);$i++) { - $port_array[$temp_port_A_array[$i]['port_number']]['vlan_id'] = 'N/A'; - $port_array[$temp_port_A_array[$i]['port_number']]['vlan_name'] = 'N/A'; - $port_array[$temp_port_A_array[$i]['port_number']]['port_name'] = 'N/A'; - $port_array[$temp_port_A_array[$i]['port_number']]['port_number'] = $temp_port_A_array[$i]['port_number']; - $port_array[$temp_port_A_array[$i]['port_number']]['mac_address'] = $temp_port_A_array[$i]['mac_address']; - } - - if ($store_to_db) { - if (cacti_sizeof($port_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $port_array; - } - +function get_base_sfps_ports($site, &$device, &$ifInterfaces, $snmp_readstring, $store_to_db, $lowPort, $highPort) +{ + global $debug, $scan_date; + + // initialize variables + $port_number = 0; + $ports_active = 0; + $ports_total = 0; + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + // get the ignore ports list + $ignore_ports = port_list_to_array($device['ignorePorts']); + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + } + + // now obtain securefast port information + $sfps_A_ports = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.6', $device, 3); + $sfps_A_mac_addresses = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.8', $device, 3, true); + + $sfps_A_keys = array_keys($sfps_A_ports); + $sfps_A_size = cacti_sizeof($sfps_A_ports); + + $j = 0; + $i = 0; + while ($j < $sfps_A_size) { + $port_number = $sfps_A_ports[$sfps_A_keys[$j]]; + $mac_address = $sfps_A_mac_addresses[$sfps_A_keys[$j]]; + + if (($port_number >= $lowPort) && ($port_number <= $highPort)) { + if (!in_array($port_number, $ignore_ports)) { + $temp_port_A_array[$i]['port_number'] = $port_number; + $temp_port_A_array[$i]['mac_address'] = xform_mac_address($mac_address); + ++$i; + } + } + ++$j; + } + + $j = 0; + $port_array = []; + for ($i = 0; $i < cacti_sizeof($temp_port_A_array); ++$i) { + $port_array[$temp_port_A_array[$i]['port_number']]['vlan_id'] = 'N/A'; + $port_array[$temp_port_A_array[$i]['port_number']]['vlan_name'] = 'N/A'; + $port_array[$temp_port_A_array[$i]['port_number']]['port_name'] = 'N/A'; + $port_array[$temp_port_A_array[$i]['port_number']]['port_number'] = $temp_port_A_array[$i]['port_number']; + $port_array[$temp_port_A_array[$i]['port_number']]['mac_address'] = $temp_port_A_array[$i]['mac_address']; + } + + if ($store_to_db) { + if (cacti_sizeof($port_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $port_array; + } } /* get_repeater_snmp_readstring - Cabletron SEHI's are quite odd. They have potentially - 5 distinct snmp_readstrings for each of 5 agent structures. If the read_string - for the port information is different than sysObjectID, then let's find it and - set it. + 5 distinct snmp_readstrings for each of 5 agent structures. If the read_string + for the port information is different than sysObjectID, then let's find it and + set it. */ -function get_repeater_snmp_readstring(&$device) { - $active_ports = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($active_ports != '') { - mactrack_debug('Repeater readstring is: ' . $device['snmp_readstring']); - return $device['snmp_readstring']; - } else { - /* loop through the default and then other common for the correct answer */ - $read_strings = explode(':', $device['snmp_readstrings']); - - if (cacti_sizeof($read_strings)) { - foreach($read_strings as $snmp_readstring) { - $active_ports = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($active_ports != '') { - mactrack_debug('Repeater readstring is: ' . $snmp_readstring); - return $snmp_readstring; - } - } - } - } - - return ''; +function get_repeater_snmp_readstring(&$device) +{ + $active_ports = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $active_ports) { + mactrack_debug('Repeater readstring is: '.$device['snmp_readstring']); + + return $device['snmp_readstring']; + } + // loop through the default and then other common for the correct answer + $read_strings = explode(':', $device['snmp_readstrings']); + + if (cacti_sizeof($read_strings)) { + foreach ($read_strings as $snmp_readstring) { + $active_ports = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $active_ports) { + mactrack_debug('Repeater readstring is: '.$snmp_readstring); + + return $snmp_readstring; + } + } + } + + return ''; } -function get_repeater_rev4_ports($site, &$device, $lowPort, $highPort) { - global $debug, $scan_date; - - $snmp_readstring = get_repeater_snmp_readstring($device); - - if ($snmp_readstring != '') { - $ports_active = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.5.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']) - 1; - - $ports_total = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']) - 1; - - /* get the ignore ports list */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', ACTIVE PORTS: ' . $ports_active); - - $device['vlans_total'] = 0; - $device['ports_total'] = $ports_total; - - if ($ports_active >= 0) { - $device['ports_active'] = $ports_active; - } else { - $device['ports_active'] = 0; - } - - if ($device['snmp_version'] == 2) { - $snmp_version = '2c'; - } else { - $snmp_version = $device['snmp_version']; - } - - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_number = 0; - $nextOID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.2'; - $to = ceil($device['snmp_timeout']/1000); - - $i = 0; - $previous_port = 0; - while (1) { - $exec_string = trim(read_config_option('path_snmpgetnext') . - ' -c ' . $snmp_readstring . - ' -OnUQ -v ' . $snmp_version . - ' -r ' . $device['snmp_retries'] . - ' -t ' . $to . ' ' . - $device['hostname'] . ':' . $device['snmp_port'] . ' ' . - $nextOID); - - exec($exec_string, $return_array, $return_code); - - list($nextOID, $port_number) = explode('=', $return_array[$i]); - - if ($port_number < $previous_port) { - break; - } - - if (($port_number <= $highPort) && ($port_number >= $lowPort)) { - if (!in_array($port_number, $ignore_ports)) { - /* set defaults for devices in case they don't have/support vlans */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - $new_port_key_array[$i]['key'] = trim(substr($nextOID,36)); - $new_port_key_array[$i]['port_number'] = trim(strtr($port_number,' ','')); - } - - $previous_port = trim(strtr($port_number,' ','')); - } else { - break; - } - - - mactrack_debug('CMD: ' . $exec_string . ', PORT: ' . $port_number); - $i++; - $port_number = ''; - } - - if (cacti_sizeof($new_port_key_array) > 0) { - /* map mac address */ - $i=0; - foreach ($new_port_key_array as $port_key) { - $OID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.1.' . $port_key['key']; - - $mac_address = @cacti_snmp_get($device['hostname'], $snmp_readstring, - $OID, $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - $new_port_key_array[$i]['mac_address'] = xform_mac_address($mac_address); - - mactrack_debug('OID: ' . $OID . ', MAC ADDRESS: ' . $new_port_key_array[$i]['mac_address']); - $i++; - } - - $device['last_runmessage'] = 'Data collection completed ok'; - } else { - mactrack_debug('INFO: The following device has no active ports: ' . $site . '/' . $device['hostname']); - - $device['last_runmessage'] = 'Data collection completed ok'; - } - } else { - mactrack_debug('ERROR: Could not determine snmp_readstring for host: ' . $site . '/' . $device['hostname']); - - $device['snmp_status'] = HOST_ERROR; - $device['last_runmessage'] = 'ERROR: Could not determine snmp_readstring for host.'; - } - - $device['ports_active'] = $ports_active; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - - return $device; +function get_repeater_rev4_ports($site, &$device, $lowPort, $highPort) +{ + global $debug, $scan_date; + + $snmp_readstring = get_repeater_snmp_readstring($device); + + if ('' != $snmp_readstring) { + $ports_active = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.5.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ) - 1; + + $ports_total = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ) - 1; + + // get the ignore ports list + $ignore_ports = port_list_to_array($device['ignorePorts']); + + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', ACTIVE PORTS: '.$ports_active); + + $device['vlans_total'] = 0; + $device['ports_total'] = $ports_total; + + if ($ports_active >= 0) { + $device['ports_active'] = $ports_active; + } else { + $device['ports_active'] = 0; + } + + if (2 == $device['snmp_version']) { + $snmp_version = '2c'; + } else { + $snmp_version = $device['snmp_version']; + } + + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_number = 0; + $nextOID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.2'; + $to = ceil($device['snmp_timeout'] / 1000); + + $i = 0; + $previous_port = 0; + while (1) { + $exec_string = trim(read_config_option('path_snmpgetnext') + .' -c '.$snmp_readstring + .' -OnUQ -v '.$snmp_version + .' -r '.$device['snmp_retries'] + .' -t '.$to.' ' + .$device['hostname'].':'.$device['snmp_port'].' ' + .$nextOID); + + exec($exec_string, $return_array, $return_code); + + list($nextOID, $port_number) = explode('=', $return_array[$i]); + + if ($port_number < $previous_port) { + break; + } + + if (($port_number <= $highPort) && ($port_number >= $lowPort)) { + if (!in_array($port_number, $ignore_ports)) { + // set defaults for devices in case they don't have/support vlans + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + $new_port_key_array[$i]['key'] = trim(substr($nextOID, 36)); + $new_port_key_array[$i]['port_number'] = trim(strtr($port_number, ' ', '')); + } + + $previous_port = trim(strtr($port_number, ' ', '')); + } else { + break; + } + + mactrack_debug('CMD: '.$exec_string.', PORT: '.$port_number); + ++$i; + $port_number = ''; + } + + if (cacti_sizeof($new_port_key_array) > 0) { + // map mac address + $i = 0; + foreach ($new_port_key_array as $port_key) { + $OID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.1.'.$port_key['key']; + + $mac_address = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + $OID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $new_port_key_array[$i]['mac_address'] = xform_mac_address($mac_address); + + mactrack_debug('OID: '.$OID.', MAC ADDRESS: '.$new_port_key_array[$i]['mac_address']); + ++$i; + } + + $device['last_runmessage'] = 'Data collection completed ok'; + } else { + mactrack_debug('INFO: The following device has no active ports: '.$site.'/'.$device['hostname']); + + $device['last_runmessage'] = 'Data collection completed ok'; + } + } else { + mactrack_debug('ERROR: Could not determine snmp_readstring for host: '.$site.'/'.$device['hostname']); + + $device['snmp_status'] = HOST_ERROR; + $device['last_runmessage'] = 'ERROR: Could not determine snmp_readstring for host.'; + } + + $device['ports_active'] = $ports_active; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + + return $device; } - diff --git a/lib/mactrack_cisco.php b/lib/mactrack_cisco.php index d324fad4..f8829015 100644 --- a/lib/mactrack_cisco.php +++ b/lib/mactrack_cisco.php @@ -1,4 +1,5 @@ $vlanStatus) { - $vlanName = $vlan_names[$vlan_number]; - - if ($vlanStatus == 1) { /* vlan is operatinal */ - switch ($vlan_number) { - case '1002': - case '1003': - case '1004': - case '1005': - $active_vlan_ports = 0; - break; - default: - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'] . '@' . $vlan_number; - $active_vlan_ports = cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - SNMP_POLLER, $device['snmp_engine_id']); - } else { - $active_vlan_ports = cacti_snmp_get($device['hostname'], '', - '.1.3.6.1.2.1.17.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], 'vlan-' . $vlan_number, - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - SNMP_POLLER, $device['snmp_engine_id']); - } - - if ((!is_numeric($active_vlan_ports)) || ($active_vlan_ports) < 0) { - $active_vlan_ports = 0; - } - - mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is complete. ACTIVE PORTS: ' . $active_vlan_ports); - - if ($active_vlan_ports > 0) { /* does the vlan have active ports on it */ - $active_vlans[$j]['vlan_id'] = $vlan_number; - $active_vlans[$j]['vlan_name'] = $vlanName; - $active_vlans[$j]['active_ports'] = $active_vlan_ports; - - // Commented out because why wuuld you increment an array!! - // $active_vlans++; - - $j++; - } - } - } - - $i++; - } - } - - if (cacti_sizeof($active_vlans)) { - $i = 0; - /* get the port status information */ - foreach ($active_vlans as $active_vlan) { - /* ignore empty vlans */ - if ($active_vlan['active_ports'] <= $device['ports_trunk']) { - $active_vlans[$i]['port_results'] = array(); - $i++; - continue; - } - - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'] . '@' . $active_vlan['vlan_id']; - } else { - $snmp_readstring = 'cisco@' . $active_vlan['vlan_id']; - } - - mactrack_debug('Processing has begun for VLAN: ' . $active_vlan['vlan_id']); - - if ($highPort == 0) { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); - } else { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); - } - - /* get bridge port mappings */ - /* get bridge port to ifIndex mappings */ - mactrack_debug('Bridge port information about to be collected.'); - mactrack_debug('VLAN_ID: ' . $active_vlans[$i]['vlan_id'] . ', VLAN_NAME: ' . $active_vlans[$i]['vlan_name'] . ', ACTIVE PORTS: ' . cacti_sizeof($active_vlans[$i]['port_results'])); - - if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { - $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('Bridge port information collection complete.'); - } - - $i++; - } - - mactrack_debug('Final cross check\'s now being performed.'); - $i = 0; - $j = 0; - $port_array = array(); - - if (cacti_sizeof($active_vlans)) { - foreach ($active_vlans as $active_vlan) { - if (cacti_sizeof($active_vlan['port_results'])) { - foreach ($active_vlan['port_results'] as $port_result) { - $ifIndex = isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''; - $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); - $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); - $portName = (isset($portNames[$ifName]) ? $portNames[$ifName] : ''); - $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); - $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); - - if ($vvlans) { - $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); - } else { - $vVlanID = -1; - } - - /* only output legitimate end user ports */ - if (($ifType == 6) && ($portTrunk == 2)) { - if (($portTrunkStatus == '2')||($portTrunkStatus == '4')||($portTrunkStatus =='')) { - $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; - $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; - $port_array[$i]['port_number'] = $ifInterfaces[$ifIndex]['ifName']; - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - $i++; - - mactrack_debug('VLAN: ' . $active_vlan['vlan_id'] . ', ' . - 'NAME: ' . $active_vlan['vlan_name'] . ', ' . - 'PORT: ' . $ifInterfaces[$ifIndex]['ifName'] . ', ' . - 'NAME: ' . $portName . ', ' . - 'MAC: ' . $port_result['mac_address']); - } - } - } - } - - $j++; - } - } - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_catalyst_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // Variables to determine VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); + + $device['vlans_total'] = cacti_sizeof($vlan_ids) - 3; + mactrack_debug('There are '.(cacti_sizeof($vlan_ids) - 3).' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + + // get the Voice VLAN information if it exists + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); + if (cacti_sizeof($portVoiceVLANs)) { + $vvlans = true; + } else { + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); + if (cacti_sizeof($portVoiceVLANs)) { + $vvlans = true; + } else { + $vvlans = false; + } + } + mactrack_debug('Cisco Voice VLAN collection complete'); + if ($vvlans) { + mactrack_debug('Voice VLANs exist on this device'); + } else { + mactrack_debug('Voice VLANs do not exist on this device'); + } + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['trunkPortState'] = isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''; + if ($vvlans) { + $ifInterfaces[$ifIndex]['vVlanID'] = isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''; + } + + if (6 == $ifInterfaces[$ifIndex]['ifType']) { + ++$device['ports_total']; + } + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // get the portNames + $portNames = xform_cisco_workgroup_port_data('.1.3.6.1.4.1.9.5.1.4.1.1.4', $device); + mactrack_debug('portNames data collected.'); + + // get trunking status + $portTrunking = xform_cisco_workgroup_port_data('.1.3.6.1.4.1.9.5.1.9.3.1.8', $device); + mactrack_debug('portTrunking data collected.'); + + // calculate the number of end user ports + if (cacti_sizeof($portTrunking)) { + foreach ($portTrunking as $portTrunk) { + if (1 == $portTrunk) { + ++$device['ports_trunk']; + } + } + } + + // build VLAN array from results + $i = 0; + $j = 0; + $active_vlans = []; + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_number => $vlanStatus) { + $vlanName = $vlan_names[$vlan_number]; + + if (1 == $vlanStatus) { // vlan is operatinal + switch ($vlan_number) { + case '1002': + case '1003': + case '1004': + case '1005': + $active_vlan_ports = 0; + + break; + + default: + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'].'@'.$vlan_number; + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } else { + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + '', + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + 'vlan-'.$vlan_number, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } + + if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { + $active_vlan_ports = 0; + } + + mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is complete. ACTIVE PORTS: '.$active_vlan_ports); + + if ($active_vlan_ports > 0) { // does the vlan have active ports on it + $active_vlans[$j]['vlan_id'] = $vlan_number; + $active_vlans[$j]['vlan_name'] = $vlanName; + $active_vlans[$j]['active_ports'] = $active_vlan_ports; + + // Commented out because why wuuld you increment an array!! + // $active_vlans++; + + ++$j; + } + } + } + + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + $i = 0; + // get the port status information + foreach ($active_vlans as $active_vlan) { + // ignore empty vlans + if ($active_vlan['active_ports'] <= $device['ports_trunk']) { + $active_vlans[$i]['port_results'] = []; + ++$i; + + continue; + } + + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'].'@'.$active_vlan['vlan_id']; + } else { + $snmp_readstring = 'cisco@'.$active_vlan['vlan_id']; + } + + mactrack_debug('Processing has begun for VLAN: '.$active_vlan['vlan_id']); + + if (0 == $highPort) { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); + } else { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); + } + + // get bridge port mappings + // get bridge port to ifIndex mappings + mactrack_debug('Bridge port information about to be collected.'); + mactrack_debug('VLAN_ID: '.$active_vlans[$i]['vlan_id'].', VLAN_NAME: '.$active_vlans[$i]['vlan_name'].', ACTIVE PORTS: '.cacti_sizeof($active_vlans[$i]['port_results'])); + + if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { + $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('Bridge port information collection complete.'); + } + + ++$i; + } + + mactrack_debug('Final cross check\'s now being performed.'); + $i = 0; + $j = 0; + $port_array = []; + + if (cacti_sizeof($active_vlans)) { + foreach ($active_vlans as $active_vlan) { + if (cacti_sizeof($active_vlan['port_results'])) { + foreach ($active_vlan['port_results'] as $port_result) { + $ifIndex = isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''; + $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); + $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); + $portName = (isset($portNames[$ifName]) ? $portNames[$ifName] : ''); + $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); + $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); + + if ($vvlans) { + $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); + } else { + $vVlanID = -1; + } + + // only output legitimate end user ports + if ((6 == $ifType) && (2 == $portTrunk)) { + if (('2' == $portTrunkStatus) || ('4' == $portTrunkStatus) || ('' == $portTrunkStatus)) { + $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; + $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; + $port_array[$i]['port_number'] = $ifInterfaces[$ifIndex]['ifName']; + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + ++$i; + + mactrack_debug('VLAN: '.$active_vlan['vlan_id'].', ' + .'NAME: '.$active_vlan['vlan_name'].', ' + .'PORT: '.$ifInterfaces[$ifIndex]['ifName'].', ' + .'NAME: '.$portName.', ' + .'MAC: '.$port_result['mac_address']); + } + } + } + } + + ++$j; + } + } + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_IOS_dot1dTpFdbEntry_ports - obtains port associations for Cisco Catalyst Switches. Catalyst - switches are unique in that they support a different snmp_readstring for - every VLAN interface on the switch. + obtains port associations for Cisco Catalyst Switches. Catalyst + switches are unique in that they support a different snmp_readstring for + every VLAN interface on the switch. */ -function get_IOS_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) { - global $debug, $scan_date; - - $ifIndexes = array(); - - /* get and store the interfaces table */ - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); - - /* initialize port counters */ - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - - /* Variables to determine VLAN information */ - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); - $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); - - $device['vlans_total'] = cacti_sizeof($vlan_ids) - 4; - mactrack_debug('There are ' . (cacti_sizeof($vlan_ids)-4) . ' VLANS.'); - - if (cacti_sizeof($vlan_names) == 0) { - cacti_log('No VLANs Name found: ' . $device['device_name']); - return $device; - } - - if (cacti_sizeof($vlan_trunkstatus) == 0) { - cacti_log('No VLANs Trunk Status found: ' . $device['device_name']); - return $device; - } - - /* get the Voice VLAN information if it exists */ - $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); - if (cacti_sizeof($portVoiceVLANs) > 0) { - $vvlans = true; - } else { - $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); - if (cacti_sizeof($portVoiceVLANs) > 0) { - $vvlans = true; - } else { - $vvlans = false; - } - } - - mactrack_debug('Cisco Voice VLAN collection complete'); - if ($vvlans) { - mactrack_debug('Voice VLANs exist on this device'); - } else { - mactrack_debug('Voice VLANs do not exist on this device'); - } - - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['trunkPortState'] = (isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''); - if ($vvlans) { - $ifInterfaces[$ifIndex]['vVlanID'] = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); - } - - if ($ifInterfaces[$ifIndex]['ifType'] == 6) { - $device['ports_total']++; - } - - if ($ifInterfaces[$ifIndex]['trunkPortState'] == '1') { - $device['ports_trunk']++; - } - } - } - mactrack_debug('ifInterfaces assembly complete.'); - - /* build VLAN array from results */ - $i = 0; - $j = 0; - $active_vlans = array(); - - $skip_vlans = array(); - $sql_result = db_fetch_cell_prepared('SELECT skip_vlans +function get_IOS_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; + + $ifIndexes = []; + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // Variables to determine VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); + + $device['vlans_total'] = cacti_sizeof($vlan_ids) - 4; + mactrack_debug('There are '.(cacti_sizeof($vlan_ids) - 4).' VLANS.'); + + if (0 == cacti_sizeof($vlan_names)) { + cacti_log('No VLANs Name found: '.$device['device_name']); + + return $device; + } + + if (0 == cacti_sizeof($vlan_trunkstatus)) { + cacti_log('No VLANs Trunk Status found: '.$device['device_name']); + + return $device; + } + + // get the Voice VLAN information if it exists + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); + if (cacti_sizeof($portVoiceVLANs) > 0) { + $vvlans = true; + } else { + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); + if (cacti_sizeof($portVoiceVLANs) > 0) { + $vvlans = true; + } else { + $vvlans = false; + } + } + + mactrack_debug('Cisco Voice VLAN collection complete'); + if ($vvlans) { + mactrack_debug('Voice VLANs exist on this device'); + } else { + mactrack_debug('Voice VLANs do not exist on this device'); + } + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['trunkPortState'] = (isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''); + if ($vvlans) { + $ifInterfaces[$ifIndex]['vVlanID'] = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); + } + + if (6 == $ifInterfaces[$ifIndex]['ifType']) { + ++$device['ports_total']; + } + + if ('1' == $ifInterfaces[$ifIndex]['trunkPortState']) { + ++$device['ports_trunk']; + } + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // build VLAN array from results + $i = 0; + $j = 0; + $active_vlans = []; + + $skip_vlans = []; + $sql_result = db_fetch_cell_prepared( + 'SELECT skip_vlans FROM mac_track_sites WHERE site_name = ?', - array($site)); + [$site] + ); - if ($sql_result != '') { - $skip_vlans = explode(',', $sql_result); - } + if ('' != $sql_result) { + $skip_vlans = explode(',', $sql_result); + } - $scan_vlans = array(); - $sql_result = db_fetch_cell_prepared('SELECT scan_vlans + $scan_vlans = []; + $sql_result = db_fetch_cell_prepared( + 'SELECT scan_vlans FROM mac_track_sites WHERE site_name = ?', - array($site)); - - if ($sql_result != '') { - $scan_vlans = explode(',', $sql_result); - $scan_vlans = array_merge(array_diff($scan_vlans, $skip_vlans)); - } - - $scan_trunk_port = array(); - if ($device['scan_trunk_port'] != '') { - $scan_trunk_port = explode(',', $device['scan_trunk_port']); - } - - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_number => $vlanStatus) { - $vlanName = mactrack_arr_key($vlan_names, $vlan_number); - - if ($vlanName == '') { - cacti_log('Empty VLAN Name: ' . $device['device_name']); - continue; - } - - // VLAN-ID to skip - if (in_array($vlan_number, $skip_vlans)) { - mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is skipped. *** ALWAYS FORCED ***'); - continue; - } - - // VLAN-ID to scan - if (count($scan_vlans) > 0) { - if (!in_array($vlan_number, $scan_vlans)) { - mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is skipped. *** NOT CONFIGURED ***'); - continue; - } - } - - if ($vlanStatus == 1) { /* vlan is operatinal */ - switch ($vlan_number) { - case '1002': - case '1003': - case '1004': - case '1005': - $active_vlan_ports = 0; - break; - default: - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'] . '@' . $vlan_number; - $active_vlan_ports = cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - SNMP_POLLER, $device['snmp_engine_id']); - } else { - $active_vlan_ports = cacti_snmp_get($device['hostname'], 'vlan-' . $vlan_number, - '.1.3.6.1.2.1.17.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], 'vlan-' . $vlan_number, - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - SNMP_POLLER, $device['snmp_engine_id']); - } - - if ((!is_numeric($active_vlan_ports)) || ($active_vlan_ports) < 0) { - $active_vlan_ports = 0; - } - - mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is complete. ACTIVE PORTS: ' . $active_vlan_ports); - - if ($active_vlan_ports > 0) { /* does the vlan have active ports on it */ - $active_vlans[$j]['vlan_id'] = $vlan_number; - $active_vlans[$j]['vlan_name'] = $vlanName; - $active_vlans[$j]['active_ports'] = $active_vlan_ports; - - $j++; - } - } - } - - $i++; - } - } - - if (cacti_sizeof($active_vlans)) { - $i = 0; - /* get the port status information */ - foreach ($active_vlans as $active_vlan) { - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'] . '@' . $active_vlan['vlan_id']; - } else { - $snmp_readstring = 'vlan-' . $active_vlan['vlan_id']; - } - - mactrack_debug('Processing has begun for VLAN: ' . $active_vlan['vlan_id']); - if ($highPort == 0) { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); - } else { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); - } - - /* get bridge port mappings */ - /* get bridge port to ifIndex mappings */ - mactrack_debug('Bridge port information about to be collected.'); - mactrack_debug('VLAN_ID: ' . $active_vlans[$i]['vlan_id'] . ', VLAN_NAME: ' . $active_vlans[$i]['vlan_name'] . ', ACTIVE PORTS: ' . cacti_sizeof($active_vlans[$i]['port_results'])); - - if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { - $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('Bridge port information collection complete.'); - } - $i++; - } - - $i = 0; - $j = 0; - $port_array = array(); - - mactrack_debug('Final cross check\'s now being performed.'); - if (cacti_sizeof($active_vlans)) { - foreach ($active_vlans as $active_vlan) { - if (cacti_sizeof($active_vlan['port_results'])) { - foreach ($active_vlan['port_results'] as $port_result) { - $ifIndex = (isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''); - $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); - $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); - $portNumber = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); - $portName = (isset($ifInterfaces[$ifIndex]['ifAlias']) ? $ifInterfaces[$ifIndex]['ifAlias'] : ''); - $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); - $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); - - if ($vvlans) { - $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); - } else { - $vVlanID = -1; - } - - /* only output legitimate end user ports */ - /* ifType: 6 = ethernetCsmacd - 53 = propVirtual - 161 = ieee8023adLag - */ - if ($ifType == 6 || $ifType == 53 || $ifType == 161) { - if (($portTrunkStatus == '2') || - //(empty($portTrunkStatus)) || - (in_array($portNumber, $scan_trunk_port)) || - (($vVlanID > 0) && ($vVlanID <= 1000))) { - $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; - $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; - $port_array[$i]['port_number'] = $portNumber; - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - $port_array[$i]['ifType'] = $ifType; - $port_array[$i]['portTrunkStatus'] = $portTrunkStatus; - $i++; - - mactrack_debug('HOST: ' . $device['hostname'] . ', ' . - 'VLAN: ' . $active_vlan['vlan_id'] . ', ' . - 'NAME: ' . $active_vlan['vlan_name'] . ', ' . - 'TRUNK: ' . $portTrunkStatus . ', ' . - 'TYPE: ' . $ifType . ', ' . - 'PORT: ' . $portNumber . ', ' . - 'NAME: ' . $portName . ', ' . - 'MAC: ' . $port_result['mac_address']); - } - } - } - } - - $j++; - } - } - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active end devices on this device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; - } - - return $device; + [$site] + ); + + if ('' != $sql_result) { + $scan_vlans = explode(',', $sql_result); + $scan_vlans = array_merge(array_diff($scan_vlans, $skip_vlans)); + } + + $scan_trunk_port = []; + if ('' != $device['scan_trunk_port']) { + $scan_trunk_port = explode(',', $device['scan_trunk_port']); + } + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_number => $vlanStatus) { + $vlanName = mactrack_arr_key($vlan_names, $vlan_number); + + if ('' == $vlanName) { + cacti_log('Empty VLAN Name: '.$device['device_name']); + + continue; + } + + // VLAN-ID to skip + if (in_array($vlan_number, $skip_vlans)) { + mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is skipped. *** ALWAYS FORCED ***'); + + continue; + } + + // VLAN-ID to scan + if (count($scan_vlans) > 0) { + if (!in_array($vlan_number, $scan_vlans)) { + mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is skipped. *** NOT CONFIGURED ***'); + + continue; + } + } + + if (1 == $vlanStatus) { // vlan is operatinal + switch ($vlan_number) { + case '1002': + case '1003': + case '1004': + case '1005': + $active_vlan_ports = 0; + + break; + + default: + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'].'@'.$vlan_number; + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } else { + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + 'vlan-'.$vlan_number, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + 'vlan-'.$vlan_number, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } + + if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { + $active_vlan_ports = 0; + } + + mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is complete. ACTIVE PORTS: '.$active_vlan_ports); + + if ($active_vlan_ports > 0) { // does the vlan have active ports on it + $active_vlans[$j]['vlan_id'] = $vlan_number; + $active_vlans[$j]['vlan_name'] = $vlanName; + $active_vlans[$j]['active_ports'] = $active_vlan_ports; + + ++$j; + } + } + } + + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + $i = 0; + // get the port status information + foreach ($active_vlans as $active_vlan) { + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'].'@'.$active_vlan['vlan_id']; + } else { + $snmp_readstring = 'vlan-'.$active_vlan['vlan_id']; + } + + mactrack_debug('Processing has begun for VLAN: '.$active_vlan['vlan_id']); + if (0 == $highPort) { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); + } else { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); + } + + // get bridge port mappings + // get bridge port to ifIndex mappings + mactrack_debug('Bridge port information about to be collected.'); + mactrack_debug('VLAN_ID: '.$active_vlans[$i]['vlan_id'].', VLAN_NAME: '.$active_vlans[$i]['vlan_name'].', ACTIVE PORTS: '.cacti_sizeof($active_vlans[$i]['port_results'])); + + if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { + $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('Bridge port information collection complete.'); + } + ++$i; + } + + $i = 0; + $j = 0; + $port_array = []; + + mactrack_debug('Final cross check\'s now being performed.'); + if (cacti_sizeof($active_vlans)) { + foreach ($active_vlans as $active_vlan) { + if (cacti_sizeof($active_vlan['port_results'])) { + foreach ($active_vlan['port_results'] as $port_result) { + $ifIndex = (isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''); + $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); + $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); + $portNumber = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); + $portName = (isset($ifInterfaces[$ifIndex]['ifAlias']) ? $ifInterfaces[$ifIndex]['ifAlias'] : ''); + $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); + $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); + + if ($vvlans) { + $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); + } else { + $vVlanID = -1; + } + + // only output legitimate end user ports + /* ifType: 6 = ethernetCsmacd + 53 = propVirtual + 161 = ieee8023adLag + */ + if (6 == $ifType || 53 == $ifType || 161 == $ifType) { + if (('2' == $portTrunkStatus) + // (empty($portTrunkStatus)) || + || in_array($portNumber, $scan_trunk_port) + || (($vVlanID > 0) && ($vVlanID <= 1000))) { + $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; + $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; + $port_array[$i]['port_number'] = $portNumber; + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + $port_array[$i]['ifType'] = $ifType; + $port_array[$i]['portTrunkStatus'] = $portTrunkStatus; + ++$i; + + mactrack_debug('HOST: '.$device['hostname'].', ' + .'VLAN: '.$active_vlan['vlan_id'].', ' + .'NAME: '.$active_vlan['vlan_name'].', ' + .'TRUNK: '.$portTrunkStatus.', ' + .'TYPE: '.$ifType.', ' + .'PORT: '.$portNumber.', ' + .'NAME: '.$portName.', ' + .'MAC: '.$port_result['mac_address']); + } + } + } + } + + ++$j; + } + } + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active end devices on this device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; + } + + return $device; } /* get_cisco_dhcpsnooping_table - This function reads a devices DHCP Snooping table for a site and stores @@ -561,274 +624,297 @@ function get_IOS_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort fully implemented we match MACs from dot1dTpFdbEntry so some IPs won't get the MAC populated. Send an email to mii@external.cisco.com with the word 'help' in the subject to get MIBs supported per IOS Image. */ -function get_cisco_dhcpsnooping_table($site, &$device) { - global $debug, $scan_date; - - /* get the cdsBindingInterface Index for the device */ - $cdsBindingInterface = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.5', $device); - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); - $cdsBindingsIpAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.4', $device); - $cdsBindingEntries = array(); - $dot1dTpFdbEntries = array(); - - /* build VLAN array from results */ - $i = 0; - $j = 0; - $active_vlans = array(); - - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_number => $vlanStatus) { - $vlanName = $vlan_names[$vlan_number]; - - if ($vlanStatus == 1) { /* vlan is operatinal */ - switch ($vlan_number) { - case '1002': - case '1003': - case '1004': - case '1005': - $active_vlan_ports = 0; - break; - default: - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'] . '@' . $vlan_number; - $active_vlan_ports = cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - SNMP_POLLER, $device['snmp_engine_id']); - } else { - $active_vlan_ports = cacti_snmp_get($device['hostname'], 'vlan-' . $vlan_number, - '.1.3.6.1.2.1.17.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], 'vlan-' . $vlan_number, - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - SNMP_POLLER, $device['snmp_engine_id']); - } - - if ((!is_numeric($active_vlan_ports)) || ($active_vlan_ports) < 0) { - $active_vlan_ports = 0; - } - - mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is complete. ACTIVE PORTS: ' . $active_vlan_ports); - - if ($active_vlan_ports > 0) { /* does the vlan have active ports on it */ - $active_vlans[$j]['vlan_id'] = $vlan_number; - $active_vlans[$j]['vlan_name'] = $vlanName; - $active_vlans[$j]['active_ports'] = $active_vlan_ports; - - // Commented out because why wuuld you increment an array!! - // $active_vlans++; - - $j++; - } - } - } - - $i++; - } - } - - if (cacti_sizeof($active_vlans)) { - $n = 1; - $dot1dTpFdbEntry = array(); - - /* get the port status information */ - foreach ($active_vlans as $active_vlan) { - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'] . '@' . $active_vlan['vlan_id']; - } else { - $snmp_readstring = 'vlan-' . $active_vlan['vlan_id']; - } - - mactrack_debug('Processing has begun for VLAN: ' . $active_vlan['vlan_id']); - - if (cacti_sizeof($active_vlans)) { - $dot1dTpFdbEntries[$n] = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring); - foreach ($dot1dTpFdbEntries[$n] as $key => $val) { - $dot1dTpFdbEntries[$n][$active_vlan['vlan_id']. '.' . $key] = $val; //ugly tweak to add vlan id to OID. - unset($dot1dTpFdbEntries[$n][$key]); - } - - mactrack_debug('dot1dTpFdbEntry data collection complete :' . cacti_sizeof($dot1dTpFdbEntries[$n])); - - if ($n > 0 ) { - $dot1dTpFdbEntry = array_merge($dot1dTpFdbEntry, $dot1dTpFdbEntries[$n]); - mactrack_debug('merge data collection complete : ' . cacti_sizeof($dot1dTpFdbEntry)); - } - } - $n++; - - mactrack_debug('dot1dTpFdbEntry vlan_id: ' . $active_vlan['vlan_id']); - } - - $keys = array_keys($cdsBindingInterface); - - $j = 0; - if (cacti_sizeof($cdsBindingInterface)) { - foreach ($cdsBindingInterface as $cdsBindingIndex) { - $cdsBindingEntries[$j]['cdsBindingIndex'] = $cdsBindingIndex; - $cdsBindingEntries[$j]['dot1dTpFdbEntry'] = isset($dot1dTpFdbEntry[$keys[$j]]) ? xform_mac_address($dot1dTpFdbEntry[$keys[$j]]):''; - $cdsBindingEntries[$j]['cdsBindingsIpAddress'] = isset($cdsBindingsIpAddress[$keys[$j]]) ? xform_net_address($cdsBindingsIpAddress[$keys[$j]]):''; - $j++; - } - - mactrack_debug('cdsBindingEntries Total entries: ' . cacti_sizeof($cdsBindingEntries)); - } - - mactrack_debug('cdsBindingEntries assembly complete.'); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active end devices on this device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; - } - - /* output details to database */ - if (cacti_sizeof($cdsBindingEntries)) { - foreach ($cdsBindingEntries as $cdsBindingEntry) { - if ($cdsBindingEntry['cdsBindingsIpAddress'] != '') { //It's acceptable to have IPs without a MAC (meaning that MAC is not present but DHCP entry is still present) here but not the other way around. - $insert_string = 'REPLACE INTO mac_track_ips +function get_cisco_dhcpsnooping_table($site, &$device) +{ + global $debug, $scan_date; + + // get the cdsBindingInterface Index for the device + $cdsBindingInterface = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.5', $device); + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); + $cdsBindingsIpAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.4', $device); + $cdsBindingEntries = []; + $dot1dTpFdbEntries = []; + + // build VLAN array from results + $i = 0; + $j = 0; + $active_vlans = []; + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_number => $vlanStatus) { + $vlanName = $vlan_names[$vlan_number]; + + if (1 == $vlanStatus) { // vlan is operatinal + switch ($vlan_number) { + case '1002': + case '1003': + case '1004': + case '1005': + $active_vlan_ports = 0; + + break; + + default: + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'].'@'.$vlan_number; + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } else { + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + 'vlan-'.$vlan_number, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + 'vlan-'.$vlan_number, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } + + if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { + $active_vlan_ports = 0; + } + + mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is complete. ACTIVE PORTS: '.$active_vlan_ports); + + if ($active_vlan_ports > 0) { // does the vlan have active ports on it + $active_vlans[$j]['vlan_id'] = $vlan_number; + $active_vlans[$j]['vlan_name'] = $vlanName; + $active_vlans[$j]['active_ports'] = $active_vlan_ports; + + // Commented out because why wuuld you increment an array!! + // $active_vlans++; + + ++$j; + } + } + } + + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + $n = 1; + $dot1dTpFdbEntry = []; + + // get the port status information + foreach ($active_vlans as $active_vlan) { + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'].'@'.$active_vlan['vlan_id']; + } else { + $snmp_readstring = 'vlan-'.$active_vlan['vlan_id']; + } + + mactrack_debug('Processing has begun for VLAN: '.$active_vlan['vlan_id']); + + if (cacti_sizeof($active_vlans)) { + $dot1dTpFdbEntries[$n] = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring); + foreach ($dot1dTpFdbEntries[$n] as $key => $val) { + $dot1dTpFdbEntries[$n][$active_vlan['vlan_id'].'.'.$key] = $val; // ugly tweak to add vlan id to OID. + unset($dot1dTpFdbEntries[$n][$key]); + } + + mactrack_debug('dot1dTpFdbEntry data collection complete :'.cacti_sizeof($dot1dTpFdbEntries[$n])); + + if ($n > 0) { + $dot1dTpFdbEntry = array_merge($dot1dTpFdbEntry, $dot1dTpFdbEntries[$n]); + mactrack_debug('merge data collection complete : '.cacti_sizeof($dot1dTpFdbEntry)); + } + } + ++$n; + + mactrack_debug('dot1dTpFdbEntry vlan_id: '.$active_vlan['vlan_id']); + } + + $keys = array_keys($cdsBindingInterface); + + $j = 0; + if (cacti_sizeof($cdsBindingInterface)) { + foreach ($cdsBindingInterface as $cdsBindingIndex) { + $cdsBindingEntries[$j]['cdsBindingIndex'] = $cdsBindingIndex; + $cdsBindingEntries[$j]['dot1dTpFdbEntry'] = isset($dot1dTpFdbEntry[$keys[$j]]) ? xform_mac_address($dot1dTpFdbEntry[$keys[$j]]) : ''; + $cdsBindingEntries[$j]['cdsBindingsIpAddress'] = isset($cdsBindingsIpAddress[$keys[$j]]) ? xform_net_address($cdsBindingsIpAddress[$keys[$j]]) : ''; + ++$j; + } + + mactrack_debug('cdsBindingEntries Total entries: '.cacti_sizeof($cdsBindingEntries)); + } + + mactrack_debug('cdsBindingEntries assembly complete.'); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active end devices on this device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; + } + + // output details to database + if (cacti_sizeof($cdsBindingEntries)) { + foreach ($cdsBindingEntries as $cdsBindingEntry) { + if ('' != $cdsBindingEntry['cdsBindingsIpAddress']) { // It's acceptable to have IPs without a MAC (meaning that MAC is not present but DHCP entry is still present) here but not the other way around. + $insert_string = 'REPLACE INTO mac_track_ips (site_id,device_id,hostname,device_name,port_number, mac_address,ip_address,scan_date) - VALUES (' . - $device['site_id'] . ',' . - $device['device_id'] . ',' . - db_qstr($device['hostname']) . ',' . - db_qstr($device['device_name']) . ',' . - db_qstr($cdsBindingEntry['cdsBindingIndex']) . ',' . - db_qstr($cdsBindingEntry['dot1dTpFdbEntry']) . ',' . - db_qstr($cdsBindingEntry['cdsBindingsIpAddress']) . ',' . - db_qstr($scan_date) . ')'; - - db_execute($insert_string); - } - } - } - - /* save ip information for the device */ - $device['ips_total'] = cacti_sizeof($cdsBindingEntries); - db_execute('UPDATE mac_track_devices SET ips_total =' . $device['ips_total'] . ' WHERE device_id=' . $device['device_id']); - - mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete'); + VALUES (' + .$device['site_id'].',' + .$device['device_id'].',' + .db_qstr($device['hostname']).',' + .db_qstr($device['device_name']).',' + .db_qstr($cdsBindingEntry['cdsBindingIndex']).',' + .db_qstr($cdsBindingEntry['dot1dTpFdbEntry']).',' + .db_qstr($cdsBindingEntry['cdsBindingsIpAddress']).',' + .db_qstr($scan_date).')'; + + db_execute($insert_string); + } + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($cdsBindingEntries); + db_execute('UPDATE mac_track_devices SET ips_total ='.$device['ips_total'].' WHERE device_id='.$device['device_id']); + + mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete'); } /* get_cisco_vrf_arp_table - This function reads a devices ARP table for a site with VRF/MPLS and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_cisco_vrf_arp_table($site, &$device) { - global $debug, $scan_date; +function get_cisco_vrf_arp_table($site, &$device) +{ + global $debug, $scan_date; - /* get the cdsBindingInterface Index for the device */ - $cdsBindingEntries = get_ios_vrf_arp_table('.1.3.6.1.2.1.3.1.1.2', $device); + // get the cdsBindingInterface Index for the device + $cdsBindingEntries = get_ios_vrf_arp_table('.1.3.6.1.2.1.3.1.1.2', $device); - - /* output details to database */ - if (cacti_sizeof($cdsBindingEntries)) { - foreach ($cdsBindingEntries as $cdsBindingEntry) { - $insert_string = 'INSERT INTO mac_track_arp + // output details to database + if (cacti_sizeof($cdsBindingEntries)) { + foreach ($cdsBindingEntries as $cdsBindingEntry) { + $insert_string = 'INSERT INTO mac_track_arp (site_id,ip_address,mac_address,scan_date) VALUES - (' . - $device['site_id'] . ',' . - db_qstr($cdsBindingEntry['key']) . ',' . - db_qstr($cdsBindingEntry['value']) . ',' . - db_qstr($scan_date) . ' + (' + .$device['site_id'].',' + .db_qstr($cdsBindingEntry['key']).',' + .db_qstr($cdsBindingEntry['value']).',' + .db_qstr($scan_date).' ) ON DUPLICATE KEY UPDATE - `ip_address` = ' . db_qstr($cdsBindingEntry['key']) . ', - `scan_date` = ' . db_qstr($scan_date) . ';'; - - db_execute($insert_string); + `ip_address` = '.db_qstr($cdsBindingEntry['key']).', + `scan_date` = '.db_qstr($scan_date).';'; - } - } + db_execute($insert_string); + } + } - /* save ip information for the device */ - $device['ips_total'] = cacti_sizeof($cdsBindingEntries); - db_execute('UPDATE mac_track_devices SET ips_total =' . $device['ips_total'] . ' WHERE device_id=' . $device['device_id']); + // save ip information for the device + $device['ips_total'] = cacti_sizeof($cdsBindingEntries); + db_execute('UPDATE mac_track_devices SET ips_total ='.$device['ips_total'].' WHERE device_id='.$device['device_id']); - mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete'); + mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete'); } /* get_cisco_dot1x_table - This function reads a devices Dot1x table for a site and stores the IP address, MAC address, Username, Domain and Status combinations in the mac_track_dot1x table. */ -function get_cisco_dot1x_table($site, &$device) { - global $debug, $scan_date; - - /* get the cafSessionAuthUserName from the device */ - $cafSessionAuthUserName = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.10', $device); - - if (cacti_sizeof($cafSessionAuthUserName)) { - mactrack_debug('cafSessionAuthUserName data collection complete: ' . cacti_sizeof($cafSessionAuthUserName)); - $cafSessionClientMacAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.2', $device, '', true); - mactrack_debug('cafSessionClientMacAddress data collection complete: ' . cacti_sizeof($cafSessionClientMacAddress)); - $cafSessionClientAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.4', $device, '', true); - mactrack_debug('cafSessionClientAddress data collection complete: ' . cacti_sizeof($cafSessionClientAddress)); - $cafSessionDomain = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.6', $device); - mactrack_debug('cafSessionDomain data collection complete: ' . cacti_sizeof($cafSessionDomain)); - $cafSessionStatus = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.5', $device); - mactrack_debug('cafSessionStatus data collection complete: ' . cacti_sizeof($cafSessionStatus)); - } else { - mactrack_debug(sprintf('The Device: %s does not support dot1x', $device['hostname'])); - return false; - } - - $ifIndex = array(); - $entries = array(); - $cafSessionAuthUserNames = array(); - $cafSessionAuthUserKey = array_keys($cafSessionAuthUserName); //Getting the keys to explode the first part which is the ifIndex - - mactrack_debug('cafSessionAuthUserName assembly complete: ' . cacti_sizeof($cafSessionAuthUserName)); - - $i = 0; - if (cacti_sizeof($cafSessionAuthUserName)) { - foreach ($cafSessionAuthUserName as $index => $value) { - $entries[$i]['Dot1xIndex'] = $index; - $entries[$i]['UserName'] = $value; - $entries[$i]['cafSessionClientMacAddress'] = isset($cafSessionClientMacAddress[$index]) ? xform_mac_address($cafSessionClientMacAddress[$index]):''; - $entries[$i]['cafSessionClientAddress'] = isset($cafSessionClientAddress[$index]) ? xform_net_address($cafSessionClientAddress[$index]):''; - $entries[$i]['cafSessionDomain'] = isset($cafSessionDomain[$index]) ? $cafSessionDomain[$index]:''; - $entries[$i]['cafSessionStatus'] = isset($cafSessionStatus[$index]) ? $cafSessionStatus[$index]:''; - - $parts = explode('.', trim($index, '.')); - $entries[$i]['port_number'] = $parts[0]; - - $i++; - } - } - mactrack_debug('cafSession assembly complete.'); - - /* output details to database */ - $sql = array(); - $prefix = 'REPLACE INTO mac_track_dot1x +function get_cisco_dot1x_table($site, &$device) +{ + global $debug, $scan_date; + + // get the cafSessionAuthUserName from the device + $cafSessionAuthUserName = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.10', $device); + + if (cacti_sizeof($cafSessionAuthUserName)) { + mactrack_debug('cafSessionAuthUserName data collection complete: '.cacti_sizeof($cafSessionAuthUserName)); + $cafSessionClientMacAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.2', $device, '', true); + mactrack_debug('cafSessionClientMacAddress data collection complete: '.cacti_sizeof($cafSessionClientMacAddress)); + $cafSessionClientAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.4', $device, '', true); + mactrack_debug('cafSessionClientAddress data collection complete: '.cacti_sizeof($cafSessionClientAddress)); + $cafSessionDomain = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.6', $device); + mactrack_debug('cafSessionDomain data collection complete: '.cacti_sizeof($cafSessionDomain)); + $cafSessionStatus = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.5', $device); + mactrack_debug('cafSessionStatus data collection complete: '.cacti_sizeof($cafSessionStatus)); + } else { + mactrack_debug(sprintf('The Device: %s does not support dot1x', $device['hostname'])); + + return false; + } + + $ifIndex = []; + $entries = []; + $cafSessionAuthUserNames = []; + $cafSessionAuthUserKey = array_keys($cafSessionAuthUserName); // Getting the keys to explode the first part which is the ifIndex + + mactrack_debug('cafSessionAuthUserName assembly complete: '.cacti_sizeof($cafSessionAuthUserName)); + + $i = 0; + if (cacti_sizeof($cafSessionAuthUserName)) { + foreach ($cafSessionAuthUserName as $index => $value) { + $entries[$i]['Dot1xIndex'] = $index; + $entries[$i]['UserName'] = $value; + $entries[$i]['cafSessionClientMacAddress'] = isset($cafSessionClientMacAddress[$index]) ? xform_mac_address($cafSessionClientMacAddress[$index]) : ''; + $entries[$i]['cafSessionClientAddress'] = isset($cafSessionClientAddress[$index]) ? xform_net_address($cafSessionClientAddress[$index]) : ''; + $entries[$i]['cafSessionDomain'] = isset($cafSessionDomain[$index]) ? $cafSessionDomain[$index] : ''; + $entries[$i]['cafSessionStatus'] = isset($cafSessionStatus[$index]) ? $cafSessionStatus[$index] : ''; + + $parts = explode('.', trim($index, '.')); + $entries[$i]['port_number'] = $parts[0]; + + ++$i; + } + } + mactrack_debug('cafSession assembly complete.'); + + // output details to database + $sql = []; + $prefix = 'REPLACE INTO mac_track_dot1x (site_id, device_id, hostname, device_name, username, mac_address, ip_address, domain, status, port_number, scan_date) VALUES '; - if (cacti_sizeof($entries)) { - foreach ($entries as $entry) { - if ($entry['UserName'] != '') { - $sql[] = '(' . $device['site_id'] . ',' . - $device['device_id'] . ',' . - db_qstr($device['hostname']) . ',' . - db_qstr($device['device_name']) . ',' . - db_qstr($entry['UserName']) . ',' . - db_qstr($entry['cafSessionClientMacAddress']) . ',' . - db_qstr($entry['cafSessionClientAddress']) . ',' . - db_qstr($entry['cafSessionDomain']) . ',' . - db_qstr($entry['cafSessionStatus']) . ',' . - db_qstr($entry['port_number']) . ',' . - db_qstr($scan_date) . ')'; - } - } - - if (cacti_sizeof($sql)) { - db_execute($prefix . implode(', ', $sql)); - } - } + if (cacti_sizeof($entries)) { + foreach ($entries as $entry) { + if ('' != $entry['UserName']) { + $sql[] = '('.$device['site_id'].',' + .$device['device_id'].',' + .db_qstr($device['hostname']).',' + .db_qstr($device['device_name']).',' + .db_qstr($entry['UserName']).',' + .db_qstr($entry['cafSessionClientMacAddress']).',' + .db_qstr($entry['cafSessionClientAddress']).',' + .db_qstr($entry['cafSessionDomain']).',' + .db_qstr($entry['cafSessionStatus']).',' + .db_qstr($entry['port_number']).',' + .db_qstr($scan_date).')'; + } + } + + if (cacti_sizeof($sql)) { + db_execute($prefix.implode(', ', $sql)); + } + } } - diff --git a/lib/mactrack_dell.php b/lib/mactrack_dell.php index 4714e3bc..8d67b2f5 100644 --- a/lib/mactrack_dell.php +++ b/lib/mactrack_dell.php @@ -1,4 +1,5 @@ $tempInterfaces) { - preg_match('/[0-9]{1,3}/', $tempInterfaces['ifType'], $newType); - $ifInterfaces[$key]['ifType'] = $newType[0]; - } - } + // sanitize ifInterfaces by removing text from ifType field + if (cacti_sizeof($ifInterfaces)) { + foreach ($ifInterfaces as $key => $tempInterfaces) { + preg_match('/[0-9]{1,3}/', $tempInterfaces['ifType'], $newType); + $ifInterfaces[$key]['ifType'] = $newType[0]; + } + } - get_base_dell_dot1qFdb_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_dell_dot1qFdb_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /* get_base_dell_dot1qFdb_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. @@ -64,207 +67,215 @@ function get_dell_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = This was mainly copied from the default dot1q function in mactrack_functions.php but was modified to work with Dell switches */ -function get_base_dell_dot1qFdb_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { - global $debug, $scan_date; - - /* initialize variables */ - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_key_array = array(); - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - $snmp_readstring = $device['snmp_readstring']; - - /* get the operational status of the ports */ - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - /* Sanitize active ports array, removing text junk as the dell's don't return just a plain numeric value */ - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $key => $tempPorts) { - preg_match('/[0-9]{1,3}/',$tempPorts,$newStatus); - $active_ports_array[$key]=$newStatus[0]; - } - } - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) || - ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { - if ($port_info == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); - /* Sanitize port_status array, removing text junk as the dell's don't return just a plain numeric value*/ - if (cacti_sizeof($port_status)) { - foreach ($port_status as $key => $tempStatus) { - preg_match('/[0-9]{1,3}/',$tempStatus,$newStatus); - $port_status[$key]=$newStatus[0]; - } - } - - //print_r($port_status); - /* get device active port numbers - This is the OID that shows the mac address as the index and the port as the value*/ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* get the bridge root port so we don't capture active ports on it */ - $bridge_root_port = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.2.7.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort) && - ($bridge_root_port != $port_number))) { - - if (!in_array($port_number, $ignore_ports)) { - if ((isset($port_status[$key]) && $port_status[$key] == '3') || (isset($port_status[$key]) && $port_status[$key] == '5')) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - $i++; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes) != 0) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || ($brPortIfType == 71)) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $new_port_key_array[$i]['port_name'] = $ifInterfaces[$port_key['port_number']]['ifAlias']; - $i++; - } - } - } - } - mactrack_debug('Port number information collected.'); - - /* map mac address */ - /* only continue if there were user ports defined */ - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_mac) { - $new_port_key_array[$key]['mac_address'] = dell_mac_address_convert($port_mac['key']); - mactrack_debug('INDEX: '. $key . ' MAC ADDRESS: ' . $new_port_key_array[$key]['mac_address']); - } - - /* Map Vlan names to pvid's */ - $vlan_names = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); - - - /* map pvid's to ports with vlan names*/ - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port) { - $temp_array = explode('.', $port['key']); - $new_port_key_array[$key]['vlan_id'] = $temp_array[0]; - $new_port_key_array[$key]['vlan_name'] = mactrack_arr_key($vlan_names, $new_port_key_array[$key]['vlan_id']); - } - } - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_base_dell_dot1qFdb_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + $snmp_readstring = $device['snmp_readstring']; + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + // Sanitize active ports array, removing text junk as the dell's don't return just a plain numeric value + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $key => $tempPorts) { + preg_match('/[0-9]{1,3}/', $tempPorts, $newStatus); + $active_ports_array[$key] = $newStatus[0]; + } + } + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); + // Sanitize port_status array, removing text junk as the dell's don't return just a plain numeric value + if (cacti_sizeof($port_status)) { + foreach ($port_status as $key => $tempStatus) { + preg_match('/[0-9]{1,3}/', $tempStatus, $newStatus); + $port_status[$key] = $newStatus[0]; + } + } + + // print_r($port_status); + /* get device active port numbers + This is the OID that shows the mac address as the index and the port as the value*/ + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // get the bridge root port so we don't capture active ports on it + $bridge_root_port = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.2.7.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort) + && ($bridge_root_port != $port_number))) { + if (!in_array($port_number, $ignore_ports)) { + if ((isset($port_status[$key]) && '3' == $port_status[$key]) || (isset($port_status[$key]) && '5' == $port_status[$key])) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (0 != cacti_sizeof($bridgePortIfIndexes)) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || (71 == $brPortIfType)) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + $new_port_key_array[$i]['port_name'] = $ifInterfaces[$port_key['port_number']]['ifAlias']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_mac) { + $new_port_key_array[$key]['mac_address'] = dell_mac_address_convert($port_mac['key']); + mactrack_debug('INDEX: '.$key.' MAC ADDRESS: '.$new_port_key_array[$key]['mac_address']); + } + + // Map Vlan names to pvid's + $vlan_names = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); + + // map pvid's to ports with vlan names + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port) { + $temp_array = explode('.', $port['key']); + $new_port_key_array[$key]['vlan_id'] = $temp_array[0]; + $new_port_key_array[$key]['vlan_name'] = mactrack_arr_key($vlan_names, $new_port_key_array[$key]['vlan_id']); + } + } + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } -function dell_mac_address_convert($mac_address) { - if ($mac_address == '') { - $mac_address = 'NOT USER'; - } elseif (strlen($mac_address) > 10) { /* return is in ascii */ - $mac_address = trim(str_replace('"', '', $mac_address)); - $mac_address = str_replace('.', ':', $mac_address); - $mac_address = str_replace('-', ':', $mac_address); - $mac = explode(':', $mac_address); - - foreach ($mac as $key => $mac_item) { - if (!empty($mac_item)) { - $mac_item = dechex($mac_item); - if (strlen($mac_item) < 2) { - $mac_item = '0'.$mac_item; - } - $mac[$key] = strtoupper($mac_item); - } - } - - $mac_address = implode('', $mac); - } - - return $mac_address; +function dell_mac_address_convert($mac_address) +{ + if ('' == $mac_address) { + $mac_address = 'NOT USER'; + } elseif (strlen($mac_address) > 10) { // return is in ascii + $mac_address = trim(str_replace('"', '', $mac_address)); + $mac_address = str_replace('.', ':', $mac_address); + $mac_address = str_replace('-', ':', $mac_address); + $mac = explode(':', $mac_address); + + foreach ($mac as $key => $mac_item) { + if (!empty($mac_item)) { + $mac_item = dechex($mac_item); + if (strlen($mac_item) < 2) { + $mac_item = '0'.$mac_item; + } + $mac[$key] = strtoupper($mac_item); + } + } + + $mac_address = implode('', $mac); + } + + return $mac_address; } - diff --git a/lib/mactrack_dlink.php b/lib/mactrack_dlink.php index 6423f56d..58b3bc61 100644 --- a/lib/mactrack_dlink.php +++ b/lib/mactrack_dlink.php @@ -1,4 +1,5 @@ = 6) && - (convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) <= 9)) || - (convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) == 117)) { - if (convert_dlink_data($port_info) == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); - - /* get device active port numbers */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to a new array. */ - $i = 0; - - if (cacti_sizeof($port_numbers) > 0) { - foreach ($port_numbers as $key => $port_number) { - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort))) { - - if (!in_array($port_number, $ignore_ports)) { - if ((@$port_status[$key] == '3') || (@$port_status[$key] == '1')) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - $i++; - } - } - } - } - } - - $i = 0; - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); - - $i = 0; - if (cacti_sizeof($port_key_array) > 0) { - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] >= 0) { - if (cacti_sizeof($bridgePortIfIndexes) != 0) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; - } else { - $brPortIfIndex = @$port_key['port_number']; - } - $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; - } - - if ((((convert_dlink_data($brPortIfType) >= 6) && - (convert_dlink_data($brPortIfType) <= 9)) || (convert_dlink_data($brPortIfType) == 117)) && - (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = get_dlink_vlan_id($port_key['key']); - $new_port_key_array[$i]['vlan_name'] = $vlan_names[$new_port_key_array[$i]['vlan_id']]; - $new_port_key_array[$i]['mac_address'] = dlink_convert_macs($port_key['key']); - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $new_port_key_array[$i]['port_name'] = @$ifNames[$port_key['port_number']]; - /* now set the real data */ - $new_port_key_array[$i]['key'] = $port_key['key']; - $i++; - } - } - } - } - mactrack_debug('Port number information collected.'); - - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_dlink_l2_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + if (((convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) >= 6) + && (convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) <= 9)) + || (117 == convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']))) { + if (1 == convert_dlink_data($port_info)) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // determine user ports for this device and transfer user ports to a new array. + $i = 0; + + if (cacti_sizeof($port_numbers) > 0) { + foreach ($port_numbers as $key => $port_number) { + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports)) { + if (('3' == @$port_status[$key]) || ('1' == @$port_status[$key])) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + ++$i; + } + } + } + } + } + + $i = 0; + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); + + $i = 0; + if (cacti_sizeof($port_key_array) > 0) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] >= 0) { + if (0 != cacti_sizeof($bridgePortIfIndexes)) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; + } else { + $brPortIfIndex = @$port_key['port_number']; + } + $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; + } + + if ((((convert_dlink_data($brPortIfType) >= 6) + && (convert_dlink_data($brPortIfType) <= 9)) || (117 == convert_dlink_data($brPortIfType))) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = get_dlink_vlan_id($port_key['key']); + $new_port_key_array[$i]['vlan_name'] = $vlan_names[$new_port_key_array[$i]['vlan_id']]; + $new_port_key_array[$i]['mac_address'] = dlink_convert_macs($port_key['key']); + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + $new_port_key_array[$i]['port_name'] = @$ifNames[$port_key['port_number']]; + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } -function dlink_convert_macs ($oldmac){ - if ($oldmac[0] != '.') { - $oldmac = '.' . $oldmac; - } - - $oldmac =substr($oldmac,stripos($oldmac,'.')+1); - $oldmac =substr($oldmac,stripos($oldmac,'.')+1); - $piece = explode('.', $oldmac); - $newmac = ''; +function dlink_convert_macs($oldmac) +{ + if ('.' != $oldmac[0]) { + $oldmac = '.'.$oldmac; + } - for ($i = 0; $i < 6; $i++){ - $newmac = $newmac . dec2hex($piece[$i],2) . ':'; - } + $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); + $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); + $piece = explode('.', $oldmac); + $newmac = ''; - $newmac = substr($newmac, 0, strlen($newmac)-1); + for ($i = 0; $i < 6; ++$i) { + $newmac = $newmac.dec2hex($piece[$i], 2).':'; + } - return $newmac; + return substr($newmac, 0, strlen($newmac) - 1); } -function dec2hex($number, $length) { - $hexval = ''; - - while ($number>0) { - $remainder=$number%16; - if ($remainder<10) - $hexval=$remainder.$hexval; - elseif ($remainder==10) - $hexval='a'.$hexval; - elseif ($remainder==11) - $hexval='b'.$hexval; - elseif ($remainder==12) - $hexval='c'.$hexval; - elseif ($remainder==13) - $hexval='d'.$hexval; - elseif ($remainder==14) - $hexval='e'.$hexval; - elseif ($remainder==15) - $hexval='f'.$hexval; - $number=floor($number/16); - } - - while (strlen($hexval) < $length) { - $hexval = '0' . $hexval; - } - - //this is just to add zero's at the beginning to make hexval a certain length - return $hexval; +function dec2hex($number, $length) +{ + $hexval = ''; + + while ($number > 0) { + $remainder = $number % 16; + if ($remainder < 10) { + $hexval = $remainder.$hexval; + } elseif (10 == $remainder) { + $hexval = 'a'.$hexval; + } elseif (11 == $remainder) { + $hexval = 'b'.$hexval; + } elseif (12 == $remainder) { + $hexval = 'c'.$hexval; + } elseif (13 == $remainder) { + $hexval = 'd'.$hexval; + } elseif (14 == $remainder) { + $hexval = 'e'.$hexval; + } elseif (15 == $remainder) { + $hexval = 'f'.$hexval; + } + $number = floor($number / 16); + } + + while (strlen($hexval) < $length) { + $hexval = '0'.$hexval; + } + + // this is just to add zero's at the beginning to make hexval a certain length + return $hexval; } if (!function_exists('stripos')) { - function stripos($str,$needle) { - return strpos(strtolower($str),strtolower($needle)); - } + function stripos($str, $needle) + { + return strpos(strtolower($str), strtolower($needle)); + } } -function xform_dlink_vlan_associations(&$device, $snmp_readstring = '') { - /* get raw index data */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* initialize the output array */ - $output_array = array(); - - /* obtain vlan associations */ - $xformArray = cacti_snmp_walk($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.2.2.1.2', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries'], $device['max_oids']); - - $i = 0; - foreach ($xformArray as $xformItem) { - /* peel off the beginning of the OID */ - $key = $xformItem['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); - /* now grab the VLAN */ - $perPos = strpos($key, '.',1); - $output_array[$i]['vlan_id'] = substr($key,1,$perPos-1); - /* save the key for association with the dot1d table */ - $output_array[$i]['key'] = substr($key, $perPos+1); - $vlan_name = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.4.3.1.1.' . $output_array[$i]['vlan_id'], $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - $output_array[$i]['vlan_name'] = $vlan_name; - - $i++; - } - - //return array_rekey($output_array, 'key', 'vlan_name'); - return $output_array; +function xform_dlink_vlan_associations(&$device, $snmp_readstring = '') +{ + // get raw index data + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // initialize the output array + $output_array = []; + + // obtain vlan associations + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.2.2.1.2', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + $i = 0; + foreach ($xformArray as $xformItem) { + // peel off the beginning of the OID + $key = $xformItem['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); + // now grab the VLAN + $perPos = strpos($key, '.', 1); + $output_array[$i]['vlan_id'] = substr($key, 1, $perPos - 1); + // save the key for association with the dot1d table + $output_array[$i]['key'] = substr($key, $perPos + 1); + $vlan_name = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.4.3.1.1.'.$output_array[$i]['vlan_id'], + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $output_array[$i]['vlan_name'] = $vlan_name; + + ++$i; + } + + // return array_rekey($output_array, 'key', 'vlan_name'); + return $output_array; } -function get_dlink_vlan_id($OID) { - if ($OID[0] != '.') { - $OID = '.' . $OID; - } +function get_dlink_vlan_id($OID) +{ + if ('.' != $OID[0]) { + $OID = '.'.$OID; + } - $perPos = strpos($OID, '.', 1); - $vlan_id = substr($OID, 1, $perPos-1); + $perPos = strpos($OID, '.', 1); - return $vlan_id; + return substr($OID, 1, $perPos - 1); } -function convert_dlink_data($old_port_type) { - $result = $old_port_type; - if (is_string($old_port_type) && substr_count($old_port_type, '(') > 0) { - $pos1 = strpos($old_port_type, '('); - $pos2 = strpos($old_port_type, ')'); - $result = substr($old_port_type, $pos1+1, $pos2-$pos1-1); - } +function convert_dlink_data($old_port_type) +{ + $result = $old_port_type; + if (is_string($old_port_type) && substr_count($old_port_type, '(') > 0) { + $pos1 = strpos($old_port_type, '('); + $pos2 = strpos($old_port_type, ')'); + $result = substr($old_port_type, $pos1 + 1, $pos2 - $pos1 - 1); + } - return $result; + return $result; } - diff --git a/lib/mactrack_enterasys.php b/lib/mactrack_enterasys.php index 890a775a..e7e699af 100644 --- a/lib/mactrack_enterasys.php +++ b/lib/mactrack_enterasys.php @@ -1,4 +1,5 @@ = 6) && ($ifType <= 9)) { - $device['ports_total']++; - } - } - } - mactrack_debug('Total Ports = ' . $device['ports_total']); - - /* calculate the number of trunk ports */ - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - if ($ifInterfaces[$ifIndex]['trunkPortState'] == 1) { - $device['ports_trunk']++; - } - } - } - mactrack_debug('Total Trunk Ports = ' . $device['ports_trunk']); - - /* get VLAN details */ - $i = 0; - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_id => $vlan_name) { - $active_vlans[$i]['vlan_id'] = $vlan_id; - $active_vlans[$i]['vlan_name'] = $vlan_name; - $active_vlans++; - $i++; - } - } - - if (cacti_sizeof($active_vlans)) { - /* get the port status information */ - $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); - $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.3.4', $device); - - $i = 0; - $j = 0; - $port_array = array(); - - foreach ($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - $ifType = mactrack_strip_alpha($ifTypes[$ifIndex]); - $ifName = $ifNames[$ifIndex]; - $portName = $ifName; - $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; - - /* only output legitimate end user ports */ - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); - $port_array[$i]['vlan_name'] = isset($vlan_ids[$port_array[$i]['vlan_id']]) ? $vlan_ids[$port_array[$i]['vlan_id']] : ''; - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - - mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' . - 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' . - 'PORT: ' . $ifIndex . ', ' . - 'NAME: ' . $port_array[$i]['port_name'] . ', ' . - 'MAC: ' . $port_array[$i]['mac_address']); - - $i++; - } - - $j++; - } - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_enterasys_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // get VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.4.4.1.2', $device); + + // get VLAN Trunk status + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.5.4', $device); + $device['vlans_total'] = cacti_sizeof($vlan_trunkstatus); + mactrack_debug('VLAN data collected. There are '.cacti_sizeof($vlan_ids).' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get the ifTypes for the device + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + mactrack_debug('ifTypes data collection complete.'); + + // get the ifNames for the device + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete.'); + + // get ports that happen to be link ports + $link_ports = get_link_port_status($device); + mactrack_debug('ipAddrTable scanning for link ports data collection complete.'); + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); + $ifInterfaces[$ifIndex]['ifType'] = mactrack_strip_alpha($ifTypes[$ifIndex]); + $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); + $ifInterfaces[$ifIndex]['trunkPortState'] = mactrack_arr_key($vlan_trunkstatus, $ifIndex); + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // calculate the number of end user ports + if (cacti_sizeof($ifTypes)) { + foreach ($ifTypes as $ifType) { + $ifType = mactrack_strip_alpha($ifType); + + if (($ifType >= 6) && ($ifType <= 9)) { + ++$device['ports_total']; + } + } + } + mactrack_debug('Total Ports = '.$device['ports_total']); + + // calculate the number of trunk ports + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + if (1 == $ifInterfaces[$ifIndex]['trunkPortState']) { + ++$device['ports_trunk']; + } + } + } + mactrack_debug('Total Trunk Ports = '.$device['ports_trunk']); + + // get VLAN details + $i = 0; + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_id => $vlan_name) { + $active_vlans[$i]['vlan_id'] = $vlan_id; + $active_vlans[$i]['vlan_name'] = $vlan_name; + ++$active_vlans; + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + // get the port status information + $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); + $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.3.4', $device); + + $i = 0; + $j = 0; + $port_array = []; + + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + $ifType = mactrack_strip_alpha($ifTypes[$ifIndex]); + $ifName = $ifNames[$ifIndex]; + $portName = $ifName; + $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); + $port_array[$i]['vlan_name'] = isset($vlan_ids[$port_array[$i]['vlan_id']]) ? $vlan_ids[$port_array[$i]['vlan_id']] : ''; + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + + mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' + .'NAME: '.$port_array[$i]['vlan_name'].', ' + .'PORT: '.$ifIndex.', ' + .'NAME: '.$port_array[$i]['port_name'].', ' + .'MAC: '.$port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } - diff --git a/lib/mactrack_enterasys_N7.php b/lib/mactrack_enterasys_N7.php index c0b99d76..2801c364 100644 --- a/lib/mactrack_enterasys_N7.php +++ b/lib/mactrack_enterasys_N7.php @@ -1,4 +1,5 @@ = 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { - $device['ports_total']++; - } - } - mactrack_debug('ifInterfaces assembly complete: ' . cacti_sizeof($ifIndexes)); - - /* map vlans to bridge ports */ - if (cacti_sizeof($vlan_ids) > 0) { - /* get the port status information */ - #$port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); - $port_results = get_enterasys_N7_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); - #print_r($port_results); - /* get the ifIndexes for the device */ - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device); - #print_r($vlan_names); - - $i = 0; - $j = 0; - $port_array = array(); - foreach($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - #print_r($port_result); print_r($ifInterfaces[$ifIndex]); - $ifType = $ifInterfaces[$ifIndex]['ifType']; - - /* only output legitimate end user ports */ - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_result['key']); - $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_names, $port_array[$i]['vlan_id']); - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - - mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' . - 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' . - 'PORT: ' . $ifInterfaces[$ifIndex]['ifName'] . ', ' . - 'NAME: ' . $port_array[$i]['port_name'] . ', ' . - 'MAC: ' . $port_array[$i]['mac_address']); - - $i++; - } - - $j++; - } - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . trim(substr($device['snmp_sysDescr'],0,40)) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - mactrack_debug('macs active on this switch:' . $device['macs_active']); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_enterasys_N7_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + + // get VLAN information + $vlan_ids = xform_dot1q_vlan_associations($device, $device['snmp_readstring']); + // $vlan_ids = xform_enterasys_N7_vlan_associations($device, $device['snmp_readstring']); + // print_r($vlan_ids); + // get VLAN Trunk status: not (yet) implemented for Enterasys N7 + // $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.2272.1.3.3.1.4', $device); + $device['vlans_total'] = cacti_sizeof($vlan_ids); + mactrack_debug('VLAN data collected. There are '.cacti_sizeof($vlan_ids).' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete: '.cacti_sizeof($ifIndexes)); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + // print_r($ifInterfaces); + + foreach ($ifIndexes as $ifIndex) { + if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { + ++$device['ports_total']; + } + } + mactrack_debug('ifInterfaces assembly complete: '.cacti_sizeof($ifIndexes)); + + // map vlans to bridge ports + if (cacti_sizeof($vlan_ids) > 0) { + // get the port status information + // $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); + $port_results = get_enterasys_N7_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); + // print_r($port_results); + // get the ifIndexes for the device + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device); + // print_r($vlan_names); + + $i = 0; + $j = 0; + $port_array = []; + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + // print_r($port_result); print_r($ifInterfaces[$ifIndex]); + $ifType = $ifInterfaces[$ifIndex]['ifType']; + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_result['key']); + $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_names, $port_array[$i]['vlan_id']); + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + + mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' + .'NAME: '.$port_array[$i]['vlan_name'].', ' + .'PORT: '.$ifInterfaces[$ifIndex]['ifName'].', ' + .'NAME: '.$port_array[$i]['port_name'].', ' + .'MAC: '.$port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.trim(substr($device['snmp_sysDescr'], 0, 40)).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + mactrack_debug('macs active on this switch:'.$device['macs_active']); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_base_dot1dTpFdbEntry_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. This is a foundational function for all vendor data collection functions. */ -function get_enterasys_N7_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { - global $debug, $scan_date; - mactrack_debug('FUNCTION: get_enterasys_N7_dot1dTpFdbEntry_ports started'); - - /* initialize variables */ - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_key_array = array(); - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - /* cisco uses a hybrid read string, if one is not defined, use the default */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* get the operational status of the ports */ - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - mactrack_debug('get active ports: ' . cacti_sizeof($active_ports_array)); - $indexes = array_keys($active_ports_array); - - $i = 0; - foreach($active_ports_array as $port_info) { - if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { - if ($port_info == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 - where - table index = bridge port (dot1dBasePort) and - table value = ifIndex */ - /* -------------------------------------------- */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('get bridgePortIfIndexes: ' . cacti_sizeof($bridgePortIfIndexes)); - - /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ - /* -------------------------------------------- */ - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - mactrack_debug('get port_status: ' . cacti_sizeof($port_status)); - - /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = bridge port */ - /* -------------------------------------------- */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - mactrack_debug('get port_numbers: ' . cacti_sizeof($port_numbers)); - - /* get VLAN information */ - /* -------------------------------------------- */ - #$vlan_ids = xform_enterasys_N7_vlan_associations($device, $snmp_readstring); - $vlan_ids = xform_dot1q_vlan_associations($device, $snmp_readstring); - mactrack_debug('get vlan_ids: ' . cacti_sizeof($vlan_ids)); -#print_r($vlan_ids); - - - - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - foreach ($port_numbers as $key => $port_number) { - /* key = MAC Address from dot1dTpFdbTable */ - /* value = bridge port */ - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort))) { - - if (!in_array($port_number, $ignore_ports)) { - if (isset($port_status[$key]) && $port_status[$key] == '3') { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; -#print('i: $i, Key: ' . $port_key_array[$i]['key'] . ', Number: $port_number\n'); - $i++; - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes) != 0) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - mactrack_debug('Searching Bridge Port: ' . $port_key['port_number'] . ', Bridge: ' . $bridgePortIfIndexes[$port_key['port_number']]); - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - } else { - $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); - } - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if (($brPortIfType >= 6) && - ($brPortIfType <= 9) && - (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); - $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; - $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_key['key']); -#print_r($new_port_key_array[$i]); - $i++; - } - } - } - mactrack_debug('Port number information collected: ' . cacti_sizeof($new_port_key_array)); - - /* map mac address */ - /* only continue if there were user ports defined */ - if (cacti_sizeof($new_port_key_array) > 0) { - /* get the bridges active MAC addresses */ - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); - mactrack_debug('INDEX: ' . $key . ' MAC ADDRESS: ' . $new_port_key_array[$key]['mac_address']); - } - - mactrack_debug('Port mac address information collected: ' . cacti_sizeof($port_macs)); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } - +function get_enterasys_N7_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + mactrack_debug('FUNCTION: get_enterasys_N7_dot1dTpFdbEntry_ports started'); + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + mactrack_debug('get active ports: '.cacti_sizeof($active_ports_array)); + $indexes = array_keys($active_ports_array); + + $i = 0; + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 + where + table index = bridge port (dot1dBasePort) and + table value = ifIndex */ + // -------------------------------------------- + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('get bridgePortIfIndexes: '.cacti_sizeof($bridgePortIfIndexes)); + + /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ + // -------------------------------------------- + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + mactrack_debug('get port_status: '.cacti_sizeof($port_status)); + + /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = bridge port */ + // -------------------------------------------- + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + mactrack_debug('get port_numbers: '.cacti_sizeof($port_numbers)); + + // get VLAN information + // -------------------------------------------- + // $vlan_ids = xform_enterasys_N7_vlan_associations($device, $snmp_readstring); + $vlan_ids = xform_dot1q_vlan_associations($device, $snmp_readstring); + mactrack_debug('get vlan_ids: '.cacti_sizeof($vlan_ids)); + // print_r($vlan_ids); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + foreach ($port_numbers as $key => $port_number) { + // key = MAC Address from dot1dTpFdbTable + // value = bridge port + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports)) { + if (isset($port_status[$key]) && '3' == $port_status[$key]) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + // print('i: $i, Key: ' . $port_key_array[$i]['key'] . ', Number: $port_number\n'); + ++$i; + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (0 != cacti_sizeof($bridgePortIfIndexes)) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + mactrack_debug('Searching Bridge Port: '.$port_key['port_number'].', Bridge: '.$bridgePortIfIndexes[$port_key['port_number']]); + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + } else { + $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); + } + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if (($brPortIfType >= 6) + && ($brPortIfType <= 9) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); + $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; + $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_key['key']); + // print_r($new_port_key_array[$i]); + ++$i; + } + } + } + mactrack_debug('Port number information collected: '.cacti_sizeof($new_port_key_array)); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array) > 0) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); + mactrack_debug('INDEX: '.$key.' MAC ADDRESS: '.$new_port_key_array[$key]['mac_address']); + } + + mactrack_debug('Port mac address information collected: '.cacti_sizeof($port_macs)); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } -function enterasys_N7_convert_macs($oldmac) { - $oldmac = substr($oldmac,stripos($oldmac,'.')+1); - $oldmac = substr($oldmac,stripos($oldmac,'.')); - $piece = explode('.', $oldmac); - $newmac = ''; +function enterasys_N7_convert_macs($oldmac) +{ + $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); + $oldmac = substr($oldmac, stripos($oldmac, '.')); + $piece = explode('.', $oldmac); + $newmac = ''; - for ($i = 0; $i < 6; $i++) { - $newmac .= ($newmac != '' ? ':':'') . dec2hex($piece[$i],2); - } + for ($i = 0; $i < 6; ++$i) { + $newmac .= ('' != $newmac ? ':' : '').dec2hex($piece[$i], 2); + } - return $newmac; + return $newmac; } -function xform_enterasys_N7_vlan_associations(&$device, $snmp_readstring = '') { - /* get raw index data */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* initialize the output array */ - $output_array = array(); - - /* obtain vlan associations: dot1qTpFdbStatus from dot1qTpFdbTable */ - $xformArray = cacti_snmp_walk($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.2.2.1.2', $device['snmp_version'], '', '', - '', '', '', '', $device['snmp_port'], $device['snmp_timeout']); - - $i = 0; - foreach($xformArray as $xformItem) { - /* peel off the beginning of the OID */ - $key = $xformItem['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); - - /* now grab the VLAN Id */ - $perPos = strpos($key, '.',1); - $output_array[$i]['vlan_id'] = substr($key,1,$perPos-1); - - /* save the key=MAC Address for association with the dot1d table */ - $output_array[$i]['key'] = substr($key, $perPos); - - /* get VLAN name, if any: dot1qVlanStaticName from dot1qVlanStaticTable */ - $vlan_name = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.4.3.1.1.' . $output_array[$i]['vlan_id'], $device['snmp_version'], '', '', - '', '', '', '', $device['snmp_port'], $device['snmp_timeout']); - $output_array[$i]['vlan_name'] = $vlan_name; - $i++; - } - - return array_rekey($output_array, 'key', 'vlan_id'); - #return $output_array; +function xform_enterasys_N7_vlan_associations(&$device, $snmp_readstring = '') +{ + // get raw index data + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // initialize the output array + $output_array = []; + + // obtain vlan associations: dot1qTpFdbStatus from dot1qTpFdbTable + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.2.2.1.2', + $device['snmp_version'], + '', + '', + '', + '', + '', + '', + $device['snmp_port'], + $device['snmp_timeout'] + ); + + $i = 0; + foreach ($xformArray as $xformItem) { + // peel off the beginning of the OID + $key = $xformItem['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); + + // now grab the VLAN Id + $perPos = strpos($key, '.', 1); + $output_array[$i]['vlan_id'] = substr($key, 1, $perPos - 1); + + // save the key=MAC Address for association with the dot1d table + $output_array[$i]['key'] = substr($key, $perPos); + + // get VLAN name, if any: dot1qVlanStaticName from dot1qVlanStaticTable + $vlan_name = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.4.3.1.1.'.$output_array[$i]['vlan_id'], + $device['snmp_version'], + '', + '', + '', + '', + '', + '', + $device['snmp_port'], + $device['snmp_timeout'] + ); + $output_array[$i]['vlan_name'] = $vlan_name; + ++$i; + } + + return array_rekey($output_array, 'key', 'vlan_id'); + // return $output_array; } -function get_enterasys_N7_vlan_id($OID) { - $perPos = strpos($OID, '.',1); - $vlan_id = substr($OID,0,$perPos); - return $vlan_id; -} +function get_enterasys_N7_vlan_id($OID) +{ + $perPos = strpos($OID, '.', 1); + return substr($OID, 0, $perPos); +} /* get_CTAlias_table - This function reads a devices CTAlias table for a site and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_CTAlias_table($site, &$device) { - global $debug, $scan_date; - - mactrack_debug('FUNCTION: get_CTAlias_table started'); - - /* get the CTAlias Table for the device */ - $CTAliasInterfaces = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.3', $device, 2); - mactrack_debug('CTAliasInterfaces data collection complete: ' . cacti_sizeof($CTAliasInterfaces)); - - /* get the CTAliasMacAddress for the device */ - $CTAliasMacAddress = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.4', $device, 2, true); - mactrack_debug('CTAliasMacAddress data collection complete: ' . cacti_sizeof($CTAliasMacAddress)); - - /* convert the mac address if necessary */ - $keys = array_keys($CTAliasMacAddress); - $i = 0; - foreach($CTAliasMacAddress as $MacAddress) { - $CTAliasMacAddress[$keys[$i]] = xform_mac_address($MacAddress); - $i++; - } - - /* get the CTAliasProtocol Table for the device */ - $CTAliasProtocol = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.6', $device, 2); - mactrack_debug('CTAliasProtocol data collection complete: ' . cacti_sizeof($CTAliasProtocol)); - - /* get the CTAliasAddressText for the device */ - $CTAliasAddressText = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.9', $device, 2); - mactrack_debug('CTAliasAddressText data collection complete: ' . cacti_sizeof($CTAliasAddressText)); - - /* get the ifNames for the device */ - $keys = array_keys($CTAliasInterfaces); - $i = 0; - $CTAliasEntries = array(); - - foreach($CTAliasInterfaces as $ifIndex) { - $CTAliasEntries[$i]['ifIndex'] = $ifIndex; - $CTAliasEntries[$i]['timestamp'] = $keys[$i]; - $CTAliasEntries[$i]['CTAliasProtocol'] = mactrack_arr_key($CTAliasProtocol, $keys[$i]); - $CTAliasEntries[$i]['CTAliasMacAddress'] = mactrack_arr_key($CTAliasMacAddress, $keys[$i]); - $CTAliasEntries[$i]['CTAliasAddressText'] = mactrack_arr_key($CTAliasAddressText, $keys[$i]); - $i++; - } - mactrack_debug('CTAliasEntries assembly complete: ' . cacti_sizeof($CTAliasEntries)); - - /* output details to database */ - if (cacti_sizeof($CTAliasEntries)) { - $sql = array(); - - foreach($CTAliasEntries as $CTAliasEntry) { - /* drop non-IP protocols */ - if ($CTAliasEntry['CTAliasProtocol'] != 1) { - continue; - } - - $sql[] = '(' . - $device['site_id'] . ', ' . - $device['device_id'] . ', ' . - db_qstr($device['hostname']) . ', ' . - db_qstr($device['device_name']) . ', ' . - db_qstr($CTAliasEntry['ifIndex']) . ', ' . - db_qstr($CTAliasEntry['CTAliasMacAddress']) . ', ' . - db_qstr($CTAliasEntry['CTAliasAddressText']) . ', ' . - db_qstr($scan_date) . ')'; - } - - db_execute('REPLACE INTO mac_track_ips +function get_CTAlias_table($site, &$device) +{ + global $debug, $scan_date; + + mactrack_debug('FUNCTION: get_CTAlias_table started'); + + // get the CTAlias Table for the device + $CTAliasInterfaces = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.3', $device, 2); + mactrack_debug('CTAliasInterfaces data collection complete: '.cacti_sizeof($CTAliasInterfaces)); + + // get the CTAliasMacAddress for the device + $CTAliasMacAddress = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.4', $device, 2, true); + mactrack_debug('CTAliasMacAddress data collection complete: '.cacti_sizeof($CTAliasMacAddress)); + + // convert the mac address if necessary + $keys = array_keys($CTAliasMacAddress); + $i = 0; + foreach ($CTAliasMacAddress as $MacAddress) { + $CTAliasMacAddress[$keys[$i]] = xform_mac_address($MacAddress); + ++$i; + } + + // get the CTAliasProtocol Table for the device + $CTAliasProtocol = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.6', $device, 2); + mactrack_debug('CTAliasProtocol data collection complete: '.cacti_sizeof($CTAliasProtocol)); + + // get the CTAliasAddressText for the device + $CTAliasAddressText = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.9', $device, 2); + mactrack_debug('CTAliasAddressText data collection complete: '.cacti_sizeof($CTAliasAddressText)); + + // get the ifNames for the device + $keys = array_keys($CTAliasInterfaces); + $i = 0; + $CTAliasEntries = []; + + foreach ($CTAliasInterfaces as $ifIndex) { + $CTAliasEntries[$i]['ifIndex'] = $ifIndex; + $CTAliasEntries[$i]['timestamp'] = $keys[$i]; + $CTAliasEntries[$i]['CTAliasProtocol'] = mactrack_arr_key($CTAliasProtocol, $keys[$i]); + $CTAliasEntries[$i]['CTAliasMacAddress'] = mactrack_arr_key($CTAliasMacAddress, $keys[$i]); + $CTAliasEntries[$i]['CTAliasAddressText'] = mactrack_arr_key($CTAliasAddressText, $keys[$i]); + ++$i; + } + mactrack_debug('CTAliasEntries assembly complete: '.cacti_sizeof($CTAliasEntries)); + + // output details to database + if (cacti_sizeof($CTAliasEntries)) { + $sql = []; + + foreach ($CTAliasEntries as $CTAliasEntry) { + // drop non-IP protocols + if (1 != $CTAliasEntry['CTAliasProtocol']) { + continue; + } + + $sql[] = '(' + .$device['site_id'].', ' + .$device['device_id'].', ' + .db_qstr($device['hostname']).', ' + .db_qstr($device['device_name']).', ' + .db_qstr($CTAliasEntry['ifIndex']).', ' + .db_qstr($CTAliasEntry['CTAliasMacAddress']).', ' + .db_qstr($CTAliasEntry['CTAliasAddressText']).', ' + .db_qstr($scan_date).')'; + } + + db_execute('REPLACE INTO mac_track_ips (site_id,device_id,hostname,device_name,port_number, mac_address,ip_address,scan_date) - VALUES ' . implode(', ', $sql)); - } + VALUES '.implode(', ', $sql)); + } - /* save ip information for the device */ - $device['ips_total'] = cacti_sizeof($CTAliasEntries); + // save ip information for the device + $device['ips_total'] = cacti_sizeof($CTAliasEntries); - db_execute_prepared('UPDATE mac_track_devices + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id= ?', - array($device['ips_total'], $device['device_id'])); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete: ' . $device['ips_total']); + mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete: '.$device['ips_total']); } - diff --git a/lib/mactrack_extreme.php b/lib/mactrack_extreme.php index a8b7aada..704656bd 100644 --- a/lib/mactrack_extreme.php +++ b/lib/mactrack_extreme.php @@ -1,4 +1,5 @@ = index - VLAN name - .1.3.6.1.4.1.1916.1.2.1.2.1.2 - EXTREME-VLAN-MIB::extremeVlanIfDescr. = description - VLAN ID - .1.3.6.1.4.1.1916.1.2.1.2.1.10 - EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id - */ - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.2', $device); - $device['vlans_total'] = cacti_sizeof($vlan_ids); - mactrack_debug('There are ' . (cacti_sizeof($vlan_ids)) . ' VLANS.'); - - /* get the ifIndexes for the device - .1.3.6.1.2.1.2.2.1.1 - RFC1213-MIB::ifIndex. = index - .1.3.6.1.2.1.2.2.1.2 - RFC1213-MIB::ifDescr. = description - .1.3.6.1.2.1.2.2.1.3 - RFC1213-MIB::ifType. = type (6=ether) - .1.3.6.1.2.1.31.1.1.1.1 - IF-MIB::ifName. = name - .1.3.6.1.2.1.31.1.1.1.18 - IF-MIB::ifAlias. = alias - */ - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); - - mactrack_debug('ifInterfaces assembly complete.'); - - /* get VLAN details */ - $i = 0; - foreach ($vlan_ids as $vlan_index => $vlan_id) { - $active_vlans[$i]['vlan_id'] = $vlan_id; - $active_vlans[$i]['vlan_name'] = $vlan_names[$vlan_index]; - $active_vlans++; - mactrack_debug('VLAN ID = ' . $active_vlans[$i]['vlan_id'] . ' VLAN Name = ' . $active_vlans[$i]['vlan_name']); - $i++; - } - - if (cacti_sizeof($active_vlans) > 0) { - - /* get the port status information */ - /* get port_number and MAC addr */ - /*extremeXOS - addr mac - .1.3.6.1.4.1.1916.1.16.4.1.1 - EXTREME-BASE-MIB::extremeFdb.4.1.1..= hex MAC - index du vlan ? - .1.3.6.1.4.1.1916.1.16.4.1.2 - EXTREME-BASE-MIB::extremeFdb.4.1.2..=vlanid - index du port - .1.3.6.1.4.1.1916.1.16.4.1.3 - EXTREME-BASE-MIB::extremeFdb.4.1.3..=port id - status - .1.3.6.1.4.1.1916.1.16.4.1.4 - EXTREME-BASE-MIB::extremeFdb.4.1.4..= 3 learned - - extremeware - .1.3.6.1.4.1.1916.1.16.1.1.3 - EXTREME-FDB-MIB::extremeFdbMacFdbMacAddress.. = mac - .1.3.6.1.4.1.1916.1.16.1.1.4 - EXTREME-FDB-MIB::extremeFdbMacFdbPortIfIndex.. = index du port - .1.3.6.1.4.1.1916.1.16.1.1.5 - EXTREME-FDB-MIB::extremeFdbMacFdbStatus.. = 3 learned - */ - if ($extremeware) { - $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.3', $device); - $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.4', $device); - $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.5', $device); - } else { - $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.1', $device); - $mac_vlan_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.2', $device); - $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.3', $device); - $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.4', $device); - } - - $port_array = array(); - - foreach ($mac_addr_list as $mac_key => $mac_addr) { - /* check if mac addr is 'learned' or 'mgnt' */ - if (isset($mac_status_list[$mac_key]) and (($mac_status_list[$mac_key] == '3') || ($mac_status_list[$mac_key] == '5'))) { - $ifIndex = $mac_port_list[$mac_key]; - $ifType = $ifInterfaces[$ifIndex]['ifType']; - //$ifType = $ifTypes[$ifIndex]; - /* only output legitimate end user ports */ - if (($ifType >= 6) && ($ifType <= 9)) { - if ($extremeware) { - $vlanid = substr($mac_key,0,strpos($mac_key,'.')); - $new_port_array['vlan_id'] = $vlan_ids[$vlanid]; - $new_port_array['vlan_name'] = $vlan_names[$vlanid]; - } else { - $new_port_array['vlan_id'] = $vlan_ids[$mac_vlan_list[$mac_key]]; - $new_port_array['vlan_name'] = $vlan_names[$mac_vlan_list[$mac_key]]; - } - - //$new_port_array['port_number'] = $ifIndex; - //$new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifName']; - $new_port_array['port_number'] = $ifInterfaces[$ifIndex]['ifName']; - $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifAlias']; - $new_port_array['mac_address'] = xform_mac_address($mac_addr_list[$mac_key]); - $ifInterfaces[$ifIndex]['Used'] = 1; - $port_array[] = $new_port_array; - - mactrack_debug('VLAN: ' . $new_port_array['vlan_id'] . ', ' . - 'NAME: ' . $new_port_array['vlan_name'] . ', ' . - 'PORT: ' . $ifIndex . ', ' . - 'NAME: ' . $new_port_array['port_name'] . ', ' . - 'MAC: ' . $new_port_array['mac_address']); - } - } - } - - $device['ports_total'] = cacti_sizeof($ifInterfaces); - $device['ports_active'] = 0; - - foreach ($ifInterfaces as $interface) { - if (isset($interface['Used'])) { - $device['ports_active']++; - } - } - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_extreme_switch_ports($site, &$device, $lowPort = 0, $highPort = 0, $extremeware = false) +{ + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + $device['macs_active'] = 0; + + /* get VLAN information + VLAN index + .1.3.6.1.4.1.1916.1.2.1.2.1.1 + EXTREME-VLAN-MIB::extremeVlanIfIndex. = index + VLAN name + .1.3.6.1.4.1.1916.1.2.1.2.1.2 + EXTREME-VLAN-MIB::extremeVlanIfDescr. = description + VLAN ID + .1.3.6.1.4.1.1916.1.2.1.2.1.10 + EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id + */ + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.2', $device); + $device['vlans_total'] = cacti_sizeof($vlan_ids); + mactrack_debug('There are '.cacti_sizeof($vlan_ids).' VLANS.'); + + /* get the ifIndexes for the device + .1.3.6.1.2.1.2.2.1.1 + RFC1213-MIB::ifIndex. = index + .1.3.6.1.2.1.2.2.1.2 + RFC1213-MIB::ifDescr. = description + .1.3.6.1.2.1.2.2.1.3 + RFC1213-MIB::ifType. = type (6=ether) + .1.3.6.1.2.1.31.1.1.1.1 + IF-MIB::ifName. = name + .1.3.6.1.2.1.31.1.1.1.18 + IF-MIB::ifAlias. = alias + */ + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); + + mactrack_debug('ifInterfaces assembly complete.'); + + // get VLAN details + $i = 0; + foreach ($vlan_ids as $vlan_index => $vlan_id) { + $active_vlans[$i]['vlan_id'] = $vlan_id; + $active_vlans[$i]['vlan_name'] = $vlan_names[$vlan_index]; + ++$active_vlans; + mactrack_debug('VLAN ID = '.$active_vlans[$i]['vlan_id'].' VLAN Name = '.$active_vlans[$i]['vlan_name']); + ++$i; + } + + if (cacti_sizeof($active_vlans) > 0) { + // get the port status information + // get port_number and MAC addr + /*extremeXOS + addr mac + .1.3.6.1.4.1.1916.1.16.4.1.1 + EXTREME-BASE-MIB::extremeFdb.4.1.1..= hex MAC + index du vlan ? + .1.3.6.1.4.1.1916.1.16.4.1.2 + EXTREME-BASE-MIB::extremeFdb.4.1.2..=vlanid + index du port + .1.3.6.1.4.1.1916.1.16.4.1.3 + EXTREME-BASE-MIB::extremeFdb.4.1.3..=port id + status + .1.3.6.1.4.1.1916.1.16.4.1.4 + EXTREME-BASE-MIB::extremeFdb.4.1.4..= 3 learned + + extremeware + .1.3.6.1.4.1.1916.1.16.1.1.3 + EXTREME-FDB-MIB::extremeFdbMacFdbMacAddress.. = mac + .1.3.6.1.4.1.1916.1.16.1.1.4 + EXTREME-FDB-MIB::extremeFdbMacFdbPortIfIndex.. = index du port + .1.3.6.1.4.1.1916.1.16.1.1.5 + EXTREME-FDB-MIB::extremeFdbMacFdbStatus.. = 3 learned + */ + if ($extremeware) { + $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.3', $device); + $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.4', $device); + $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.5', $device); + } else { + $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.1', $device); + $mac_vlan_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.2', $device); + $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.3', $device); + $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.4', $device); + } + + $port_array = []; + + foreach ($mac_addr_list as $mac_key => $mac_addr) { + // check if mac addr is 'learned' or 'mgnt' + if (isset($mac_status_list[$mac_key]) and (('3' == $mac_status_list[$mac_key]) || ('5' == $mac_status_list[$mac_key]))) { + $ifIndex = $mac_port_list[$mac_key]; + $ifType = $ifInterfaces[$ifIndex]['ifType']; + // $ifType = $ifTypes[$ifIndex]; + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + if ($extremeware) { + $vlanid = substr($mac_key, 0, strpos($mac_key, '.')); + $new_port_array['vlan_id'] = $vlan_ids[$vlanid]; + $new_port_array['vlan_name'] = $vlan_names[$vlanid]; + } else { + $new_port_array['vlan_id'] = $vlan_ids[$mac_vlan_list[$mac_key]]; + $new_port_array['vlan_name'] = $vlan_names[$mac_vlan_list[$mac_key]]; + } + + // $new_port_array['port_number'] = $ifIndex; + // $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifName']; + $new_port_array['port_number'] = $ifInterfaces[$ifIndex]['ifName']; + $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifAlias']; + $new_port_array['mac_address'] = xform_mac_address($mac_addr_list[$mac_key]); + $ifInterfaces[$ifIndex]['Used'] = 1; + $port_array[] = $new_port_array; + + mactrack_debug('VLAN: '.$new_port_array['vlan_id'].', ' + .'NAME: '.$new_port_array['vlan_name'].', ' + .'PORT: '.$ifIndex.', ' + .'NAME: '.$new_port_array['port_name'].', ' + .'MAC: '.$new_port_array['mac_address']); + } + } + } + + $device['ports_total'] = cacti_sizeof($ifInterfaces); + $device['ports_active'] = 0; + + foreach ($ifInterfaces as $interface) { + if (isset($interface['Used'])) { + ++$device['ports_active']; + } + } + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } - /* get_extreme_arp_table - This function reads a devices ARP table for a site and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_extreme_arp_table($site, &$device, $extremeware = false) { - global $debug, $scan_date; -/* -EXTREME-FDB-MIB::extremeFdbIpFdbIPAddress : The IP Address of the IP FDB entry. -.1.3.6.1.4.1.1916.1.16.2.1.2 -EXTREME-FDB-MIB::extremeFdbIpFdbMacAddress : The MAC address corresponding to the IP Address. -.1.3.6.1.4.1.1916.1.16.2.1.3 -EXTREME-FDB-MIB::extremeFdbIpFdbVlanIfIndex : The ifIndex of the Vlan on which this ip is learned. -.1.3.6.1.4.1.1916.1.16.2.1.4 -EXTREME-FDB-MIB::extremeFdbIpFdbPortIfIndex : The IfIndex of the port on which this entry was learned. -.1.3.6.1.4.1.1916.1.16.2.1.5 -EXTREME-VLAN-MIB::extremeVlanIfIndex. = index -.1.3.6.1.4.1.1916.1.2.1.2.1.1 -EXTREME-VLAN-MIB::extremeVlanIfDescr. = description -.1.3.6.1.4.1.1916.1.2.1.2.1.2 -EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id -.1.3.6.1.4.1.1916.1.2.1.2.1.10 -BRIDGE-MIB::dot1dBasePortIfIndex : get Ifindex from extremeFdbIpFdbPortIfIndex -.1.3.6.1.2.1.17.1.4.1.2 -IF-MIB::ifName : get name of port from IfIndex -.1.3.6.1.2.1.31.1.1.1.1 -*/ - if ($extremeware) { // for extremeware use standard apr table + ifDescr for interface name - /* get the atifIndexes for the device */ - $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); - $atEntries = array(); - - if (cacti_sizeof($atifIndexes)) { - mactrack_debug('atifIndexes data collection complete'); - $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device, true); - mactrack_debug('atPhysAddress data collection complete'); - $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device, true); - mactrack_debug('atNetAddress data collection complete'); - $ifDescr = xform_stripped_oid('.1.3.6.1.2.1.2.2.1.2', $device); - mactrack_debug('ifDescr data collection complete'); - } - $i = 0; - if (cacti_sizeof($atifIndexes)) { - foreach($atifIndexes as $key => $atifIndex) { - $atEntries[$i]['atifIndex'] = $ifDescr[$atifIndex]; - $atEntries[$i]['atPhysAddress'] = xform_mac_address($atPhysAddress[$key]); - $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$key]); - $i++; - } - } - } else { - /* get the atifIndexes for the device */ - $FdbPortIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.5', $device); - $atEntries = array(); - - if (cacti_sizeof($FdbPortIfIndex)) { - mactrack_debug('FdbPortIfIndex data collection complete'); - $FdbMacAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.3', $device, true); - mactrack_debug('FdbMacAddress data collection complete'); - $FdbIPAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.2', $device); - mactrack_debug('FdbIPAddress data collection complete'); - $FdbVlanIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.4', $device); - mactrack_debug('FdbVlanIfIndex data collection complete'); - $VlanIfVlanId = xform_stripped_oid('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); - mactrack_debug('VlanIfVlanId data collection complete'); - $BasePortIfIndex = xform_stripped_oid('.1.3.6.1.2.1.17.1.4.1.2', $device); - mactrack_debug('BasePortIfIndex data collection complete'); - $ifName = xform_stripped_oid('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifName data collection complete'); - } - - $i = 0; - if (cacti_sizeof($FdbPortIfIndex)) { - foreach($FdbPortIfIndex as $key => $PortIndex) { - $atEntries[$i]['atifIndex'] = $ifName[$BasePortIfIndex[$PortIndex]] . ', vlan:' . $VlanIfVlanId[$FdbVlanIfIndex[$key]]; - $atEntries[$i]['atPhysAddress'] = xform_mac_address($FdbMacAddress[$key]); - $atEntries[$i]['atNetAddress'] = xform_net_address($FdbIPAddress[$key]); - $i++; - } - } - - mactrack_debug('atEntries assembly complete.'); - } - - /* output details to database */ - if (cacti_sizeof($atEntries)) { - $sql = array(); - - foreach($atEntries as $atEntry) { - $sql[] = '(' . - $device['site_id'] . ', ' . - $device['device_id'] . ', ' . - db_qstr($device['hostname']) . ', ' . - db_qstr($device['device_name']) . ', ' . - db_qstr($atEntry['atifIndex']) . ', ' . - db_qstr($atEntry['atPhysAddress']) . ', ' . - db_qstr($atEntry['atNetAddress']) . ', ' . - db_qstr($scan_date) . ')'; - } - - if (cacti_sizeof($sql)) { - db_execute('REPLACE INTO mac_track_ips +function get_extreme_arp_table($site, &$device, $extremeware = false) +{ + global $debug, $scan_date; + /* + EXTREME-FDB-MIB::extremeFdbIpFdbIPAddress : The IP Address of the IP FDB entry. + .1.3.6.1.4.1.1916.1.16.2.1.2 + EXTREME-FDB-MIB::extremeFdbIpFdbMacAddress : The MAC address corresponding to the IP Address. + .1.3.6.1.4.1.1916.1.16.2.1.3 + EXTREME-FDB-MIB::extremeFdbIpFdbVlanIfIndex : The ifIndex of the Vlan on which this ip is learned. + .1.3.6.1.4.1.1916.1.16.2.1.4 + EXTREME-FDB-MIB::extremeFdbIpFdbPortIfIndex : The IfIndex of the port on which this entry was learned. + .1.3.6.1.4.1.1916.1.16.2.1.5 + EXTREME-VLAN-MIB::extremeVlanIfIndex. = index + .1.3.6.1.4.1.1916.1.2.1.2.1.1 + EXTREME-VLAN-MIB::extremeVlanIfDescr. = description + .1.3.6.1.4.1.1916.1.2.1.2.1.2 + EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id + .1.3.6.1.4.1.1916.1.2.1.2.1.10 + BRIDGE-MIB::dot1dBasePortIfIndex : get Ifindex from extremeFdbIpFdbPortIfIndex + .1.3.6.1.2.1.17.1.4.1.2 + IF-MIB::ifName : get name of port from IfIndex + .1.3.6.1.2.1.31.1.1.1.1 + */ + if ($extremeware) { // for extremeware use standard apr table + ifDescr for interface name + // get the atifIndexes for the device + $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); + $atEntries = []; + + if (cacti_sizeof($atifIndexes)) { + mactrack_debug('atifIndexes data collection complete'); + $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device, true); + mactrack_debug('atPhysAddress data collection complete'); + $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device, true); + mactrack_debug('atNetAddress data collection complete'); + $ifDescr = xform_stripped_oid('.1.3.6.1.2.1.2.2.1.2', $device); + mactrack_debug('ifDescr data collection complete'); + } + $i = 0; + if (cacti_sizeof($atifIndexes)) { + foreach ($atifIndexes as $key => $atifIndex) { + $atEntries[$i]['atifIndex'] = $ifDescr[$atifIndex]; + $atEntries[$i]['atPhysAddress'] = xform_mac_address($atPhysAddress[$key]); + $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$key]); + ++$i; + } + } + } else { + // get the atifIndexes for the device + $FdbPortIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.5', $device); + $atEntries = []; + + if (cacti_sizeof($FdbPortIfIndex)) { + mactrack_debug('FdbPortIfIndex data collection complete'); + $FdbMacAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.3', $device, true); + mactrack_debug('FdbMacAddress data collection complete'); + $FdbIPAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.2', $device); + mactrack_debug('FdbIPAddress data collection complete'); + $FdbVlanIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.4', $device); + mactrack_debug('FdbVlanIfIndex data collection complete'); + $VlanIfVlanId = xform_stripped_oid('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); + mactrack_debug('VlanIfVlanId data collection complete'); + $BasePortIfIndex = xform_stripped_oid('.1.3.6.1.2.1.17.1.4.1.2', $device); + mactrack_debug('BasePortIfIndex data collection complete'); + $ifName = xform_stripped_oid('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifName data collection complete'); + } + + $i = 0; + if (cacti_sizeof($FdbPortIfIndex)) { + foreach ($FdbPortIfIndex as $key => $PortIndex) { + $atEntries[$i]['atifIndex'] = $ifName[$BasePortIfIndex[$PortIndex]].', vlan:'.$VlanIfVlanId[$FdbVlanIfIndex[$key]]; + $atEntries[$i]['atPhysAddress'] = xform_mac_address($FdbMacAddress[$key]); + $atEntries[$i]['atNetAddress'] = xform_net_address($FdbIPAddress[$key]); + ++$i; + } + } + + mactrack_debug('atEntries assembly complete.'); + } + + // output details to database + if (cacti_sizeof($atEntries)) { + $sql = []; + + foreach ($atEntries as $atEntry) { + $sql[] = '(' + .$device['site_id'].', ' + .$device['device_id'].', ' + .db_qstr($device['hostname']).', ' + .db_qstr($device['device_name']).', ' + .db_qstr($atEntry['atifIndex']).', ' + .db_qstr($atEntry['atPhysAddress']).', ' + .db_qstr($atEntry['atNetAddress']).', ' + .db_qstr($scan_date).')'; + } + + if (cacti_sizeof($sql)) { + db_execute('REPLACE INTO mac_track_ips (site_id, device_id, hostname, device_name, port_number, mac_address,ip_address,scan_date) - VALUES ' . implode(', ', $sql)); - } - } - - /* save ip information for the device */ - $device['ips_total'] = cacti_sizeof($atEntries); - db_execute_prepared('UPDATE mac_track_devices + VALUES '.implode(', ', $sql)); + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($atEntries); + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - array($device['ips_total'], $device['device_id'])); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete: nb IP=' . cacti_sizeof($atEntries) . '.'); + mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete: nb IP='.cacti_sizeof($atEntries).'.'); } - diff --git a/lib/mactrack_foundry.php b/lib/mactrack_foundry.php index 231ddd9d..d22376d1 100644 --- a/lib/mactrack_foundry.php +++ b/lib/mactrack_foundry.php @@ -1,4 +1,5 @@ = 6) && ($ifType <= 9)) { - $device['ports_total']++; - } - } - } - mactrack_debug('Total Ports = ' . $device['ports_total']); - - /* calculate the number of trunk ports */ - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - if (($ifInterfaces[$ifIndex]['trunkPortState'] == 1) && - ($ifInterfaces[$ifIndex]['ifVlanId'] == 0)) { - $device['ports_trunk']++; - } - } - } - mactrack_debug('Total Trunk Ports = ' . $device['ports_trunk']); - - /* get VLAN details */ - $i = 0; - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_id => $vlan_name) { - $active_vlans[$i]['vlan_id'] = $vlan_id; - $active_vlans[$i]['vlan_name'] = $vlan_name; - $active_vlans++; - mactrack_debug('VLAN ID = ' . $active_vlans[$i]['vlan_id'] . ' VLAN Name = ' . $active_vlans[$i]['vlan_name']); - $i++; - } - } - - if (cacti_sizeof($active_vlans)) { - /* get the port status information */ - $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); - $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.6.1.1', $device); - - $i = 0; - $j = 0; - $port_array = array(); - - if (cacti_sizeof($port_results)) { - foreach ($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - $ifType = $ifTypes[$ifIndex]; - $ifName = $ifNames[$ifIndex]; - $portName = $ifName; - $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; - mactrack_debug('Port Number = ' . $ifIndex . ' Type = ' . $ifType . ' Name = ' . $ifName . ' Port Name = ' . $portName . ' Trunk Status = ' . $portTrunkStatus); - - /* only output legitimate end user ports */ - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); - $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_ids, $port_array[$i]['vlan_id']); - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - - mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' . - 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' . - 'PORT: ' . $ifIndex . ', ' . - 'NAME: ' . $port_array[$i]['port_name'] . ', ' . - 'MAC: ' . $port_array[$i]['mac_address']); - - $i++; - } - - $j++; - } - - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - $ifInterfaces[$indexes[$i]]['ifType'] = mactrack_strip_alpha($ifInterfaces[$indexes[$i]]['ifType']); - - mactrack_debug($ifInterfaces[$indexes[$i]]['ifType']); - - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <=9)) || - ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { - if ($port_info == 1) { - $device['ports_active']++; - } - - $i++; - } - } - } - - $device['ports_active'] = $device['ports_active'] - $device['ports_trunk']; - - /* get IP Addresses */ - $gateway = cacti_snmp_get($device['hostname'], $device['snmp_readstring'], '.1.3.6.1.4.1.1991.1.1.2.1.10.0', - $device['snmp_version'], $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - mactrack_debug('INFO: GATEWAY: ' . $gateway); - - /* display completion message */ - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } - } else { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_foundry_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + $device['ports_dual_mode'] = 0; + + // get VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.7.1.21', $device); + + // get VLAN Trunk status + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.3.5.1.4', $device); + $device['vlans_total'] = cacti_sizeof($vlan_trunkstatus); + mactrack_debug('VLAN data collected. There are '.cacti_sizeof($vlan_ids).' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get the ifTypes for the device + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + mactrack_debug('ifTypes data collection complete.'); + + // get the ifNames for the device + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete.'); + + // get ports that happen to be link ports + $link_ports = get_link_port_status($device); + mactrack_debug('ipAddrTable scanning for link ports data collection complete.'); + + // get ports that have no vlan id (non dual-mode) + $port_dualmode = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.3.5.1.24', $device); + mactrack_debug('ifVlanId data collection complete.'); + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); + $ifInterfaces[$ifIndex]['ifType'] = $ifTypes[$ifIndex]; + $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); + $ifInterfaces[$ifIndex]['trunkPortState'] = mactrack_arr_key($vlan_trunkstatus, $ifIndex); + $ifInterfaces[$ifIndex]['ifVlanId'] = mactrack_arr_key($port_dualmode, $ifIndex); + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // calculate the number of end user ports + if (cacti_sizeof($ifTypes)) { + foreach ($ifTypes as $ifType) { + if (($ifType >= 6) && ($ifType <= 9)) { + ++$device['ports_total']; + } + } + } + mactrack_debug('Total Ports = '.$device['ports_total']); + + // calculate the number of trunk ports + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + if ((1 == $ifInterfaces[$ifIndex]['trunkPortState']) + && (0 == $ifInterfaces[$ifIndex]['ifVlanId'])) { + ++$device['ports_trunk']; + } + } + } + mactrack_debug('Total Trunk Ports = '.$device['ports_trunk']); + + // get VLAN details + $i = 0; + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_id => $vlan_name) { + $active_vlans[$i]['vlan_id'] = $vlan_id; + $active_vlans[$i]['vlan_name'] = $vlan_name; + ++$active_vlans; + mactrack_debug('VLAN ID = '.$active_vlans[$i]['vlan_id'].' VLAN Name = '.$active_vlans[$i]['vlan_name']); + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + // get the port status information + $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); + $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.6.1.1', $device); + + $i = 0; + $j = 0; + $port_array = []; + + if (cacti_sizeof($port_results)) { + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + $ifType = $ifTypes[$ifIndex]; + $ifName = $ifNames[$ifIndex]; + $portName = $ifName; + $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; + mactrack_debug('Port Number = '.$ifIndex.' Type = '.$ifType.' Name = '.$ifName.' Port Name = '.$portName.' Trunk Status = '.$portTrunkStatus); + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); + $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_ids, $port_array[$i]['vlan_id']); + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + + mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' + .'NAME: '.$port_array[$i]['vlan_name'].', ' + .'PORT: '.$ifIndex.', ' + .'NAME: '.$port_array[$i]['port_name'].', ' + .'MAC: '.$port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + $ifInterfaces[$indexes[$i]]['ifType'] = mactrack_strip_alpha($ifInterfaces[$indexes[$i]]['ifType']); + + mactrack_debug($ifInterfaces[$indexes[$i]]['ifType']); + + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { + if (1 == $port_info) { + ++$device['ports_active']; + } + + ++$i; + } + } + } + + $device['ports_active'] = $device['ports_active'] - $device['ports_trunk']; + + // get IP Addresses + $gateway = cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.4.1.1991.1.1.2.1.10.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + mactrack_debug('INFO: GATEWAY: '.$gateway); + + // display completion message + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } + } else { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } - diff --git a/lib/mactrack_functions.php b/lib/mactrack_functions.php index d6cf0ea8..aefe7aa8 100644 --- a/lib/mactrack_functions.php +++ b/lib/mactrack_functions.php @@ -22,106 +22,120 @@ +-------------------------------------------------------------------------+ */ -/* register these scanning functions */ +// register these scanning functions global $mactrack_scanning_functions; -if (!isset($mactrack_scanning_functions)) { $mactrack_scanning_functions = array(); } +if (!isset($mactrack_scanning_functions)) { + $mactrack_scanning_functions = []; +} array_push($mactrack_scanning_functions, 'get_generic_dot1q_switch_ports', 'get_generic_switch_ports', 'get_generic_wireless_ports'); global $mactrack_scanning_functions_ip; -if (!isset($mactrack_scanning_functions_ip)) { $mactrack_scanning_functions_ip = array(); } +if (!isset($mactrack_scanning_functions_ip)) { + $mactrack_scanning_functions_ip = []; +} array_push($mactrack_scanning_functions_ip, 'get_standard_arp_table', 'get_netscreen_arp_table'); global $mactrack_device_status; if (!isset($mactrack_device_status)) { - $mactrack_device_status = array( - 1 => __('Idle', 'mactrack'), - 2 => __('Running', 'mactrack'), - 3 => __('No method', 'mactrack'), - 4 => __('Authentication Success', 'mactrack'), - 5 => __('Authentication Failed', 'mactrack'), - 6 => __('Authorization Success', 'mactrack'), - 7 => __('Authorization Failed', 'mactrack') - ); + $mactrack_device_status = [ + 1 => __('Idle', 'mactrack'), + 2 => __('Running', 'mactrack'), + 3 => __('No method', 'mactrack'), + 4 => __('Authentication Success', 'mactrack'), + 5 => __('Authentication Failed', 'mactrack'), + 6 => __('Authorization Success', 'mactrack'), + 7 => __('Authorization Failed', 'mactrack'), + ]; } -function mactrack_debug($message) { - global $debug, $web, $config; +function mactrack_debug($message) +{ + global $debug, $web, $config; - $print_output=!(isset($web) && $web); - if (isset($web) && $web && is_string($message) && !substr_count($message, 'SQL')) { - print($message . '
'); - } + $print_output = !(isset($web) && $web); + if (isset($web) && $web && is_string($message) && !substr_count($message, 'SQL')) { + echo $message.'
'; + } - $debug_level=POLLER_VERBOSITY_HIGH; - if (substr_count($message, 'ERROR:') || $debug) { - $debug_level=POLLER_VERBOSITY_LOW; - } + $debug_level = POLLER_VERBOSITY_HIGH; + if (substr_count($message, 'ERROR:') || $debug) { + $debug_level = POLLER_VERBOSITY_LOW; + } - if (!preg_match('~(\w): .*~',$message)) { - $message = 'DEBUG: ' . $message; - } + if (!preg_match('~(\w): .*~', $message)) { + $message = 'DEBUG: '.$message; + } - cacti_log($message, $print_output, 'MACTRACK', $debug_level); + cacti_log($message, $print_output, 'MACTRACK', $debug_level); } -function mactrack_rebuild_scanning_funcs() { - global $config, $mactrack_scanning_functions_ip, $mactrack_scanning_functions, $mactrack_scanning_functions_dot1x; +function mactrack_rebuild_scanning_funcs() +{ + global $config, $mactrack_scanning_functions_ip, $mactrack_scanning_functions, $mactrack_scanning_functions_dot1x; - if (defined('CACTI_BASE_PATH')) { - $config['base_path'] = CACTI_BASE_PATH; - } + if (defined('CACTI_BASE_PATH')) { + $config['base_path'] = CACTI_BASE_PATH; + } - db_execute('TRUNCATE TABLE mac_track_scanning_functions'); + db_execute('TRUNCATE TABLE mac_track_scanning_functions'); - include_once($config['base_path'] . '/plugins/mactrack/lib/mactrack_vendors.php'); + include_once $config['base_path'].'/plugins/mactrack/lib/mactrack_vendors.php'; - /* store the list of registered mactrack scanning functions */ - db_execute("REPLACE INTO mac_track_scanning_functions + // store the list of registered mactrack scanning functions + db_execute("REPLACE INTO mac_track_scanning_functions (scanning_function,type) VALUES ('Not Applicable - Router', '1')"); - if (isset($mactrack_scanning_functions)) { - foreach($mactrack_scanning_functions as $scanning_function) { - db_execute_prepared('REPLACE INTO mac_track_scanning_functions + if (isset($mactrack_scanning_functions)) { + foreach ($mactrack_scanning_functions as $scanning_function) { + db_execute_prepared( + 'REPLACE INTO mac_track_scanning_functions (scanning_function, type) VALUES (?, ?)', - array($scanning_function, 1)); - } - } + [$scanning_function, 1] + ); + } + } - db_execute("REPLACE INTO mac_track_scanning_functions + db_execute("REPLACE INTO mac_track_scanning_functions (scanning_function,type) VALUES ('Not Applicable - Switch/Hub', '2')"); - if (isset($mactrack_scanning_functions_ip)) { - foreach($mactrack_scanning_functions_ip as $scanning_function) { - db_execute_prepared('REPLACE INTO mac_track_scanning_functions + if (isset($mactrack_scanning_functions_ip)) { + foreach ($mactrack_scanning_functions_ip as $scanning_function) { + db_execute_prepared( + 'REPLACE INTO mac_track_scanning_functions (scanning_function, type) VALUES (?, ?)', - array($scanning_function, 2)); - } - } + [$scanning_function, 2] + ); + } + } - db_execute("REPLACE INTO mac_track_scanning_functions + db_execute("REPLACE INTO mac_track_scanning_functions (scanning_function,type) VALUES ('Not Applicable', '3')"); - if (isset($mactrack_scanning_functions_dot1x)) { - foreach($mactrack_scanning_functions_dot1x as $scanning_function) { - db_execute_prepared('REPLACE INTO mac_track_scanning_functions + if (isset($mactrack_scanning_functions_dot1x)) { + foreach ($mactrack_scanning_functions_dot1x as $scanning_function) { + db_execute_prepared( + 'REPLACE INTO mac_track_scanning_functions (scanning_function, type) VALUES (?, ?)', - array($scanning_function, 3)); - } - } + [$scanning_function, 3] + ); + } + } } -function mactrack_strip_alpha($string = '') { - return trim($string, 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ()[]{}'); +function mactrack_strip_alpha($string = '') +{ + return trim($string, 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ()[]{}'); } -function mactrack_check_user_realm($realm_id) { - return is_realm_allowed($realm_id); +function mactrack_check_user_realm($realm_id) +{ + return is_realm_allowed($realm_id); } /* valid_snmp_device - This function validates that the device is reachable via snmp. @@ -129,424 +143,511 @@ function mactrack_check_user_realm($realm_id) { attempts to find the correct read string and then updates several system information variable. it returns the status of the host (up=true, down=false) */ -function valid_snmp_device(&$device) { - global $config; - - /* initialize variable */ - $host_up = false; - $device['snmp_status'] = HOST_DOWN; - - /* force php to return numeric oid's */ - cacti_oid_numeric_format(); - - /* if the first read did not work, loop until found */ - $snmp_sysObjectID = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); - - if ($snmp_sysObjectID != '' && - $snmp_sysObjectID != 'U' && - (!substr_count($snmp_sysObjectID, 'No Such Object')) && - (!substr_count($snmp_sysObjectID, 'Error In'))) { - $snmp_sysObjectID = trim(str_replace('"','', $snmp_sysObjectID)); - $host_up = true; - $device['snmp_status'] = HOST_UP; - } else { - /* loop through the default and then other common for the correct answer */ - $snmp_options = db_fetch_assoc_prepared('SELECT * from mac_track_snmp_items WHERE snmp_id = ? ORDER BY sequence', array($device['snmp_options'])); - - if (cacti_sizeof($snmp_options)) { - foreach($snmp_options as $snmp_option) { - # update $device for later db update via db_update_device_status - $device['snmp_readstring'] = $snmp_option['snmp_readstring']; - $device['snmp_version'] = $snmp_option['snmp_version']; - $device['snmp_username'] = $snmp_option['snmp_username']; - $device['snmp_password'] = $snmp_option['snmp_password']; - $device['snmp_auth_protocol'] = $snmp_option['snmp_auth_protocol']; - $device['snmp_priv_passphrase'] = $snmp_option['snmp_priv_passphrase']; - $device['snmp_priv_protocol'] = $snmp_option['snmp_priv_protocol']; - $device['snmp_context'] = $snmp_option['snmp_context']; - $device['snmp_port'] = $snmp_option['snmp_port']; - $device['snmp_timeout'] = $snmp_option['snmp_timeout']; - $device['snmp_retries'] = $snmp_option['snmp_retries']; - - $snmp_sysObjectID = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.2.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries']); - - $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); - - if ($snmp_sysObjectID != '' && - $snmp_sysObjectID != 'U' && - (!substr_count($snmp_sysObjectID, 'No Such Object')) && - (!substr_count($snmp_sysObjectID, 'Error In'))) { - $snmp_sysObjectID = trim(str_replace("'", '', $snmp_sysObjectID)); - $device['snmp_readstring'] = $snmp_option['snmp_readstring']; - $device['snmp_status'] = HOST_UP; - $host_up = true; - # update cacti device, if required - sync_mactrack_to_cacti($device); - # update to mactrack itself is done by db_update_device_status in mactrack_scanner.php - # TODO: if db_update_device_status would use api_mactrack_device_save, there would be no need to call sync_mactrack_to_cacti here - # but currently the parameter set doesn't match - mactrack_debug('Result found on Option Set (' . $snmp_option['snmp_id'] . ') Sequence (' . $snmp_option['sequence'] . '): ' . $snmp_sysObjectID); - break; # no need to continue if we have a match - } else { - $device['snmp_status'] = HOST_DOWN; - $host_up = false; - } - } - } - } - - if ($host_up) { - $device['snmp_sysObjectID'] = $snmp_sysObjectID; - - /* get system name */ - $snmp_sysName = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.5.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($snmp_sysName != '') { - $snmp_sysName = trim(strtr($snmp_sysName,'"',' ')); - $device['snmp_sysName'] = $snmp_sysName; - } - - /* get system location */ - $snmp_sysLocation = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.6.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($snmp_sysLocation != '') { - $snmp_sysLocation = trim(strtr($snmp_sysLocation,'"',' ')); - $device['snmp_sysLocation'] = $snmp_sysLocation; - } - - /* get system contact */ - $snmp_sysContact = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.4.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($snmp_sysContact != '') { - $snmp_sysContact = trim(strtr($snmp_sysContact,'"',' ')); - $device['snmp_sysContact'] = $snmp_sysContact; - } - - /* get system description */ - $snmp_sysDescr = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.1.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($snmp_sysDescr != '') { - $snmp_sysDescr = trim(strtr($snmp_sysDescr,'"',' ')); - $device['snmp_sysDescr'] = $snmp_sysDescr; - } - - /* get system uptime */ - $snmp_sysUptime = @cacti_snmp_get($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.1.3.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - if ($snmp_sysUptime != '') { - $snmp_sysUptime = trim(strtr($snmp_sysUptime,'"',' ')); - $device['snmp_sysUptime'] = $snmp_sysUptime; - } - } - - return $host_up; +function valid_snmp_device(&$device) +{ + global $config; + + // initialize variable + $host_up = false; + $device['snmp_status'] = HOST_DOWN; + + // force php to return numeric oid's + cacti_oid_numeric_format(); + + // if the first read did not work, loop until found + $snmp_sysObjectID = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); + + if ('' != $snmp_sysObjectID + && 'U' != $snmp_sysObjectID + && (!substr_count($snmp_sysObjectID, 'No Such Object')) + && (!substr_count($snmp_sysObjectID, 'Error In'))) { + $snmp_sysObjectID = trim(str_replace('"', '', $snmp_sysObjectID)); + $host_up = true; + $device['snmp_status'] = HOST_UP; + } else { + // loop through the default and then other common for the correct answer + $snmp_options = db_fetch_assoc_prepared('SELECT * from mac_track_snmp_items WHERE snmp_id = ? ORDER BY sequence', [$device['snmp_options']]); + + if (cacti_sizeof($snmp_options)) { + foreach ($snmp_options as $snmp_option) { + // update $device for later db update via db_update_device_status + $device['snmp_readstring'] = $snmp_option['snmp_readstring']; + $device['snmp_version'] = $snmp_option['snmp_version']; + $device['snmp_username'] = $snmp_option['snmp_username']; + $device['snmp_password'] = $snmp_option['snmp_password']; + $device['snmp_auth_protocol'] = $snmp_option['snmp_auth_protocol']; + $device['snmp_priv_passphrase'] = $snmp_option['snmp_priv_passphrase']; + $device['snmp_priv_protocol'] = $snmp_option['snmp_priv_protocol']; + $device['snmp_context'] = $snmp_option['snmp_context']; + $device['snmp_port'] = $snmp_option['snmp_port']; + $device['snmp_timeout'] = $snmp_option['snmp_timeout']; + $device['snmp_retries'] = $snmp_option['snmp_retries']; + + $snmp_sysObjectID = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); + + if ('' != $snmp_sysObjectID + && 'U' != $snmp_sysObjectID + && (!substr_count($snmp_sysObjectID, 'No Such Object')) + && (!substr_count($snmp_sysObjectID, 'Error In'))) { + $snmp_sysObjectID = trim(str_replace("'", '', $snmp_sysObjectID)); + $device['snmp_readstring'] = $snmp_option['snmp_readstring']; + $device['snmp_status'] = HOST_UP; + $host_up = true; + // update cacti device, if required + sync_mactrack_to_cacti($device); + // update to mactrack itself is done by db_update_device_status in mactrack_scanner.php + // TODO: if db_update_device_status would use api_mactrack_device_save, there would be no need to call sync_mactrack_to_cacti here + // but currently the parameter set doesn't match + mactrack_debug('Result found on Option Set ('.$snmp_option['snmp_id'].') Sequence ('.$snmp_option['sequence'].'): '.$snmp_sysObjectID); + + break; // no need to continue if we have a match + } + $device['snmp_status'] = HOST_DOWN; + $host_up = false; + } + } + } + + if ($host_up) { + $device['snmp_sysObjectID'] = $snmp_sysObjectID; + + // get system name + $snmp_sysName = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.5.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $snmp_sysName) { + $snmp_sysName = trim(strtr($snmp_sysName, '"', ' ')); + $device['snmp_sysName'] = $snmp_sysName; + } + + // get system location + $snmp_sysLocation = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.6.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $snmp_sysLocation) { + $snmp_sysLocation = trim(strtr($snmp_sysLocation, '"', ' ')); + $device['snmp_sysLocation'] = $snmp_sysLocation; + } + + // get system contact + $snmp_sysContact = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $snmp_sysContact) { + $snmp_sysContact = trim(strtr($snmp_sysContact, '"', ' ')); + $device['snmp_sysContact'] = $snmp_sysContact; + } + + // get system description + $snmp_sysDescr = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.1.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $snmp_sysDescr) { + $snmp_sysDescr = trim(strtr($snmp_sysDescr, '"', ' ')); + $device['snmp_sysDescr'] = $snmp_sysDescr; + } + + // get system uptime + $snmp_sysUptime = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.3.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ('' != $snmp_sysUptime) { + $snmp_sysUptime = trim(strtr($snmp_sysUptime, '"', ' ')); + $device['snmp_sysUptime'] = $snmp_sysUptime; + } + } + + return $host_up; } /** * find_scanning_function - This function scans the mac_track_device_type database * for a valid scanning function and then returns an array with the current device * type and it's characteristics for the main mac_track_scanner function to call. + * + * @param mixed $device + * @param mixed $device_types */ -function find_scanning_function(&$device, &$device_types) { - /* scan all device_types to determine the function to call */ - if (cacti_sizeof($device_types)) { - foreach($device_types as $device_type) { - /* by default none match */ - $sysDescr_match = false; - $sysObjectID_match = false; - - /* search for a matching snmp_sysDescr */ - if (substr_count($device_type['sysDescr_match'], '*') > 0) { - /* need to assume mixed string */ - $parts = explode('*', $device_type['sysDescr_match']); - if (cacti_sizeof($parts)) { - foreach($parts as $part) { - if ($part != '') { - if (substr_count($device['snmp_sysDescr'],$part) > 0) { - $sysDescr_match = true; - } else { - $sysDescr_match = false; - } - } - } - } - } else { - if ($device_type['sysDescr_match'] == '') { - $sysDescr_match = true; - } else { - if (substr_count($device['snmp_sysDescr'], $device_type['sysDescr_match'])) { - $sysDescr_match = true; - } else { - $sysDescr_match = false; - } - } - } - - /* search for a matching snmp_sysObjectID*/ - /* need to assume mixed string */ - if (substr_count($device_type['sysObjectID_match'], '*') > 0) { - $parts = explode('*', $device_type['sysObjectID_match']); - if (cacti_sizeof($parts)) { - foreach($parts as $part) { - if ($part != '') { - if (substr_count($device['snmp_sysObjectID'],$part) > 0) { - $sysObjectID_match = true; - } else { - $sysObjectID_match = false; - } - } - } - } - } else { - if ($device_type['sysObjectID_match'] == '') { - $sysObjectID_match = true; - } else { - if (substr_count($device['snmp_sysObjectID'], $device_type['sysObjectID_match'])) { - $sysObjectID_match = true; - } else { - $sysObjectID_match = false; - } - } - } - - if (($sysObjectID_match == true) && ($sysDescr_match == true)) { - $device['device_type_id'] = $device_type['device_type_id']; - $device['scan_type'] = $device_type['device_type']; - return $device_type; - } - } - } - - return array(); +function find_scanning_function(&$device, &$device_types) +{ + // scan all device_types to determine the function to call + if (cacti_sizeof($device_types)) { + foreach ($device_types as $device_type) { + // by default none match + $sysDescr_match = false; + $sysObjectID_match = false; + + // search for a matching snmp_sysDescr + if (substr_count($device_type['sysDescr_match'], '*') > 0) { + // need to assume mixed string + $parts = explode('*', $device_type['sysDescr_match']); + if (cacti_sizeof($parts)) { + foreach ($parts as $part) { + if ('' != $part) { + if (substr_count($device['snmp_sysDescr'], $part) > 0) { + $sysDescr_match = true; + } else { + $sysDescr_match = false; + } + } + } + } + } else { + if ('' == $device_type['sysDescr_match']) { + $sysDescr_match = true; + } else { + if (substr_count($device['snmp_sysDescr'], $device_type['sysDescr_match'])) { + $sysDescr_match = true; + } else { + $sysDescr_match = false; + } + } + } + + // search for a matching snmp_sysObjectID + // need to assume mixed string + if (substr_count($device_type['sysObjectID_match'], '*') > 0) { + $parts = explode('*', $device_type['sysObjectID_match']); + if (cacti_sizeof($parts)) { + foreach ($parts as $part) { + if ('' != $part) { + if (substr_count($device['snmp_sysObjectID'], $part) > 0) { + $sysObjectID_match = true; + } else { + $sysObjectID_match = false; + } + } + } + } + } else { + if ('' == $device_type['sysObjectID_match']) { + $sysObjectID_match = true; + } else { + if (substr_count($device['snmp_sysObjectID'], $device_type['sysObjectID_match'])) { + $sysObjectID_match = true; + } else { + $sysObjectID_match = false; + } + } + } + + if ((true == $sysObjectID_match) && (true == $sysDescr_match)) { + $device['device_type_id'] = $device_type['device_type_id']; + $device['scan_type'] = $device_type['device_type']; + + return $device_type; + } + } + } + + return []; } /** * port_list_to_array - Takes a text list of ports and builds a trimmed array of - * the resulting array. Returns the array + * the resulting array. Returns the array. + * + * @param mixed $port_list + * @param mixed $delimiter */ -function port_list_to_array($port_list, $delimiter = ':') { - $port_array = array(); - - if (read_config_option('mt_ignorePorts_delim') == '-1') { - /* find the delimiter */ - $t1 = cacti_sizeof(explode(':', $port_list)); - $t2 = cacti_sizeof(explode('|', $port_list)); - $t3 = cacti_sizeof(explode(' ', $port_list)); - - if ($t1 > $t2 && $t1 > $t3) { - $delimiter = ':'; - } elseif ($t2 > $t1 && $t2 > $t3) { - $delimiter = '|'; - } elseif ($t3 > $t1 && $t3 > $t2) { - $delimiter = ' '; - } - } else { - $delimiter = read_config_option('mt_ignorePorts_delim'); - } - - $ports = explode($delimiter, $port_list); - - if (cacti_sizeof($ports)) { - foreach ($ports as $port) { - array_push($port_array, trim($port)); - } - } - - return $port_array; +function port_list_to_array($port_list, $delimiter = ':') +{ + $port_array = []; + + if ('-1' == read_config_option('mt_ignorePorts_delim')) { + // find the delimiter + $t1 = cacti_sizeof(explode(':', $port_list)); + $t2 = cacti_sizeof(explode('|', $port_list)); + $t3 = cacti_sizeof(explode(' ', $port_list)); + + if ($t1 > $t2 && $t1 > $t3) { + $delimiter = ':'; + } elseif ($t2 > $t1 && $t2 > $t3) { + $delimiter = '|'; + } elseif ($t3 > $t1 && $t3 > $t2) { + $delimiter = ' '; + } + } else { + $delimiter = read_config_option('mt_ignorePorts_delim'); + } + + $ports = explode($delimiter, $port_list); + + if (cacti_sizeof($ports)) { + foreach ($ports as $port) { + array_push($port_array, trim($port)); + } + } + + return $port_array; } /** * get_standard_arp_table - This function reads a devices ARP table for a site and stores * the IP address and MAC address combinations in the mac_track_ips table. + * + * @param mixed $site + * @param mixed $device */ -function get_standard_arp_table($site, &$device) { - global $debug, $scan_date; - - $atEntries = array(); - - /* get the atifIndexes for the device */ - $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); - if (cacti_sizeof($atifIndexes)) { - mactrack_debug('atifIndexes data collection complete'); - $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device); - mactrack_debug('atPhysAddress data collection complete'); - $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device); - mactrack_debug('atNetAddress data collection complete'); - } else { - /* second attempt for Force10 Gear */ - $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.1', $device); - mactrack_debug('atifIndexes data collection complete'); - $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.2', $device, '', true); - mactrack_debug('atPhysAddress data collection complete'); - $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.3', $device); - mactrack_debug('atNetAddress data collection complete'); - } - - $atifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete. \'' . cacti_sizeof($atifNames) . '\' rows found!'); - - /* convert the mac address if necessary */ - $keys = array_keys($atPhysAddress); - $i = 0; - if (cacti_sizeof($atPhysAddress)) { - foreach($atPhysAddress as $atAddress) { - $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); - $i++; - } - } - mactrack_debug('atPhysAddress MAC Address Conversion Completed'); - - /* get the ifNames for the device */ - $keys = array_keys($atifIndexes); - $i = 0; - if (cacti_sizeof($atifIndexes)) { - foreach($atifIndexes as $atifIndex) { - $atEntries[$i]['atifName'] = isset($atifNames[$atifIndex]) ? $atifNames[$atifIndex]:''; - $atEntries[$i]['atPhysAddress'] = isset($atPhysAddress[$keys[$i]]) ? $atPhysAddress[$keys[$i]]:''; - $atEntries[$i]['atNetAddress'] = isset($atNetAddress[$keys[$i]]) ? xform_net_address($atNetAddress[$keys[$i]]):''; - $i++; - } - } - mactrack_debug('atEntries assembly complete.'); - - /* output details to database */ - if (cacti_sizeof($atEntries)) { - foreach($atEntries as $atEntry) { - /* check the mac_track_arp table if no IP address is found */ - if ($atEntry['atNetAddress'] == "") { - $atEntry['atNetAddress'] = db_check_for_ip($atEntry['atPhysAddress']); - mactrack_debug('atNetAddress ****:' . $atEntry['atPhysAddress'] . '(' . $atEntry['atNetAddress'] . ')'); - } - - db_execute_prepared('REPLACE INTO mac_track_ips +function get_standard_arp_table($site, &$device) +{ + global $debug, $scan_date; + + $atEntries = []; + + // get the atifIndexes for the device + $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); + if (cacti_sizeof($atifIndexes)) { + mactrack_debug('atifIndexes data collection complete'); + $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device); + mactrack_debug('atPhysAddress data collection complete'); + $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device); + mactrack_debug('atNetAddress data collection complete'); + } else { + // second attempt for Force10 Gear + $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.1', $device); + mactrack_debug('atifIndexes data collection complete'); + $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.2', $device, '', true); + mactrack_debug('atPhysAddress data collection complete'); + $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.3', $device); + mactrack_debug('atNetAddress data collection complete'); + } + + $atifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete. \''.cacti_sizeof($atifNames).'\' rows found!'); + + // convert the mac address if necessary + $keys = array_keys($atPhysAddress); + $i = 0; + if (cacti_sizeof($atPhysAddress)) { + foreach ($atPhysAddress as $atAddress) { + $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); + ++$i; + } + } + mactrack_debug('atPhysAddress MAC Address Conversion Completed'); + + // get the ifNames for the device + $keys = array_keys($atifIndexes); + $i = 0; + if (cacti_sizeof($atifIndexes)) { + foreach ($atifIndexes as $atifIndex) { + $atEntries[$i]['atifName'] = isset($atifNames[$atifIndex]) ? $atifNames[$atifIndex] : ''; + $atEntries[$i]['atPhysAddress'] = isset($atPhysAddress[$keys[$i]]) ? $atPhysAddress[$keys[$i]] : ''; + $atEntries[$i]['atNetAddress'] = isset($atNetAddress[$keys[$i]]) ? xform_net_address($atNetAddress[$keys[$i]]) : ''; + ++$i; + } + } + mactrack_debug('atEntries assembly complete.'); + + // output details to database + if (cacti_sizeof($atEntries)) { + foreach ($atEntries as $atEntry) { + // check the mac_track_arp table if no IP address is found + if ('' == $atEntry['atNetAddress']) { + $atEntry['atNetAddress'] = db_check_for_ip($atEntry['atPhysAddress']); + mactrack_debug('atNetAddress ****:'.$atEntry['atPhysAddress'].'('.$atEntry['atNetAddress'].')'); + } + + db_execute_prepared( + 'REPLACE INTO mac_track_ips (site_id, device_id, hostname, device_name, port_number, mac_address, ip_address, scan_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - array( - $device['site_id'], - $device['device_id'], - $device['hostname'], - $device['device_name'], - $atEntry['atifName'], - $atEntry['atPhysAddress'], - $atEntry['atNetAddress'], - $scan_date - ) - ); - } - } - - /* save ip information for the device */ - $device['ips_total'] = cacti_sizeof($atEntries); - db_execute_prepared('UPDATE mac_track_devices + [ + $device['site_id'], + $device['device_id'], + $device['hostname'], + $device['device_name'], + $atEntry['atifName'], + $atEntry['atPhysAddress'], + $atEntry['atNetAddress'], + $scan_date, + ] + ); + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($atEntries); + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - array($device['ips_total'], $device['device_id'])); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete'); + mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete'); } /** * build_InterfacesTable - This is a basic function that will scan Interfaces table * and return data. It also stores data in the mac_track_interfaces table. Some of the * data is also used for scanning purposes. + * + * @param mixed $device + * @param mixed $ifIndexes + * @param mixed $getLinkPorts + * @param mixed $getAlias */ -function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $getAlias = false) { - /* initialize the interfaces array */ - $ifInterfaces = array(); - - /* get the ifIndexes for the device */ - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete. \'' . cacti_sizeof($ifIndexes) . '\' rows found!'); - - $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); - if (cacti_sizeof($ifTypes)) { - foreach($ifTypes as $key => $value) { - if (!is_numeric($value)) { - $parts = explode('(', $value); - if (!empty($parts)) { - $piece = $parts[1]; - $ifTypes[$key] = str_replace(')', '', trim($piece)); - } else { - $ifTypes[$key] = 'N/A'; - } - } - } - } - mactrack_debug('ifTypes data collection complete. \'' . cacti_sizeof($ifTypes) . '\' rows found!'); - - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete. \'' . cacti_sizeof($ifNames) . '\' rows found!'); - - /* get ports names through use of ifAlias */ - if ($getAlias) { - $ifAliases = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); - mactrack_debug('ifAlias data collection complete. \'' . cacti_sizeof($ifAliases) . '\' rows found!'); - } - - /* get ports that happen to be link ports */ - if ($getLinkPorts) { - $link_ports = get_link_port_status($device); - mactrack_debug("ipAddrTable scanning for link ports data collection complete. '" . cacti_sizeof($link_ports) . "' rows found!"); - } - - /* required only for interfaces table */ - $db_data = db_fetch_assoc("SELECT * FROM mac_track_interfaces WHERE device_id='" . $device["device_id"] . "' ORDER BY ifIndex"); - - if (cacti_sizeof($db_data)) { - foreach($db_data as $interface) { - $db_interface[$interface["ifIndex"]] = $interface; - } - } - - /* mark all interfaces as not present */ - db_execute_prepared('UPDATE mac_track_interfaces +function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $getAlias = false) +{ + // initialize the interfaces array + $ifInterfaces = []; + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete. \''.cacti_sizeof($ifIndexes).'\' rows found!'); + + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + if (cacti_sizeof($ifTypes)) { + foreach ($ifTypes as $key => $value) { + if (!is_numeric($value)) { + $parts = explode('(', $value); + if (!empty($parts)) { + $piece = $parts[1]; + $ifTypes[$key] = str_replace(')', '', trim($piece)); + } else { + $ifTypes[$key] = 'N/A'; + } + } + } + } + mactrack_debug('ifTypes data collection complete. \''.cacti_sizeof($ifTypes).'\' rows found!'); + + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete. \''.cacti_sizeof($ifNames).'\' rows found!'); + + // get ports names through use of ifAlias + if ($getAlias) { + $ifAliases = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); + mactrack_debug('ifAlias data collection complete. \''.cacti_sizeof($ifAliases).'\' rows found!'); + } + + // get ports that happen to be link ports + if ($getLinkPorts) { + $link_ports = get_link_port_status($device); + mactrack_debug("ipAddrTable scanning for link ports data collection complete. '".cacti_sizeof($link_ports)."' rows found!"); + } + + // required only for interfaces table + $db_data = db_fetch_assoc("SELECT * FROM mac_track_interfaces WHERE device_id='".$device['device_id']."' ORDER BY ifIndex"); + + if (cacti_sizeof($db_data)) { + foreach ($db_data as $interface) { + $db_interface[$interface['ifIndex']] = $interface; + } + } + + // mark all interfaces as not present + db_execute_prepared( + 'UPDATE mac_track_interfaces SET present=0 WHERE device_id= ?', - array($device['device_id'])); + [$device['device_id']] + ); - $insert_prefix = 'INSERT INTO mac_track_interfaces (site_id, device_id, sysUptime, + $insert_prefix = 'INSERT INTO mac_track_interfaces (site_id, device_id, sysUptime, ifIndex, ifType, ifName, ifAlias, linkPort, vlan_id, vlan_name, vlan_trunk_status, ifSpeed, ifHighSpeed, ifDuplex, ifDescr, ifMtu, ifPhysAddress, ifAdminStatus, ifOperStatus, ifLastChange, @@ -560,7 +661,7 @@ function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $ge int_discards_present, int_errors_present, last_down_time, last_up_time, stateChanges, present) VALUES '; - $insert_suffix = ' ON DUPLICATE KEY UPDATE + $insert_suffix = ' ON DUPLICATE KEY UPDATE sysUptime=VALUES(sysUptime), ifType=VALUES(ifType), ifName=VALUES(ifName), @@ -615,388 +716,394 @@ function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $ge stateChanges=VALUES(stateChanges), present="1"'; - $insert_vals = ''; - - $ifSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.5', $device); - mactrack_debug("ifSpeed data collection complete. '" . cacti_sizeof($ifSpeed) . "' rows found!"); - - $ifHighSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.15', $device); - mactrack_debug("ifHighSpeed data collection complete. '" . cacti_sizeof($ifHighSpeed) . "' rows found!"); - - $ifDuplex = xform_standard_indexed_data('.1.3.6.1.2.1.10.7.2.1.19', $device); - mactrack_debug("ifDuplex data collection complete. '" . cacti_sizeof($ifDuplex) . "' rows found!"); + $insert_vals = ''; - $ifDescr = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); - mactrack_debug("ifDescr data collection complete. '" . cacti_sizeof($ifDescr) . "' rows found!"); - - $ifMtu = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.4', $device); - mactrack_debug("ifMtu data collection complete. '" . cacti_sizeof($ifMtu) . "' rows found!"); - - $ifPhysAddress = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.6', $device, '', true); - mactrack_debug("ifPhysAddress data collection complete. '" . cacti_sizeof($ifPhysAddress) . "' rows found!"); - - $ifAdminStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.7', $device); - if (cacti_sizeof($ifAdminStatus)) { - foreach($ifAdminStatus as $key => $value) { - if ((substr_count(strtolower($value), 'up')) || ($value == '1')) { - $ifAdminStatus[$key] = 1; - } else { - $ifAdminStatus[$key] = 0; - } - } - } - mactrack_debug("ifAdminStatus data collection complete. '" . cacti_sizeof($ifAdminStatus) . "' rows found!"); - - $ifOperStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - if (cacti_sizeof($ifOperStatus)) { - foreach($ifOperStatus as $key=>$value) { - if ((substr_count(strtolower($value), 'up')) || ($value == '1')) { - $ifOperStatus[$key] = 1; - } else { - $ifOperStatus[$key] = 0; - } - } - } - mactrack_debug("ifOperStatus data collection complete. '" . cacti_sizeof($ifOperStatus) . "' rows found!"); - - $ifLastChange = xform_standard_indexed_data(".1.3.6.1.2.1.2.2.1.9", $device); - mactrack_debug("ifLastChange data collection complete. '" . cacti_sizeof($ifLastChange) . "' rows found!"); - - /* get timing for rate information */ - $prev_octets_time = strtotime($device['last_rundate']); - $cur_octets_time = time(); - - if ($prev_octets_time == 0) { - $divisor = false; - } else { - $divisor = $cur_octets_time - $prev_octets_time; - } - - /* if the device is snmpv2 use high speed and don't bother with the low speed stuff */ - $ifInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.10', $device); - mactrack_debug("ifInOctets data collection complete. '" . cacti_sizeof($ifInOctets) . "' rows found!"); - - $ifOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.16', $device); - mactrack_debug("ifOutOctets data collection complete. '" . cacti_sizeof($ifOutOctets) . "' rows found!"); - - if ($device['snmp_version'] > 1) { - $ifHCInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.6', $device); - mactrack_debug("ifHCInOctets data collection complete. '" . cacti_sizeof($ifHCInOctets) . "' rows found!"); - - $ifHCOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.10', $device); - mactrack_debug("ifHCOutOctets data collection complete. '" . cacti_sizeof($ifHCOutOctets) . "' rows found!"); - } - - - $ifInMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.2', $device); - mactrack_debug("ifInMulticastPkts data collection complete. '" . cacti_sizeof($ifInMulticastPkts) . "' rows found!"); - - $ifOutMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.4', $device); - mactrack_debug("ifOutMulticastPkts data collection complete. '" . cacti_sizeof($ifOutMulticastPkts) . "' rows found!"); - - $ifInBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.3', $device); - mactrack_debug("ifInBroadcastPkts data collection complete. '" . cacti_sizeof($ifInBroadcastPkts) . "' rows found!"); - - $ifOutBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.5', $device); - mactrack_debug("ifOutBroadcastPkts data collection complete. '" . cacti_sizeof($ifOutBroadcastPkts) . "' rows found!"); - - $ifInUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.11', $device); - mactrack_debug("ifInUcastPkts data collection complete. '" . cacti_sizeof($ifInUcastPkts) . "' rows found!"); - - $ifOutUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.17', $device); - mactrack_debug("ifOutUcastPkts data collection complete. '" . cacti_sizeof($ifOutUcastPkts) . "' rows found!"); - - /* get information on error conditions */ - $ifInDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.13', $device); - mactrack_debug("ifInDiscards data collection complete. '" . cacti_sizeof($ifInDiscards) . "' rows found!"); - - $ifInErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.14', $device); - mactrack_debug("ifInErrors data collection complete. '" . cacti_sizeof($ifInErrors) . "' rows found!"); - - $ifInUnknownProtos = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.15', $device); - mactrack_debug("ifInUnknownProtos data collection complete. '" . cacti_sizeof($ifInUnknownProtos) . "' rows found!"); - - $ifOutDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.19', $device); - mactrack_debug("ifOutDiscards data collection complete. '" . cacti_sizeof($ifOutDiscards) . "' rows found!"); - - $ifOutErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.20', $device); - mactrack_debug("ifOutErrors data collection complete. '" . cacti_sizeof($ifOutErrors) . "' rows found!"); - - $vlan_id = ''; - $vlan_name = ''; - $vlan_trunk = ''; - - $i = 0; - foreach($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; - $ifInterfaces[$ifIndex]['ifName'] = (isset($ifNames[$ifIndex]) ? $ifNames[$ifIndex] : ''); - $ifInterfaces[$ifIndex]['ifType'] = (isset($ifTypes[$ifIndex]) ? $ifTypes[$ifIndex] : ''); - - if ($getLinkPorts) { - $ifInterfaces[$ifIndex]['linkPort'] = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); - $linkPort = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); - } else { - $linkPort = 0; - } - - if (($getAlias) && (cacti_sizeof($ifAliases))) { - $ifInterfaces[$ifIndex]['ifAlias'] = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); - $ifAlias = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); - } else { - $ifAlias = ''; - } - - /* update the last up/down status */ - if (!isset($db_interface[$ifIndex])) { - if (isset($ifOperStatus[$ifIndex]) && $ifOperStatus[$ifIndex] == 1) { - $last_up_time = date('Y-m-d H:i:s'); - $stateChanges = 0; - $last_down_time = 0; - } else { - $stateChanges = 0; - $last_up_time = 0; - $last_down_time = date('Y-m-d H:i:s'); - } - } else { - $last_up_time = $db_interface[$ifIndex]['last_up_time']; - $last_down_time = $db_interface[$ifIndex]['last_down_time']; - $stateChanges = $db_interface[$ifIndex]['stateChanges']; - - if ($db_interface[$ifIndex]['ifOperStatus'] == 0) { /* interface previously not up */ - if (isset($ifOperStatus[$ifIndex]) && $ifOperStatus[$ifIndex] == 1) { - /* the interface just went up, mark the time */ - $last_up_time = date('Y-m-d H:i:s'); - $stateChanges += 1; - - /* if the interface has never been marked down before, make it the current time */ - if ($db_interface[$ifIndex]['last_down_time'] == '0000-00-00 00:00:00') { - $last_down_time = $last_up_time; - } - } else { - /* if the interface has never been down, make the current time */ - $last_down_time = date('Y-m-d H:i:s'); - - /* if the interface stayed down, set the last up time if not set before */ - if ($db_interface[$ifIndex]['last_up_time'] == '0000-00-00 00:00:00') { - $last_up_time = date('Y-m-d H:i:s'); - } - } - } else { - if (isset($ifOperStatus[$ifIndex]) && $ifOperStatus[$ifIndex] == 0) { - /* the interface just went down, mark the time */ - $last_down_time = date('Y-m-d H:i:s'); - $stateChanges += 1; - - /* if the interface has never been up before, mark it the current time */ - if ($db_interface[$ifIndex]['last_up_time'] == '0000-00-00 00:00:00') { - $last_up_time = date('Y-m-d H:i:s'); - } - } else { - $last_up_time = date('Y-m-d H:i:s'); - - if ($db_interface[$ifIndex]['last_down_time'] == '0000-00-00 00:00:00') { - $last_down_time = date('Y-m-d H:i:s'); - } - } - } - } + $ifSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.5', $device); + mactrack_debug("ifSpeed data collection complete. '".cacti_sizeof($ifSpeed)."' rows found!"); - /* do the in octets */ - $int_ifInOctets = get_link_int_value('ifInOctets', $ifIndex, $ifInOctets, $db_interface, $divisor, 'traffic'); + $ifHighSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.15', $device); + mactrack_debug("ifHighSpeed data collection complete. '".cacti_sizeof($ifHighSpeed)."' rows found!"); - /* do the out octets */ - $int_ifOutOctets = get_link_int_value('ifOutOctets', $ifIndex, $ifOutOctets, $db_interface, $divisor, 'traffic'); + $ifDuplex = xform_standard_indexed_data('.1.3.6.1.2.1.10.7.2.1.19', $device); + mactrack_debug("ifDuplex data collection complete. '".cacti_sizeof($ifDuplex)."' rows found!"); - if ($device['snmp_version'] > 1) { - /* do the in octets */ - $int_ifHCInOctets = get_link_int_value('ifHCInOctets', $ifIndex, $ifHCInOctets, $db_interface, $divisor, 'traffic', '64'); + $ifDescr = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); + mactrack_debug("ifDescr data collection complete. '".cacti_sizeof($ifDescr)."' rows found!"); - /* do the out octets */ - $int_ifHCOutOctets = get_link_int_value('ifHCOutOctets', $ifIndex, $ifHCOutOctets, $db_interface, $divisor, 'traffic', '64'); - } + $ifMtu = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.4', $device); + mactrack_debug("ifMtu data collection complete. '".cacti_sizeof($ifMtu)."' rows found!"); - /* accommodate values in high speed octets for interfaces that don't support 64 bit */ - if (isset($ifInOctets[$ifIndex])) { - if (!isset($ifHCInOctets[$ifIndex])) { - $ifHCInOctets[$ifIndex] = isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : ''; - $int_ifHCInOctets = $int_ifInOctets; - } - } + $ifPhysAddress = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.6', $device, '', true); + mactrack_debug("ifPhysAddress data collection complete. '".cacti_sizeof($ifPhysAddress)."' rows found!"); - if (isset($ifOutOctets[$ifIndex])) { - if (!isset($ifHCOutOctets[$ifIndex])) { - $ifHCOutOctets[$ifIndex] = isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : ''; - $int_ifHCOutOctets = $int_ifOutOctets; - } - } - - $int_ifInMulticastPkts = get_link_int_value('ifInMulticastPkts', $ifIndex, $ifInMulticastPkts, $db_interface, $divisor, 'traffic'); - $int_ifOutMulticastPkts = get_link_int_value('ifOutMulticastPkts', $ifIndex, $ifOutMulticastPkts, $db_interface, $divisor, 'traffic'); - $int_ifInBroadcastPkts = get_link_int_value('ifInBroadcastPkts', $ifIndex, $ifInBroadcastPkts, $db_interface, $divisor, 'traffic'); - $int_ifOutBroadcastPkts = get_link_int_value('ifOutBroadcastPkts', $ifIndex, $ifOutBroadcastPkts, $db_interface, $divisor, 'traffic'); - $int_ifInUcastPkts = get_link_int_value('ifInUcastPkts', $ifIndex, $ifInUcastPkts, $db_interface, $divisor, 'traffic'); - $int_ifOutUcastPkts = get_link_int_value('ifOutUcastPkts', $ifIndex, $ifOutUcastPkts, $db_interface, $divisor, 'traffic'); - - /* see if in error's have been increasing */ - $int_ifInErrors = get_link_int_value('ifInErrors', $ifIndex, $ifInErrors, $db_interface, $divisor, 'errors'); - - /* see if out error's have been increasing */ - $int_ifOutErrors = get_link_int_value('ifOutErrors', $ifIndex, $ifOutErrors, $db_interface, $divisor, 'errors'); - - if ($int_ifInErrors > 0 || $int_ifOutErrors > 0) { - $int_errors_present = true; - } else { - $int_errors_present = false; - } - - /* see if in discards's have been increasing */ - $int_ifInDiscards = get_link_int_value('ifInDiscards', $ifIndex, $ifInDiscards, $db_interface, $divisor, 'errors'); - - /* see if out discards's have been increasing */ - $int_ifOutDiscards = get_link_int_value('ifOutDiscards', $ifIndex, $ifOutDiscards, $db_interface, $divisor, 'errors'); - - if ($int_ifInDiscards > 0 || $int_ifOutDiscards > 0) { - $int_discards_present = true; - } else { - $int_discards_present = false; - } - - /* see if in discards's have been increasing */ - $int_ifInUnknownProtos = get_link_int_value('ifInUnknownProtos', $ifIndex, $ifInUnknownProtos, $db_interface, $divisor, 'errors'); - - /* format the update packet */ - if ($i == 0) { - $insert_vals .= ' '; - } else { - $insert_vals .= ','; - } - - if (isset($ifTypes[$ifIndex])) { - $type = $ifTypes[$ifIndex]; - } else { - $type = 'Undefined'; - } - - if (isset($ifNames[$ifIndex])) { - $name = $ifNames[$ifIndex]; - } else { - $name = 'Undefined'; - } - - if (isset($ifSpeed[$ifIndex])) { - $speed = $ifSpeed[$ifIndex]; - } else { - $speed = 0; - } - - if (isset($ifDescr[$ifIndex])) { - $desc = $ifDescr[$ifIndex]; - } else { - $desc = ''; - } - - if (isset($ifLastChange[$ifIndex]) && strpos($ifLastChange[$ifIndex], ':') !== false) { - $ifLastChange[$ifIndex] = mactrack_timetics_to_seconds($ifLastChange[$ifIndex]); - } - - $mac_address = isset($ifPhysAddress[$ifIndex]) ? xform_mac_address($ifPhysAddress[$ifIndex]):''; - - $insert_vals .= "('" . - $device['site_id'] . "', '" . $device['device_id'] . "', '" . - $device['snmp_sysUptime'] . "', '" . $ifIndex . "', " . - db_qstr($type) . ", " . db_qstr($name) . ", " . - db_qstr($ifAlias) . ", '" . $linkPort . "', '" . - $vlan_id . "', " . db_qstr($vlan_name) . ", '" . - $vlan_trunk . "', '" . $speed . "', '" . - (isset($ifHighSpeed[$ifIndex]) ? $ifHighSpeed[$ifIndex] : '') . "', '" . - (isset($ifDuplex[$ifIndex]) ? $ifDuplex[$ifIndex] : '') . "', " . - db_qstr($desc) . ", '" . - (isset($ifMtu[$ifIndex]) ? $ifMtu[$ifIndex] : '') . "', '" . - $mac_address . "', '" . - (isset($ifAdminStatus[$ifIndex]) ? $ifAdminStatus[$ifIndex] : '') . "', '" . - (isset($ifOperStatus[$ifIndex]) ? $ifOperStatus[$ifIndex] : '') . "', '" . - (isset($ifLastChange[$ifIndex]) ? $ifLastChange[$ifIndex] : '') . "', '" . - (isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : '') . "', '" . - (isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : '') . "', '" . - (isset($ifHCInOctets[$ifIndex]) ? $ifHCInOctets[$ifIndex] : '') . "', '" . - (isset($ifHCOutOctets[$ifIndex]) ? $ifHCOutOctets[$ifIndex] : '') . "', '" . - (isset($ifInUcastPkts[$ifIndex]) ? $ifInUcastPkts[$ifIndex] : '') . "', '" . - (isset($ifOutUcastPkts[$ifIndex]) ? $ifOutUcastPkts[$ifIndex] : '') . "', '" . - (isset($ifInDiscards[$ifIndex]) ? $ifInDiscards[$ifIndex] : '') . "', '" . - (isset($ifInErrors[$ifIndex]) ? $ifInErrors[$ifIndex] : '') . "', '" . - (isset($ifInUnknownProtos[$ifIndex]) ? $ifInUnknownProtos[$ifIndex] : '') . "', '" . - (isset($ifOutDiscards[$ifIndex]) ? $ifOutDiscards[$ifIndex] : '') . "', '" . - (isset($ifOutErrors[$ifIndex]) ? $ifOutErrors[$ifIndex] : '') . "', '" . - (isset($ifInMulticastPkts[$ifIndex]) ? $ifInMulticastPkts[$ifIndex] : '') . "', '" . - (isset($ifOutMulticastPkts[$ifIndex]) ? $ifOutMulticastPkts[$ifIndex] : '') . "', '" . - (isset($ifInBroadcastPkts[$ifIndex]) ? $ifInBroadcastPkts[$ifIndex] : '') . "', '" . - (isset($ifOutBroadcastPkts[$ifIndex]) ? $ifOutBroadcastPkts[$ifIndex] : '') . "', '" . - @$int_ifInOctets . "', '" . @$int_ifOutOctets . "', '" . - @$int_ifHCInOctets . "', '" . @$int_ifHCOutOctets . "', '" . - @$int_ifInMulticastPkts . "', '" . @$int_ifOutMulticastPkts . "', '" . - @$int_ifInBroadcastPkts . "', '" . @$int_ifOutBroadcastPkts . "', '" . - @$int_ifInUcastPkts . "', '" . @$int_ifOutUcastPkts . "', '" . - @$int_ifInDiscards . "', '" . @$int_ifInErrors . "', '" . - @$int_ifInUnknownProtos . "', '" . @$int_ifOutDiscards . "', '" . - @$int_ifOutErrors . "', '" . @$int_discards_present . "', '" . - $int_errors_present . "', '" . $last_down_time . "', '" . - $last_up_time . "', '" . $stateChanges . "', '" . "1')"; - - $i++; - } - - mactrack_debug('ifInterfaces assembly complete: ' . strlen($insert_prefix . $insert_vals . $insert_suffix)); - - if ($insert_vals != '') { - /* add/update records in the database */ - db_execute($insert_prefix . $insert_vals . $insert_suffix); - - /* remove all obsolete records from the database */ - db_execute_prepared('DELETE FROM mac_track_interfaces + $ifAdminStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.7', $device); + if (cacti_sizeof($ifAdminStatus)) { + foreach ($ifAdminStatus as $key => $value) { + if (substr_count(strtolower($value), 'up') || ('1' == $value)) { + $ifAdminStatus[$key] = 1; + } else { + $ifAdminStatus[$key] = 0; + } + } + } + mactrack_debug("ifAdminStatus data collection complete. '".cacti_sizeof($ifAdminStatus)."' rows found!"); + + $ifOperStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + if (cacti_sizeof($ifOperStatus)) { + foreach ($ifOperStatus as $key => $value) { + if (substr_count(strtolower($value), 'up') || ('1' == $value)) { + $ifOperStatus[$key] = 1; + } else { + $ifOperStatus[$key] = 0; + } + } + } + mactrack_debug("ifOperStatus data collection complete. '".cacti_sizeof($ifOperStatus)."' rows found!"); + + $ifLastChange = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.9', $device); + mactrack_debug("ifLastChange data collection complete. '".cacti_sizeof($ifLastChange)."' rows found!"); + + // get timing for rate information + $prev_octets_time = strtotime($device['last_rundate']); + $cur_octets_time = time(); + + if (0 == $prev_octets_time) { + $divisor = false; + } else { + $divisor = $cur_octets_time - $prev_octets_time; + } + + // if the device is snmpv2 use high speed and don't bother with the low speed stuff + $ifInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.10', $device); + mactrack_debug("ifInOctets data collection complete. '".cacti_sizeof($ifInOctets)."' rows found!"); + + $ifOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.16', $device); + mactrack_debug("ifOutOctets data collection complete. '".cacti_sizeof($ifOutOctets)."' rows found!"); + + if ($device['snmp_version'] > 1) { + $ifHCInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.6', $device); + mactrack_debug("ifHCInOctets data collection complete. '".cacti_sizeof($ifHCInOctets)."' rows found!"); + + $ifHCOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.10', $device); + mactrack_debug("ifHCOutOctets data collection complete. '".cacti_sizeof($ifHCOutOctets)."' rows found!"); + } + + $ifInMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.2', $device); + mactrack_debug("ifInMulticastPkts data collection complete. '".cacti_sizeof($ifInMulticastPkts)."' rows found!"); + + $ifOutMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.4', $device); + mactrack_debug("ifOutMulticastPkts data collection complete. '".cacti_sizeof($ifOutMulticastPkts)."' rows found!"); + + $ifInBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.3', $device); + mactrack_debug("ifInBroadcastPkts data collection complete. '".cacti_sizeof($ifInBroadcastPkts)."' rows found!"); + + $ifOutBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.5', $device); + mactrack_debug("ifOutBroadcastPkts data collection complete. '".cacti_sizeof($ifOutBroadcastPkts)."' rows found!"); + + $ifInUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.11', $device); + mactrack_debug("ifInUcastPkts data collection complete. '".cacti_sizeof($ifInUcastPkts)."' rows found!"); + + $ifOutUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.17', $device); + mactrack_debug("ifOutUcastPkts data collection complete. '".cacti_sizeof($ifOutUcastPkts)."' rows found!"); + + // get information on error conditions + $ifInDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.13', $device); + mactrack_debug("ifInDiscards data collection complete. '".cacti_sizeof($ifInDiscards)."' rows found!"); + + $ifInErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.14', $device); + mactrack_debug("ifInErrors data collection complete. '".cacti_sizeof($ifInErrors)."' rows found!"); + + $ifInUnknownProtos = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.15', $device); + mactrack_debug("ifInUnknownProtos data collection complete. '".cacti_sizeof($ifInUnknownProtos)."' rows found!"); + + $ifOutDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.19', $device); + mactrack_debug("ifOutDiscards data collection complete. '".cacti_sizeof($ifOutDiscards)."' rows found!"); + + $ifOutErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.20', $device); + mactrack_debug("ifOutErrors data collection complete. '".cacti_sizeof($ifOutErrors)."' rows found!"); + + $vlan_id = ''; + $vlan_name = ''; + $vlan_trunk = ''; + + $i = 0; + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = (isset($ifNames[$ifIndex]) ? $ifNames[$ifIndex] : ''); + $ifInterfaces[$ifIndex]['ifType'] = (isset($ifTypes[$ifIndex]) ? $ifTypes[$ifIndex] : ''); + + if ($getLinkPorts) { + $ifInterfaces[$ifIndex]['linkPort'] = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); + $linkPort = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); + } else { + $linkPort = 0; + } + + if ($getAlias && cacti_sizeof($ifAliases)) { + $ifInterfaces[$ifIndex]['ifAlias'] = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); + $ifAlias = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); + } else { + $ifAlias = ''; + } + + // update the last up/down status + if (!isset($db_interface[$ifIndex])) { + if (isset($ifOperStatus[$ifIndex]) && 1 == $ifOperStatus[$ifIndex]) { + $last_up_time = date('Y-m-d H:i:s'); + $stateChanges = 0; + $last_down_time = 0; + } else { + $stateChanges = 0; + $last_up_time = 0; + $last_down_time = date('Y-m-d H:i:s'); + } + } else { + $last_up_time = $db_interface[$ifIndex]['last_up_time']; + $last_down_time = $db_interface[$ifIndex]['last_down_time']; + $stateChanges = $db_interface[$ifIndex]['stateChanges']; + + if (0 == $db_interface[$ifIndex]['ifOperStatus']) { // interface previously not up + if (isset($ifOperStatus[$ifIndex]) && 1 == $ifOperStatus[$ifIndex]) { + // the interface just went up, mark the time + $last_up_time = date('Y-m-d H:i:s'); + ++$stateChanges; + + // if the interface has never been marked down before, make it the current time + if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_down_time']) { + $last_down_time = $last_up_time; + } + } else { + // if the interface has never been down, make the current time + $last_down_time = date('Y-m-d H:i:s'); + + // if the interface stayed down, set the last up time if not set before + if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_up_time']) { + $last_up_time = date('Y-m-d H:i:s'); + } + } + } else { + if (isset($ifOperStatus[$ifIndex]) && 0 == $ifOperStatus[$ifIndex]) { + // the interface just went down, mark the time + $last_down_time = date('Y-m-d H:i:s'); + ++$stateChanges; + + // if the interface has never been up before, mark it the current time + if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_up_time']) { + $last_up_time = date('Y-m-d H:i:s'); + } + } else { + $last_up_time = date('Y-m-d H:i:s'); + + if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_down_time']) { + $last_down_time = date('Y-m-d H:i:s'); + } + } + } + } + + // do the in octets + $int_ifInOctets = get_link_int_value('ifInOctets', $ifIndex, $ifInOctets, $db_interface, $divisor, 'traffic'); + + // do the out octets + $int_ifOutOctets = get_link_int_value('ifOutOctets', $ifIndex, $ifOutOctets, $db_interface, $divisor, 'traffic'); + + if ($device['snmp_version'] > 1) { + // do the in octets + $int_ifHCInOctets = get_link_int_value('ifHCInOctets', $ifIndex, $ifHCInOctets, $db_interface, $divisor, 'traffic', '64'); + + // do the out octets + $int_ifHCOutOctets = get_link_int_value('ifHCOutOctets', $ifIndex, $ifHCOutOctets, $db_interface, $divisor, 'traffic', '64'); + } + + // accommodate values in high speed octets for interfaces that don't support 64 bit + if (isset($ifInOctets[$ifIndex])) { + if (!isset($ifHCInOctets[$ifIndex])) { + $ifHCInOctets[$ifIndex] = isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : ''; + $int_ifHCInOctets = $int_ifInOctets; + } + } + + if (isset($ifOutOctets[$ifIndex])) { + if (!isset($ifHCOutOctets[$ifIndex])) { + $ifHCOutOctets[$ifIndex] = isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : ''; + $int_ifHCOutOctets = $int_ifOutOctets; + } + } + + $int_ifInMulticastPkts = get_link_int_value('ifInMulticastPkts', $ifIndex, $ifInMulticastPkts, $db_interface, $divisor, 'traffic'); + $int_ifOutMulticastPkts = get_link_int_value('ifOutMulticastPkts', $ifIndex, $ifOutMulticastPkts, $db_interface, $divisor, 'traffic'); + $int_ifInBroadcastPkts = get_link_int_value('ifInBroadcastPkts', $ifIndex, $ifInBroadcastPkts, $db_interface, $divisor, 'traffic'); + $int_ifOutBroadcastPkts = get_link_int_value('ifOutBroadcastPkts', $ifIndex, $ifOutBroadcastPkts, $db_interface, $divisor, 'traffic'); + $int_ifInUcastPkts = get_link_int_value('ifInUcastPkts', $ifIndex, $ifInUcastPkts, $db_interface, $divisor, 'traffic'); + $int_ifOutUcastPkts = get_link_int_value('ifOutUcastPkts', $ifIndex, $ifOutUcastPkts, $db_interface, $divisor, 'traffic'); + + // see if in error's have been increasing + $int_ifInErrors = get_link_int_value('ifInErrors', $ifIndex, $ifInErrors, $db_interface, $divisor, 'errors'); + + // see if out error's have been increasing + $int_ifOutErrors = get_link_int_value('ifOutErrors', $ifIndex, $ifOutErrors, $db_interface, $divisor, 'errors'); + + if ($int_ifInErrors > 0 || $int_ifOutErrors > 0) { + $int_errors_present = true; + } else { + $int_errors_present = false; + } + + // see if in discards's have been increasing + $int_ifInDiscards = get_link_int_value('ifInDiscards', $ifIndex, $ifInDiscards, $db_interface, $divisor, 'errors'); + + // see if out discards's have been increasing + $int_ifOutDiscards = get_link_int_value('ifOutDiscards', $ifIndex, $ifOutDiscards, $db_interface, $divisor, 'errors'); + + if ($int_ifInDiscards > 0 || $int_ifOutDiscards > 0) { + $int_discards_present = true; + } else { + $int_discards_present = false; + } + + // see if in discards's have been increasing + $int_ifInUnknownProtos = get_link_int_value('ifInUnknownProtos', $ifIndex, $ifInUnknownProtos, $db_interface, $divisor, 'errors'); + + // format the update packet + if (0 == $i) { + $insert_vals .= ' '; + } else { + $insert_vals .= ','; + } + + if (isset($ifTypes[$ifIndex])) { + $type = $ifTypes[$ifIndex]; + } else { + $type = 'Undefined'; + } + + if (isset($ifNames[$ifIndex])) { + $name = $ifNames[$ifIndex]; + } else { + $name = 'Undefined'; + } + + if (isset($ifSpeed[$ifIndex])) { + $speed = $ifSpeed[$ifIndex]; + } else { + $speed = 0; + } + + if (isset($ifDescr[$ifIndex])) { + $desc = $ifDescr[$ifIndex]; + } else { + $desc = ''; + } + + if (isset($ifLastChange[$ifIndex]) && false !== strpos($ifLastChange[$ifIndex], ':')) { + $ifLastChange[$ifIndex] = mactrack_timetics_to_seconds($ifLastChange[$ifIndex]); + } + + $mac_address = isset($ifPhysAddress[$ifIndex]) ? xform_mac_address($ifPhysAddress[$ifIndex]) : ''; + + $insert_vals .= "('" + .$device['site_id']."', '".$device['device_id']."', '" + .$device['snmp_sysUptime']."', '".$ifIndex."', " + .db_qstr($type).', '.db_qstr($name).', ' + .db_qstr($ifAlias).", '".$linkPort."', '" + .$vlan_id."', ".db_qstr($vlan_name).", '" + .$vlan_trunk."', '".$speed."', '" + .(isset($ifHighSpeed[$ifIndex]) ? $ifHighSpeed[$ifIndex] : '')."', '" + .(isset($ifDuplex[$ifIndex]) ? $ifDuplex[$ifIndex] : '')."', " + .db_qstr($desc).", '" + .(isset($ifMtu[$ifIndex]) ? $ifMtu[$ifIndex] : '')."', '" + .$mac_address."', '" + .(isset($ifAdminStatus[$ifIndex]) ? $ifAdminStatus[$ifIndex] : '')."', '" + .(isset($ifOperStatus[$ifIndex]) ? $ifOperStatus[$ifIndex] : '')."', '" + .(isset($ifLastChange[$ifIndex]) ? $ifLastChange[$ifIndex] : '')."', '" + .(isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : '')."', '" + .(isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : '')."', '" + .(isset($ifHCInOctets[$ifIndex]) ? $ifHCInOctets[$ifIndex] : '')."', '" + .(isset($ifHCOutOctets[$ifIndex]) ? $ifHCOutOctets[$ifIndex] : '')."', '" + .(isset($ifInUcastPkts[$ifIndex]) ? $ifInUcastPkts[$ifIndex] : '')."', '" + .(isset($ifOutUcastPkts[$ifIndex]) ? $ifOutUcastPkts[$ifIndex] : '')."', '" + .(isset($ifInDiscards[$ifIndex]) ? $ifInDiscards[$ifIndex] : '')."', '" + .(isset($ifInErrors[$ifIndex]) ? $ifInErrors[$ifIndex] : '')."', '" + .(isset($ifInUnknownProtos[$ifIndex]) ? $ifInUnknownProtos[$ifIndex] : '')."', '" + .(isset($ifOutDiscards[$ifIndex]) ? $ifOutDiscards[$ifIndex] : '')."', '" + .(isset($ifOutErrors[$ifIndex]) ? $ifOutErrors[$ifIndex] : '')."', '" + .(isset($ifInMulticastPkts[$ifIndex]) ? $ifInMulticastPkts[$ifIndex] : '')."', '" + .(isset($ifOutMulticastPkts[$ifIndex]) ? $ifOutMulticastPkts[$ifIndex] : '')."', '" + .(isset($ifInBroadcastPkts[$ifIndex]) ? $ifInBroadcastPkts[$ifIndex] : '')."', '" + .(isset($ifOutBroadcastPkts[$ifIndex]) ? $ifOutBroadcastPkts[$ifIndex] : '')."', '" + .@$int_ifInOctets."', '".@$int_ifOutOctets."', '" + .@$int_ifHCInOctets."', '".@$int_ifHCOutOctets."', '" + .@$int_ifInMulticastPkts."', '".@$int_ifOutMulticastPkts."', '" + .@$int_ifInBroadcastPkts."', '".@$int_ifOutBroadcastPkts."', '" + .@$int_ifInUcastPkts."', '".@$int_ifOutUcastPkts."', '" + .@$int_ifInDiscards."', '".@$int_ifInErrors."', '" + .@$int_ifInUnknownProtos."', '".@$int_ifOutDiscards."', '" + .@$int_ifOutErrors."', '".@$int_discards_present."', '" + .$int_errors_present."', '".$last_down_time."', '" + .$last_up_time."', '".$stateChanges."', '1')"; + + ++$i; + } + + mactrack_debug('ifInterfaces assembly complete: '.strlen($insert_prefix.$insert_vals.$insert_suffix)); + + if ('' != $insert_vals) { + // add/update records in the database + db_execute($insert_prefix.$insert_vals.$insert_suffix); + + // remove all obsolete records from the database + db_execute_prepared( + 'DELETE FROM mac_track_interfaces WHERE present=0 AND device_id = ?', - array($device['device_id'])); + [$device['device_id']] + ); - /* set the percent utilized fields, you can't do this for vlans */ - db_execute_prepared('UPDATE mac_track_interfaces + // set the percent utilized fields, you can't do this for vlans + db_execute_prepared( + 'UPDATE mac_track_interfaces SET inBound=(int_ifHCInOctets*8)/(ifHighSpeed*10000), outBound=(int_ifHCOutOctets*8)/(ifHighSpeed*10000) WHERE ifHighSpeed>0 AND ifName NOT LIKE "Vl%" AND device_id = ?', - array($device['device_id'])); + [$device['device_id']] + ); - mactrack_debug('Adding IfInterfaces Records'); - } + mactrack_debug('Adding IfInterfaces Records'); + } - if ($device['host_id'] > 0) { - mactrack_find_host_graphs($device['device_id'], $device['host_id']); - } + if ($device['host_id'] > 0) { + mactrack_find_host_graphs($device['device_id'], $device['host_id']); + } - return $ifInterfaces; + return $ifInterfaces; } -function mactrack_timetics_to_seconds($timetics) { - $time = 0; - $parts = explode(':', $timetics); +function mactrack_timetics_to_seconds($timetics) +{ + $time = 0; + $parts = explode(':', $timetics); - if (cacti_sizeof($parts) == 4) { - $time += $parts[0] * 86400; - $time += $parts[1] * 3600; - $time += $parts[2] * 60; - $time += round($parts[3], 0); - } elseif (cacti_sizeof($parts) == 3) { - $time += $parts[0] * 3600; - $time += $parts[1] * 60; - $time += round($parts[2],0); - } + if (4 == cacti_sizeof($parts)) { + $time += $parts[0] * 86400; + $time += $parts[1] * 3600; + $time += $parts[2] * 60; + $time += round($parts[3], 0); + } elseif (3 == cacti_sizeof($parts)) { + $time += $parts[0] * 3600; + $time += $parts[1] * 60; + $time += round($parts[2], 0); + } - return $time; + return $time; } -function mactrack_find_host_graphs($device_id, $host_id) { - $field_name = 'ifName'; +function mactrack_find_host_graphs($device_id, $host_id) +{ + $field_name = 'ifName'; - $local_data_ids = db_fetch_assoc_prepared('SELECT dl.*, + $local_data_ids = db_fetch_assoc_prepared( + 'SELECT dl.*, hsc.field_name, hsc.field_value FROM data_local AS dl INNER JOIN data_template_data AS dtd @@ -1012,13 +1119,15 @@ function mactrack_find_host_graphs($device_id, $host_id) { WHERE dl.id=dtd.local_data_id AND hsc.host_id = ? AND field_name = ?', - array($host_id, $field_name)); - - $output_array = array(); - if (cacti_sizeof($local_data_ids)) { - foreach($local_data_ids as $local_data_id) { - $local_graph_ids = array_rekey( - db_fetch_assoc_prepared('SELECT DISTINCT gtg.local_graph_id AS id, gtg.graph_template_id + [$host_id, $field_name] + ); + + $output_array = []; + if (cacti_sizeof($local_data_ids)) { + foreach ($local_data_ids as $local_data_id) { + $local_graph_ids = array_rekey( + db_fetch_assoc_prepared( + 'SELECT DISTINCT gtg.local_graph_id AS id, gtg.graph_template_id FROM graph_templates_graph AS gtg INNER JOIN graph_templates_item AS gti ON gtg.local_graph_id=gti.local_graph_id @@ -1026,60 +1135,65 @@ function mactrack_find_host_graphs($device_id, $host_id) { ON gti.task_item_id=dtr.id WHERE gtg.local_graph_id>0 AND dtr.local_data_id = ?', - array($local_data_id['id'])), - 'id', 'graph_template_id' - ); - - if (cacti_sizeof($local_graph_ids)) { - foreach($local_graph_ids as $local_graph_id => $graph_template_id) { - $output_array[$local_data_id['field_value']][$local_graph_id] = array($graph_template_id, $local_data_id['snmp_query_id']); - } - } - } - } - - $sql = ''; - $found = 0; - if (cacti_sizeof($output_array)) { - $interfaces = array_rekey( - db_fetch_assoc("SELECT device_id, ifIndex, $field_name + [$local_data_id['id']] + ), + 'id', + 'graph_template_id' + ); + + if (cacti_sizeof($local_graph_ids)) { + foreach ($local_graph_ids as $local_graph_id => $graph_template_id) { + $output_array[$local_data_id['field_value']][$local_graph_id] = [$graph_template_id, $local_data_id['snmp_query_id']]; + } + } + } + } + + $sql = ''; + $found = 0; + if (cacti_sizeof($output_array)) { + $interfaces = array_rekey( + db_fetch_assoc("SELECT device_id, ifIndex, {$field_name} FROM mac_track_interfaces - WHERE device_id=$device_id"), - $field_name, array('device_id', 'ifIndex') - ); - - if (cacti_sizeof($interfaces)) { - foreach($interfaces as $key => $data) { - if (isset($output_array[$key])) { - foreach($output_array[$key] as $local_graph_id => $graph_details) { - $sql .= ($sql != '' ? ', (' : '(') . - $data['ifIndex'] . ",'" . - $key . "'," . - $local_graph_id . ',' . - $device_id . ',' . - $host_id . ',' . - $graph_details[0] . ',' . - $graph_details[1] . ",'" . - $key . "','" . $field_name . "', 1)"; - - $found++; - } - } - } - } - } - - if ($found) { - /* let's make sure we mark everything gone first */ - db_execute_prepared('UPDATE mac_track_interface_graphs + WHERE device_id={$device_id}"), + $field_name, + ['device_id', 'ifIndex'] + ); + + if (cacti_sizeof($interfaces)) { + foreach ($interfaces as $key => $data) { + if (isset($output_array[$key])) { + foreach ($output_array[$key] as $local_graph_id => $graph_details) { + $sql .= ('' != $sql ? ', (' : '(') + .$data['ifIndex'].",'" + .$key."'," + .$local_graph_id.',' + .$device_id.',' + .$host_id.',' + .$graph_details[0].',' + .$graph_details[1].",'" + .$key."','".$field_name."', 1)"; + + ++$found; + } + } + } + } + } + + if ($found) { + // let's make sure we mark everything gone first + db_execute_prepared( + 'UPDATE mac_track_interface_graphs SET present = 0 WHERE device_id = ? AND host_id = ?', - array($device_id, $host_id)); + [$device_id, $host_id] + ); - db_execute("INSERT INTO mac_track_interface_graphs + db_execute("INSERT INTO mac_track_interface_graphs (ifIndex, ifName, local_graph_id, device_id, host_id, snmp_query_id, graph_template_id, field_value, field_name, present) - VALUES $sql + VALUES {$sql} ON DUPLICATE KEY UPDATE snmp_query_id=VALUES(snmp_query_id), graph_template_id=VALUES(graph_template_id), @@ -1087,79 +1201,82 @@ function mactrack_find_host_graphs($device_id, $host_id) { field_name=VALUES(field_name), present=VALUES(present)"); - db_execute_prepared('DELETE FROM mac_track_interface_graphs + db_execute_prepared( + 'DELETE FROM mac_track_interface_graphs WHERE present = 0 AND device_id = ? AND host_id = ?', - array($device_id, $host_id)); - } -} - -function get_link_int_value($snmp_oid, $ifIndex, &$snmp_array, &$db_interface, $divisor, $type = 'errors', $bits = '32') { - /* 32bit and 64bit Integer Overflow Value */ - if ($bits == '32') { - $overflow = 4294967295; - /* fudge factor */ - $fudge = 3000000001; - } else { - $overflow = 18446744065119617025; - /* fudge factor */ - $fudge = 300000000001; - } - - /* see if values have been increasing */ - $int_value = 0; - if (!isset($db_interface[$ifIndex][$snmp_oid])) { - $int_value = 0; - } elseif (!isset($snmp_array[$ifIndex])) { - $int_value = 0; - } elseif ($snmp_array[$ifIndex] != $db_interface[$ifIndex][$snmp_oid]) { - /* account for 2E32 rollover */ - /* there are two types of rollovers one rolls to 0 */ - /* the other counts backwards. let's make an educated guess */ - if ($db_interface[$ifIndex][$snmp_oid] > $snmp_array[$ifIndex]) { - /* errors count backwards from overflow */ - if ($type == 'errors') { - if (($overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]) < $fudge) { - $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; - } else { - $int_value = $db_interface[$ifIndex][$snmp_oid] - $snmp_array[$ifIndex]; - } - } else { - $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; - } - } else { - $int_value = $snmp_array[$ifIndex] - $db_interface[$ifIndex][$snmp_oid]; - } - - /* account for counter resets */ - $frequency = 0; - $timing = read_config_option('mt_collection_timing'); - - if ($timing != 'disabled') { - $frequency = $timing * 60; - } - - if ($frequency > 0) { - if ($db_interface[$ifIndex]['ifHighSpeed'] > 0) { - if ($int_value > ($db_interface[$ifIndex]['ifHighSpeed'] * 1000000 * $frequency * 1.1)) { - $int_value = $snmp_array[$ifIndex]; - } - } else { - if ($int_value > ($db_interface[$ifIndex]['ifSpeed'] * $frequency * 1.1 / 8)) { - $int_value = $snmp_array[$ifIndex]; - } - } - } - } else { - $int_value = 0; - } - - if (!$divisor) { - return 0; - } else { - return $int_value / $divisor; - } + [$device_id, $host_id] + ); + } +} + +function get_link_int_value($snmp_oid, $ifIndex, &$snmp_array, &$db_interface, $divisor, $type = 'errors', $bits = '32') +{ + // 32bit and 64bit Integer Overflow Value + if ('32' == $bits) { + $overflow = 4294967295; + // fudge factor + $fudge = 3000000001; + } else { + $overflow = 18446744065119617025; + // fudge factor + $fudge = 300000000001; + } + + // see if values have been increasing + $int_value = 0; + if (!isset($db_interface[$ifIndex][$snmp_oid])) { + $int_value = 0; + } elseif (!isset($snmp_array[$ifIndex])) { + $int_value = 0; + } elseif ($snmp_array[$ifIndex] != $db_interface[$ifIndex][$snmp_oid]) { + // account for 2E32 rollover + // there are two types of rollovers one rolls to 0 + // the other counts backwards. let's make an educated guess + if ($db_interface[$ifIndex][$snmp_oid] > $snmp_array[$ifIndex]) { + // errors count backwards from overflow + if ('errors' == $type) { + if (($overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]) < $fudge) { + $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; + } else { + $int_value = $db_interface[$ifIndex][$snmp_oid] - $snmp_array[$ifIndex]; + } + } else { + $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; + } + } else { + $int_value = $snmp_array[$ifIndex] - $db_interface[$ifIndex][$snmp_oid]; + } + + // account for counter resets + $frequency = 0; + $timing = read_config_option('mt_collection_timing'); + + if ('disabled' != $timing) { + $frequency = $timing * 60; + } + + if ($frequency > 0) { + if ($db_interface[$ifIndex]['ifHighSpeed'] > 0) { + if ($int_value > ($db_interface[$ifIndex]['ifHighSpeed'] * 1000000 * $frequency * 1.1)) { + $int_value = $snmp_array[$ifIndex]; + } + } else { + if ($int_value > ($db_interface[$ifIndex]['ifSpeed'] * $frequency * 1.1 / 8)) { + $int_value = $snmp_array[$ifIndex]; + } + } + } + } else { + $int_value = 0; + } + + if (!$divisor) { + return 0; + } + + return $int_value / $divisor; } /** @@ -1167,24 +1284,30 @@ function get_link_int_value($snmp_oid, $ifIndex, &$snmp_array, &$db_interface, $ * OID tree for all switch port to MAC address association and stores in the * mac_track_temp_ports table for future processing in the finalization steps of the * scanning process. + * + * @param mixed $site + * @param mixed $device + * @param mixed $lowPort + * @param mixed $highPort */ -function get_generic_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { - global $debug, $scan_date; +function get_generic_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; - /* initialize port counters */ - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - /* get the ifIndexes for the device */ - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /** @@ -1192,24 +1315,30 @@ function get_generic_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) * OID tree for all switch port to MAC address association and stores in the * mac_track_temp_ports table for future processing in the finalization steps of the * scanning process. + * + * @param mixed $site + * @param mixed $device + * @param mixed $lowPort + * @param mixed $highPort */ -function get_generic_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { - global $debug, $scan_date; +function get_generic_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; - /* initialize port counters */ - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - /* get the ifIndexes for the device */ - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - get_base_dot1qTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_dot1qTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /** @@ -1217,955 +1346,1099 @@ function get_generic_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort * OID tree for all switch port to MAC address association and stores in the * mac_track_temp_ports table for future processing in the finalization steps of the * scanning process. + * + * @param mixed $site + * @param mixed $device + * @param mixed $lowPort + * @param mixed $highPort */ -function get_generic_wireless_ports($site, &$device, $lowPort = 0, $highPort = 0) { - global $debug, $scan_date; +function get_generic_wireless_ports($site, &$device, $lowPort = 0, $highPort = 0) +{ + global $debug, $scan_date; - /* initialize port counters */ - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - /* get the ifIndexes for the device */ - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, false, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, false, false); - get_base_wireless_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_wireless_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /** * get_base_dot1dTpFdbEntry_ports - This function will grab information from the * port bridge snmp table and return it to the calling progrem for further processing. * This is a foundational function for all vendor data collection functions. + * + * @param mixed $site + * @param mixed $device + * @param mixed $ifInterfaces + * @param mixed $snmp_readstring + * @param mixed $store_to_db + * @param mixed $lowPort + * @param mixed $highPort */ -function get_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { - global $debug, $scan_date; - - /* initialize variables */ - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_key_array = array(); - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - /* cisco uses a hybrid read string, if one is not defined, use the default */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* get the operational status of the ports */ - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - if (isset($indexes[$i]) && isset($ifInterfaces[$indexes[$i]]['ifType'])) { - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) || - ($ifInterfaces[$indexes[$i]]['ifType'] == 53) || #vlan - ($ifInterfaces[$indexes[$i]]['ifType'] == 161) || #port-channel - ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { - if ($port_info == 1) { - $ports_active++; - } - } - $ports_total++; - } - - $i++; - } - } - $device['ports_active'] = $ports_active; - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - - /* get device active port numbers */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort))) { - - if (!in_array($port_number, $ignore_ports)) { - if ((isset($port_status[$key]) && $port_status[$key] == '3') || - (isset($port_status[$key]) && $port_status[$key] == '5')) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - $i++; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes)) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; - } else { - $brPortIfIndex = @$port_key['port_number']; - } - $brPortIfType = (isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''); - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; - } - - if ((($brPortIfType >= 6 && $brPortIfType <= 9) || - $brPortIfType == 53 || $brPortIfType == 161) && - (!isset($ifInterfaces[$brPortIfIndex]["portLink"]))) { - - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $i++; - } - } - } - } - mactrack_debug('Port number information collected.'); - - /* map mac address */ - /* only continue if there were user ports defined */ - if (cacti_sizeof($new_port_key_array)) { - /* get the bridges active MAC addresses */ - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - if (cacti_sizeof($port_macs)) { - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - } - - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = (isset($port_macs[$port_key['key']]) ? $port_macs[$port_key['key']]:'' ); - mactrack_debug("INDEX: '". $key . "' MAC ADDRESS: " . $new_port_key_array[$key]['mac_address']); - } - } +function get_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + if (isset($indexes[$i], $ifInterfaces[$indexes[$i]]['ifType'])) { + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || (53 == $ifInterfaces[$indexes[$i]]['ifType']) // vlan + || (161 == $ifInterfaces[$indexes[$i]]['ifType']) // port-channel + || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { + if (1 == $port_info) { + ++$ports_active; + } + } + ++$ports_total; + } + + ++$i; + } + } + $device['ports_active'] = $ports_active; - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array)) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports)) { + if ((isset($port_status[$key]) && '3' == $port_status[$key]) + || (isset($port_status[$key]) && '5' == $port_status[$key])) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes)) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; + } else { + $brPortIfIndex = @$port_key['port_number']; + } + $brPortIfType = (isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''); + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; + } + + if ((($brPortIfType >= 6 && $brPortIfType <= 9) + || 53 == $brPortIfType || 161 == $brPortIfType) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + if (cacti_sizeof($port_macs)) { + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + } + + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = (isset($port_macs[$port_key['key']]) ? $port_macs[$port_key['key']] : ''); + mactrack_debug("INDEX: '".$key."' MAC ADDRESS: ".$new_port_key_array[$key]['mac_address']); + } + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array)) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /* get_ios_vrf_arp_table - obtains arp associations for cisco Catalyst Switches. - At this stage only tested on 6800 series + obtains arp associations for cisco Catalyst Switches. + At this stage only tested on 6800 series */ -function get_ios_vrf_arp_table($oid, &$device, $snmp_readstring = '', $hex = false) { - $return_array = array(); - - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - if ($device['snmp_version'] == '3' && substr_count($snmp_readstring,'vlan-')) { - $snmp_context = $snmp_readstring; - } else { - $snmp_context = $device['snmp_context']; - } - - $walk_array = cacti_snmp_walk($device['hostname'], $snmp_readstring, - $oid, $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $snmp_context, $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries'], $device['max_oids'], - SNMP_POLLER, $device['snmp_engine_id'], - ($hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS)); - - $i = 0; - - if (cacti_sizeof($walk_array)) { - - foreach ($walk_array as $walk_item) { - $key = $walk_item['oid']; - $key = preg_replace('/' . $oid . '\.[0-9]+\.1\./', '', $key); - $return_array[$i]['key'] = $key; - $return_array[$i]['value'] = str_replace(' ', ':', $walk_item['value']); - - $i++; - } - } - - return $return_array; - +function get_ios_vrf_arp_table($oid, &$device, $snmp_readstring = '', $hex = false) +{ + $return_array = []; + + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + if ('3' == $device['snmp_version'] && substr_count($snmp_readstring, 'vlan-')) { + $snmp_context = $snmp_readstring; + } else { + $snmp_context = $device['snmp_context']; + } + + $walk_array = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + $oid, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $snmp_context, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $i = 0; + + if (cacti_sizeof($walk_array)) { + foreach ($walk_array as $walk_item) { + $key = $walk_item['oid']; + $key = preg_replace('/'.$oid.'\.[0-9]+\.1\./', '', $key); + $return_array[$i]['key'] = $key; + $return_array[$i]['value'] = str_replace(' ', ':', $walk_item['value']); + + ++$i; + } + } + + return $return_array; } - /** * get_base_wireless_dot1dTpFdbEntry_ports - This function will grab information from the * port bridge snmp table and return it to the calling progrem for further processing. * This is a foundational function for all vendor data collection functions. + * + * @param mixed $site + * @param mixed $device + * @param mixed $ifInterfaces + * @param mixed $snmp_readstring + * @param mixed $store_to_db + * @param mixed $lowPort + * @param mixed $highPort */ -function get_base_wireless_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { - global $debug, $scan_date; - - /* initialize variables */ - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_key_array = array(); - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - /* cisco uses a hybrid read string, if one is not defined, use the default */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* get the operational status of the ports */ - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) || - ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { - if ($port_info == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - - /* get device active port numbers */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* get the bridge root port so we don't capture active ports on it */ - $bridge_root_port = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.2.7.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort) && - ($bridge_root_port != $port_number))) { - - if (!in_array($port_number, $ignore_ports)) { - if ((@$port_status[$key] == '3') || (@$port_status[$key] == '5')) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - $i++; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes)) { - $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; - $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; - } - - if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || ($brPortIfType == 71)) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $i++; - } - } - } - } - mactrack_debug('Port number information collected.'); - - /* map mac address */ - /* only continue if there were user ports defined */ - if (cacti_sizeof($new_port_key_array)) { - /* get the bridges active MAC addresses */ - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - if (cacti_sizeof($port_macs)) { - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - } - - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; - mactrack_debug("INDEX: '". $key . "' MAC ADDRESS: " . $new_port_key_array[$key]['mac_address']); - } - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array)) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_base_wireless_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // get the bridge root port so we don't capture active ports on it + $bridge_root_port = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.2.7.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort) + && ($bridge_root_port != $port_number))) { + if (!in_array($port_number, $ignore_ports)) { + if (('3' == @$port_status[$key]) || ('5' == @$port_status[$key])) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes)) { + $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; + $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; + } + + if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || (71 == $brPortIfType)) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + if (cacti_sizeof($port_macs)) { + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + } + + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; + mactrack_debug("INDEX: '".$key."' MAC ADDRESS: ".$new_port_key_array[$key]['mac_address']); + } + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array)) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /** * get_base_dot1qTpFdbEntry_ports - This function will grab information from the * port bridge snmp table and return it to the calling progrem for further processing. * This is a foundational function for all vendor data collection functions. + * + * @param mixed $site + * @param mixed $device + * @param mixed $ifInterfaces + * @param mixed $snmp_readstring + * @param mixed $store_to_db + * @param mixed $lowPort + * @param mixed $highPort */ -function get_base_dot1qTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { - global $debug, $scan_date; - - /* initialize variables */ - $port_keys = array(); - $return_array = array(); - $new_port_key_array = array(); - $port_key_array = array(); - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - /* cisco uses a hybrid read string, if one is not defined, use the default */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* get the operational status of the ports */ - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) && - ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) || - ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { - if ($port_info == 1) { - $ports_active++; - } - $ports_total++; - } - $i++; - } - } +function get_base_dot1qTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) +{ + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { + if (1 == $port_info) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } $device['ports_active'] = $ports_active; - if ($store_to_db) { - mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'],0,40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); - - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping */ - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); - - /* get device active port numbers */ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); - - /* get the ignore ports list from device */ - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* get the bridge root port so we don't capture active ports on it */ - $bridge_root_port = @cacti_snmp_get($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.2.7.0', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if (($highPort == 0) || - (($port_number >= $lowPort) && - ($port_number <= $highPort) && - ($bridge_root_port != $port_number))) { - - if (!in_array($port_number, $ignore_ports)) { - if ((isset($port_status[$key]) && $port_status[$key] == '3') || (isset($port_status[$key]) && $port_status[$key] == '5')) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - $i++; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - /* map bridge port to interface port and check type */ - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes)) { - if (isset ($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = $bridgePortIfIndexes[$port_key['port_number']]; - } - if (isset($ifInterfaces[$brPortIfIndex]['ifType'])) { - $brPortIfType = $ifInterfaces[$brPortIfIndex]['ifType']; - } - } else { - $brPortIfIndex = $port_key['port_number']; - if (isset($ifInterfaces[$port_key['port_number']]['ifType'])) { - $brPortIfType = $ifInterfaces[$port_key['port_number']]['ifType']; - } - } - - if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || ($brPortIfType == 71)) { - /* set some defaults */ - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - /* now set the real data */ - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $i++; - } - } - } - } - mactrack_debug('Port number information collected.'); - - /* map mac address */ - /* only continue if there were user ports defined */ - if (cacti_sizeof($new_port_key_array)) { - /* get the bridges active MAC addresses */ - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.1', $device, $snmp_readstring, true); - - if (cacti_sizeof($port_macs)) { - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - } - - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_key) { - if (isset($port_macs[$port_key['key']])) { - $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; - mactrack_debug("INDEX: '". $key . "' MAC ADDRESS: " . $new_port_key_array[$key]['mac_address']); - } else { - mactrack_debug("INDEX: '". $key . "' not found in port_macs array, skipping"); - } - } - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array)) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } + if ($store_to_db) { + mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); + + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // get the bridge root port so we don't capture active ports on it + $bridge_root_port = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.2.7.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if ((0 == $highPort) + || (($port_number >= $lowPort) + && ($port_number <= $highPort) + && ($bridge_root_port != $port_number))) { + if (!in_array($port_number, $ignore_ports)) { + if ((isset($port_status[$key]) && '3' == $port_status[$key]) || (isset($port_status[$key]) && '5' == $port_status[$key])) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes)) { + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = $bridgePortIfIndexes[$port_key['port_number']]; + } + if (isset($ifInterfaces[$brPortIfIndex]['ifType'])) { + $brPortIfType = $ifInterfaces[$brPortIfIndex]['ifType']; + } + } else { + $brPortIfIndex = $port_key['port_number']; + if (isset($ifInterfaces[$port_key['port_number']]['ifType'])) { + $brPortIfType = $ifInterfaces[$port_key['port_number']]['ifType']; + } + } + + if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || (71 == $brPortIfType)) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.1', $device, $snmp_readstring, true); + + if (cacti_sizeof($port_macs)) { + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + } + + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_key) { + if (isset($port_macs[$port_key['key']])) { + $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; + mactrack_debug("INDEX: '".$key."' MAC ADDRESS: ".$new_port_key_array[$key]['mac_address']); + } else { + mactrack_debug("INDEX: '".$key."' not found in port_macs array, skipping"); + } + } + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array)) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /** * gethostbyaddr_wtimeout - This function provides a good method of performing * a rapid lookup of a DNS entry for a host so long as you don't have to look far. + * + * @param mixed $ip + * @param mixed $dns + * @param mixed $timeout */ -function mactrack_get_dns_from_ip($ip, $dns, $timeout = 1000) { - /* random transaction number (for routers etc to get the reply back) */ - $data = rand(10, 99); +function mactrack_get_dns_from_ip($ip, $dns, $timeout = 1000) +{ + // random transaction number (for routers etc to get the reply back) + $data = rand(10, 99); - /* trim it to 2 bytes */ - $data = substr($data, 0, 2); + // trim it to 2 bytes + $data = substr($data, 0, 2); - /* create request header */ - $data .= "\1\0\0\1\0\0\0\0\0\0"; + // create request header + $data .= "\1\0\0\1\0\0\0\0\0\0"; - /* split IP into octets */ - $octets = explode('.', $ip); + // split IP into octets + $octets = explode('.', $ip); - /* perform a quick error check */ - if (count($octets) != 4) return 'ERROR'; + // perform a quick error check + if (4 != count($octets)) { + return 'ERROR'; + } - /* needs a byte to indicate the length of each segment of the request */ - for ($x=3; $x>=0; $x--) { - switch (strlen($octets[$x])) { - case 1: // 1 byte long segment - $data .= "\1"; break; - case 2: // 2 byte long segment - $data .= "\2"; break; - case 3: // 3 byte long segment - $data .= "\3"; break; - default: // segment is too big, invalid IP - return 'ERROR'; - } + // needs a byte to indicate the length of each segment of the request + for ($x = 3; $x >= 0; --$x) { + switch (strlen($octets[$x])) { + case 1: // 1 byte long segment + $data .= "\1"; - /* and the segment itself */ - $data .= $octets[$x]; - } + break; - /* and the final bit of the request */ - $data .= "\7in-addr\4arpa\0\0\x0C\0\1"; + case 2: // 2 byte long segment + $data .= "\2"; - /* create UDP socket */ - $handle = @fsockopen("udp://$dns", 53); + break; - @stream_set_timeout($handle, floor($timeout/1000), ($timeout*1000)%1000000); - @stream_set_blocking($handle, 1); + case 3: // 3 byte long segment + $data .= "\3"; - /* send our request (and store request size so we can cheat later) */ - $requestsize = @fwrite($handle, $data); + break; - /* get the response */ - $response = @fread($handle, 1000); + default: // segment is too big, invalid IP + return 'ERROR'; + } - /* check to see if it timed out */ - $info = stream_get_meta_data($handle); + // and the segment itself + $data .= $octets[$x]; + } - /* close the socket */ - @fclose($handle); + // and the final bit of the request + $data .= "\7in-addr\4arpa\0\0\x0C\0\1"; - if ($info['timed_out']) { - return 'timed_out'; - } + // create UDP socket + $handle = @fsockopen("udp://{$dns}", 53); - /* more error handling */ - if ($response == '') { return $ip; } + @stream_set_timeout($handle, floor($timeout / 1000), ($timeout * 1000) % 1000000); + @stream_set_blocking($handle, 1); - /* parse the response and find the response type */ - $type = @unpack('s', substr($response, $requestsize+2)); + // send our request (and store request size so we can cheat later) + $requestsize = @fwrite($handle, $data); - if ($type[1] == 0x0C00) { - /* set up our variables */ - $host = ''; - $len = 0; + // get the response + $response = @fread($handle, 1000); - /* set our pointer at the beginning of the hostname uses the request - size from earlier rather than work it out. - */ - $position = $requestsize + 12; + // check to see if it timed out + $info = stream_get_meta_data($handle); - /* reconstruct the hostname */ - do { - /* get segment size */ - $len = unpack('c', substr($response, $position)); + // close the socket + @fclose($handle); - /* null terminated string, so length 0 = finished */ - if ($len[1] == 0) { - /* return the hostname, without the trailing '.' */ - return substr($host, 0, strlen($host) -1); - } + if ($info['timed_out']) { + return 'timed_out'; + } + + // more error handling + if ('' == $response) { + return $ip; + } + + // parse the response and find the response type + $type = @unpack('s', substr($response, $requestsize + 2)); + + if (0x0C00 == $type[1]) { + // set up our variables + $host = ''; + $len = 0; - /* add the next segment to our host */ - $host .= substr($response, $position+1, $len[1]) . '.'; + /* set our pointer at the beginning of the hostname uses the request + size from earlier rather than work it out. + */ + $position = $requestsize + 12; - /* move pointer on to the next segment */ - $position += $len[1] + 1; - } while ($len != 0); + // reconstruct the hostname + do { + // get segment size + $len = unpack('c', substr($response, $position)); - /* error - return the hostname we constructed (without the . on the end) */ - return $ip; - } + // null terminated string, so length 0 = finished + if (0 == $len[1]) { + // return the hostname, without the trailing '.' + return substr($host, 0, strlen($host) - 1); + } - /* error - return the hostname */ - return $ip; + // add the next segment to our host + $host .= substr($response, $position + 1, $len[1]).'.'; + + // move pointer on to the next segment + $position += $len[1] + 1; + } while (0 != $len); + + // error - return the hostname we constructed (without the . on the end) + return $ip; + } + + // error - return the hostname + return $ip; } /* get_link_port_status - This function walks an the ip mib for ifIndexes with ip addresses aka link ports and then returns that list if ifIndexes with a true array value if an IP exists on that ifIndex. */ -function get_link_port_status(&$device) { - $return_array = array(); - - $walk_array = cacti_snmp_walk($device['hostname'], $device['snmp_readstring'], - '.1.3.6.1.2.1.4.20.1.2', $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries'], $device['max_oids']); - - if (cacti_sizeof($walk_array)) { - foreach ($walk_array as $walk_item) { - $return_array[$walk_item['value']] = true; - } - } - - return $return_array; +function get_link_port_status(&$device) +{ + $return_array = []; + + $walk_array = cacti_snmp_walk( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.4.20.1.2', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + if (cacti_sizeof($walk_array)) { + foreach ($walk_array as $walk_item) { + $return_array[$walk_item['value']] = true; + } + } + + return $return_array; } /* xform_stripped_oid - This function walks an OID and then strips the seed OID from the complete oid. It returns the stripped oid as the key and the return value as the value of the resulting array */ -function xform_stripped_oid($oid, &$device, $snmp_readstring = '', $hex = false) { - $return_array = array(); - - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - if ($device['snmp_version'] == '3' && substr_count($snmp_readstring,'vlan-')) { - $snmp_context = $snmp_readstring; - } else { - $snmp_context = $device['snmp_context']; - } - - $walk_array = cacti_snmp_walk($device['hostname'], $snmp_readstring, - $oid, $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $snmp_context, $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries'], $device['max_oids'], - SNMP_POLLER, $device['snmp_engine_id'], - ($hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS)); - - $oid = preg_replace('/^\./', '', $oid); - - $i = 0; - - if (cacti_sizeof($walk_array)) { - foreach ($walk_array as $walk_item) { - $key = $walk_item['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace($oid . '.', '', $key); - $return_array[$i]['key'] = $key; - $return_array[$i]['value'] = $walk_item['value']; - - $i++; - } - } - - return array_rekey($return_array, 'key', 'value'); +function xform_stripped_oid($oid, &$device, $snmp_readstring = '', $hex = false) +{ + $return_array = []; + + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + if ('3' == $device['snmp_version'] && substr_count($snmp_readstring, 'vlan-')) { + $snmp_context = $snmp_readstring; + } else { + $snmp_context = $device['snmp_context']; + } + + $walk_array = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + $oid, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $snmp_context, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $oid = preg_replace('/^\./', '', $oid); + + $i = 0; + + if (cacti_sizeof($walk_array)) { + foreach ($walk_array as $walk_item) { + $key = $walk_item['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace($oid.'.', '', $key); + $return_array[$i]['key'] = $key; + $return_array[$i]['value'] = $walk_item['value']; + + ++$i; + } + } + + return array_rekey($return_array, 'key', 'value'); } /* xform_net_address - This function will return the IP address. If the agent or snmp returns a differently formatted IP address, then this function will convert it to dotted decimal notation and return. */ -function xform_net_address($ip_address) { - $ip_address = trim($ip_address); - - if (substr_count($ip_address, 'Network Address:')) { - $ip_address = trim(str_replace('Network Address:', '', $ip_address)); - } - - // Handle the binary format first - $length = strlen($ip_address); - if ($length == 4 or $length == 16) { - return inet_ntop(pack('A' . $length, $ip_address)); - } else { - // Adjust for HEX IP in form "0A 09 15 72" - $ip_address = str_replace(' ', ':', $ip_address); - - if (substr_count($ip_address, ':') != 0) { - if (strlen($ip_address) > 11) { - /* ipv6, don't alter */ - } else { - $newaddr = ''; - $address = explode(':', $ip_address); - - foreach($address as $index => $part) { - $newaddr .= ($index == 0 ? '':'.') . hexdec($part); - } - - $ip_address = $newaddr; - } - } +function xform_net_address($ip_address) +{ + $ip_address = trim($ip_address); + + if (substr_count($ip_address, 'Network Address:')) { + $ip_address = trim(str_replace('Network Address:', '', $ip_address)); + } + + // Handle the binary format first + $length = strlen($ip_address); + if (4 == $length or 16 == $length) { + return inet_ntop(pack('A'.$length, $ip_address)); + } + // Adjust for HEX IP in form "0A 09 15 72" + $ip_address = str_replace(' ', ':', $ip_address); + + if (0 != substr_count($ip_address, ':')) { + if (strlen($ip_address) > 11) { + // ipv6, don't alter + } else { + $newaddr = ''; + $address = explode(':', $ip_address); + + foreach ($address as $index => $part) { + $newaddr .= (0 == $index ? '' : '.').hexdec($part); + } - return $ip_address; - } + $ip_address = $newaddr; + } + } + + return $ip_address; } /** xform_mac_address - This function will take a variable that is either formatted as * hex or as a string representing hex and convert it to what the mactrack scanning * function expects. + * + * @param mixed $mac_address */ -function xform_mac_address($mac_address) { - $max_address = trim($mac_address); +function xform_mac_address($mac_address) +{ + $max_address = trim($mac_address); - if ($mac_address == '') { - $mac_address = 'NOT USER'; - } elseif (strlen($mac_address) > 10) { /* return is in ascii */ - $max_address = str_replace( - array('HEX-00:', 'HEX-:', 'HEX-', '"', ' ', '-'), - array('', '', '', '', ':', ':'), - $mac_address - ); - } else { /* return is hex */ - $mac = ''; + if ('' == $mac_address) { + $mac_address = 'NOT USER'; + } elseif (strlen($mac_address) > 10) { // return is in ascii + $max_address = str_replace( + ['HEX-00:', 'HEX-:', 'HEX-', '"', ' ', '-'], + ['', '', '', '', ':', ':'], + $mac_address + ); + } else { // return is hex + $mac = ''; - for ($j = 0; $j < strlen($mac_address); $j++) { - $mac .= bin2hex($mac_address[$j]) . ':'; - } + for ($j = 0; $j < strlen($mac_address); ++$j) { + $mac .= bin2hex($mac_address[$j]).':'; + } - $mac_address = $mac; - } + $mac_address = $mac; + } - $mac_address = str_replace(':', '', $max_address); + $mac_address = str_replace(':', '', $max_address); - return strtoupper($mac_address); + return strtoupper($mac_address); } /** * xform_standard_indexed_data - This function takes an oid, and a device, and * optionally an alternate snmp_readstring as input parameters and then walks the * oid and returns the data in array[index] = value format. + * + * @param mixed $xformOID + * @param mixed $device + * @param mixed $snmp_readstring + * @param mixed $hex */ -function xform_standard_indexed_data($xformOID, &$device, $snmp_readstring = '', $hex = false) { - /* get raw index data */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - if ($device['snmp_version'] == '3' && substr_count($snmp_readstring,'vlan-')) { - $snmp_context = $snmp_readstring; - } else { - $snmp_context = $device['snmp_context']; - } - - $xformArray = cacti_snmp_walk($device['hostname'], $snmp_readstring, - $xformOID, $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $snmp_context, $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries'], $device['max_oids'], - SNMP_POLLER, $device['snmp_engine_id'], - ($hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS)); - - $i = 0; - - if (cacti_sizeof($xformArray)) { - foreach($xformArray as $xformItem) { - $perPos = strrpos($xformItem['oid'], '.'); - $xformItemID = substr($xformItem['oid'], $perPos+1); - $xformArray[$i]['oid'] = $xformItemID; - $i++; - } - } - - return array_rekey($xformArray, 'oid', 'value'); +function xform_standard_indexed_data($xformOID, &$device, $snmp_readstring = '', $hex = false) +{ + // get raw index data + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + if ('3' == $device['snmp_version'] && substr_count($snmp_readstring, 'vlan-')) { + $snmp_context = $snmp_readstring; + } else { + $snmp_context = $device['snmp_context']; + } + + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + $xformOID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $snmp_context, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $i = 0; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + $perPos = strrpos($xformItem['oid'], '.'); + $xformItemID = substr($xformItem['oid'], $perPos + 1); + $xformArray[$i]['oid'] = $xformItemID; + ++$i; + } + } + + return array_rekey($xformArray, 'oid', 'value'); } /** * xform_dot1q_vlan_associations - This function takes an OID, and a device, and * optionally an alternate snmp_readstring as input parameters and then walks the * OID and returns the data in array[index] = value format. + * + * @param mixed $device + * @param mixed $snmp_readstring */ -function xform_dot1q_vlan_associations(&$device, $snmp_readstring = '') { - /* get raw index data */ - if ($snmp_readstring == '') { - $snmp_readstring = $device['snmp_readstring']; - } - - /* initialize the output array */ - $output_array = array(); - - /* obtain vlan associations */ - $xformArray = cacti_snmp_walk($device['hostname'], $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.2.2.1.2', $device['snmp_version'], - $device['snmp_username'], $device['snmp_password'], - $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], $device['snmp_context'], - $device['snmp_port'], $device['snmp_timeout'], - $device['snmp_retries'], $device['max_oids']); - - $i = 0; - - if (cacti_sizeof($xformArray)) { - foreach($xformArray as $xformItem) { - /* peel off the beginning of the OID */ - $key = $xformItem['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); - - /* now grab the VLAN */ - $perPos = strpos($key, '.'); - $output_array[$i]['vlan_id'] = substr($key,0,$perPos); - - /* save the key for association with the dot1d table */ - $output_array[$i]['key'] = substr($key, $perPos+1); - $i++; - } - } - - return array_rekey($output_array, 'key', 'vlan_id'); +function xform_dot1q_vlan_associations(&$device, $snmp_readstring = '') +{ + // get raw index data + if ('' == $snmp_readstring) { + $snmp_readstring = $device['snmp_readstring']; + } + + // initialize the output array + $output_array = []; + + // obtain vlan associations + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.2.2.1.2', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + $i = 0; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + // peel off the beginning of the OID + $key = $xformItem['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); + + // now grab the VLAN + $perPos = strpos($key, '.'); + $output_array[$i]['vlan_id'] = substr($key, 0, $perPos); + + // save the key for association with the dot1d table + $output_array[$i]['key'] = substr($key, $perPos + 1); + ++$i; + } + } + + return array_rekey($output_array, 'key', 'vlan_id'); } /** * xform_cisco_workgroup_port_data - This function is specific to Cisco devices that * use the last two OID values from each complete OID string to represent the switch * card and port. The function returns data in the format array[card.port] = value. + * + * @param mixed $xformOID + * @param mixed $device */ -function xform_cisco_workgroup_port_data($xformOID, &$device) { - /* get raw index data */ - $xformArray = cacti_snmp_walk($device['hostname'], $device['snmp_readstring'], - $xformOID, $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $device['snmp_context'], $device['snmp_port'], - $device['snmp_timeout'], $device['snmp_retries'], $device['max_oids']); - - $i = 0; - - if (cacti_sizeof($xformArray)) { - foreach($xformArray as $xformItem) { - $perPos = strrpos($xformItem['oid'], '.'); - $xformItem_piece1 = substr($xformItem['oid'], $perPos+1); - $xformItem_remainder = substr($xformItem['oid'], 0, $perPos); - $perPos = strrpos($xformItem_remainder, '.'); - $xformItem_piece2 = substr($xformItem_remainder, $perPos+1); - $xformArray[$i]['oid'] = $xformItem_piece2 . '/' . $xformItem_piece1; - - $i++; - } - } - - return array_rekey($xformArray, 'oid', 'value'); +function xform_cisco_workgroup_port_data($xformOID, &$device) +{ + // get raw index data + $xformArray = cacti_snmp_walk( + $device['hostname'], + $device['snmp_readstring'], + $xformOID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + $i = 0; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + $perPos = strrpos($xformItem['oid'], '.'); + $xformItem_piece1 = substr($xformItem['oid'], $perPos + 1); + $xformItem_remainder = substr($xformItem['oid'], 0, $perPos); + $perPos = strrpos($xformItem_remainder, '.'); + $xformItem_piece2 = substr($xformItem_remainder, $perPos + 1); + $xformArray[$i]['oid'] = $xformItem_piece2.'/'.$xformItem_piece1; + + ++$i; + } + } + + return array_rekey($xformArray, 'oid', 'value'); } /** @@ -2173,91 +2446,126 @@ function xform_cisco_workgroup_port_data($xformOID, &$device) { * in that it takes the end of each OID and uses the last $xformLevel positions as the * index. Therefore, if $xformLevel = 3, the return value would be as follows: * array[1.2.3] = value. + * + * @param mixed $xformOID + * @param mixed $device + * @param mixed $xformLevel + * @param mixed $hex */ -function xform_indexed_data($xformOID, &$device, $xformLevel = 1, $hex = false) { - /* get raw index data */ - $xformArray = cacti_snmp_walk($device['hostname'], $device['snmp_readstring'], - $xformOID, $device['snmp_version'], $device['snmp_username'], - $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], - $device['snmp_context'], $device['snmp_port'], - $device['snmp_timeout'], $device['snmp_retries'], $device['max_oids'], - SNMP_POLLER, $device['snmp_engine_id'], - ($hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS)); - - $i = 0; - $output_array = array(); - - if (cacti_sizeof($xformArray)) { - foreach($xformArray as $xformItem) { - /* break down key */ - $OID = $xformItem['oid']; - for ($j = 0; $j < $xformLevel; $j++) { - $perPos = strrpos($OID, '.'); - $xformItem_piece[$j] = substr($OID, $perPos+1); - $OID = substr($OID, 0, $perPos); - } - - /* reassemble key */ - $key = ''; - for ($j = $xformLevel-1; $j >= 0; $j--) { - $key .= $xformItem_piece[$j]; - if ($j > 0) { - $key .= '.'; - } - } - - $output_array[$i]['key'] = $key; - $output_array[$i]['value'] = $xformItem['value']; - - $i++; - } - } - - return array_rekey($output_array, 'key', 'value'); +function xform_indexed_data($xformOID, &$device, $xformLevel = 1, $hex = false) +{ + // get raw index data + $xformArray = cacti_snmp_walk( + $device['hostname'], + $device['snmp_readstring'], + $xformOID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $i = 0; + $output_array = []; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + // break down key + $OID = $xformItem['oid']; + for ($j = 0; $j < $xformLevel; ++$j) { + $perPos = strrpos($OID, '.'); + $xformItem_piece[$j] = substr($OID, $perPos + 1); + $OID = substr($OID, 0, $perPos); + } + + // reassemble key + $key = ''; + for ($j = $xformLevel - 1; $j >= 0; --$j) { + $key .= $xformItem_piece[$j]; + if ($j > 0) { + $key .= '.'; + } + } + + $output_array[$i]['key'] = $key; + $output_array[$i]['value'] = $xformItem['value']; + + ++$i; + } + } + + return array_rekey($output_array, 'key', 'value'); } /** * db_process_add - This function adds a process to the process table with the entry * with the device_id as key. -*/ -function db_process_add($device_id, $storepid = false) { - /* store the PID if required */ - if ($storepid) { - $pid = getmypid(); - } else { - $pid = 0; - } - - /* store pseudo process id in the database */ - db_execute_prepared('REPLACE INTO mac_track_processes + * + * @param mixed $device_id + * @param mixed $storepid + */ +function db_process_add($device_id, $storepid = false) +{ + // store the PID if required + if ($storepid) { + $pid = getmypid(); + } else { + $pid = 0; + } + + // store pseudo process id in the database + db_execute_prepared( + 'REPLACE INTO mac_track_processes (device_id, process_id, status, start_date) VALUES (?, ?, "Running", NOW())', - array($device_id, $pid)); + [$device_id, $pid] + ); } /** * db_process_remove - This function removes a devices entry from the processes * table indicating that the device is done processing and the next device may start. + * + * @param mixed $device_id */ -function db_process_remove($device_id) { - db_execute_prepared('DELETE FROM mac_track_processes +function db_process_remove($device_id) +{ + db_execute_prepared( + 'DELETE FROM mac_track_processes WHERE device_id = ?', - array($device_id)); + [$device_id] + ); } /** * db_update_device_status - This function is used by the scanner to save the status * of the current device including the number of ports, it's readstring, etc. + * + * @param mixed $device + * @param mixed $host_up + * @param mixed $scan_date + * @param mixed $start_time */ -function db_update_device_status(&$device, $host_up, $scan_date, $start_time) { - global $debug; +function db_update_device_status(&$device, $host_up, $scan_date, $start_time) +{ + global $debug; - $end_time = microtime(true); - $runduration = $end_time - $start_time; + $end_time = microtime(true); + $runduration = $end_time - $start_time; - if ($host_up == true) { - db_execute_prepared('UPDATE mac_track_devices + if (true == $host_up) { + db_execute_prepared( + 'UPDATE mac_track_devices SET ports_total = ?, device_type_id = ?, scan_type = ?, vlans_total = ?, ports_active = ?, ports_trunk = ?, macs_active = ?, snmp_version = ?, snmp_readstring = ?, snmp_port = ?, snmp_timeout = ?, snmp_retries = ?, @@ -2267,875 +2575,980 @@ function db_update_device_status(&$device, $host_up, $scan_date, $start_time) { snmp_sysUptime = ?, snmp_status = ?, last_runmessage = ?, last_rundate = ?, last_runduration = ? WHERE device_id = ?', - array( - $device['ports_total'], $device['device_type_id'], $device ['scan_type'], $device['vlans_total'], - $device['ports_active'], $device['ports_trunk'], $device['macs_active'], $device['snmp_version'], - $device['snmp_readstring'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - $device['max_oids'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_sysName'], - $device['snmp_sysLocation'], $device['snmp_sysContact'], $device['snmp_sysObjectID'], $device['snmp_sysDescr'], - $device['snmp_sysUptime'], $device['snmp_status'], $device['last_runmessage'], $scan_date, - round($runduration,4), $device['device_id'] - ) - ); - } else { - db_execute_prepared('UPDATE mac_track_devices + [ + $device['ports_total'], $device['device_type_id'], $device['scan_type'], $device['vlans_total'], + $device['ports_active'], $device['ports_trunk'], $device['macs_active'], $device['snmp_version'], + $device['snmp_readstring'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], + $device['max_oids'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_sysName'], + $device['snmp_sysLocation'], $device['snmp_sysContact'], $device['snmp_sysObjectID'], $device['snmp_sysDescr'], + $device['snmp_sysUptime'], $device['snmp_status'], $device['last_runmessage'], $scan_date, + round($runduration, 4), $device['device_id'], + ] + ); + } else { + db_execute_prepared( + 'UPDATE mac_track_devices SET snmp_status = ?, device_type_id = ?, scan_type = ?, vlans_total = 0, ports_active = 0, ports_trunk = 0, macs_active = 0, last_runmessage = "Device Unreachable", last_rundate = ?, last_runduration = ? WHERE device_id =?', - array( - $device['snmp_status'], - $device['device_type_id'], - $device ['scan_type'], - $scan_date, - round($runduration,4), - $device['device_id'] - ) - ); - } + [ + $device['snmp_status'], + $device['device_type_id'], + $device['scan_type'], + $scan_date, + round($runduration, 4), + $device['device_id'], + ] + ); + } } /** * db_store_device_results - This function stores each of the port results into * the temporary port results table for future processes once all devices have been * scanned. + * + * @param mixed $device + * @param mixed $port_array + * @param mixed $scan_date */ -function db_store_device_port_results(&$device, $port_array, $scan_date) { - global $debug; - - /* output details to database */ - if (cacti_sizeof($port_array)) { - foreach($port_array as $port_value) { - if ($port_value['port_number'] <> 'NOT USER' && $port_value['mac_address'] <> 'NOT USER' && $port_value['mac_address'] != '') { - $mac_authorized = db_check_auth($port_value['mac_address']); - - mactrack_debug('MAC Address \'' . $port_value['mac_address'] . '\' on device \'' . $device['device_name'] . '\' is ' . ($mac_authorized != '' ? '':'NOT ') . 'Authorized'); - - if ($mac_authorized != '') { - $authorized_mac = 1; - } else { - $authorized_mac = 0; - } - - if (!isset($port_value['vlan_id'])) { - $port_value['vlan_id'] = 'N/A'; - } - - if (!isset($port_value['vlan_name'])) { - $port_value['vlan_name'] = 'N/A'; - } - - db_execute_prepared('REPLACE INTO mac_track_temp_ports +function db_store_device_port_results(&$device, $port_array, $scan_date) +{ + global $debug; + + // output details to database + if (cacti_sizeof($port_array)) { + foreach ($port_array as $port_value) { + if ('NOT USER' != $port_value['port_number'] && 'NOT USER' != $port_value['mac_address'] && '' != $port_value['mac_address']) { + $mac_authorized = db_check_auth($port_value['mac_address']); + + mactrack_debug('MAC Address \''.$port_value['mac_address'].'\' on device \''.$device['device_name'].'\' is '.('' != $mac_authorized ? '' : 'NOT ').'Authorized'); + + if ('' != $mac_authorized) { + $authorized_mac = 1; + } else { + $authorized_mac = 0; + } + + if (!isset($port_value['vlan_id'])) { + $port_value['vlan_id'] = 'N/A'; + } + + if (!isset($port_value['vlan_name'])) { + $port_value['vlan_name'] = 'N/A'; + } + + db_execute_prepared( + 'REPLACE INTO mac_track_temp_ports (site_id,device_id,hostname,device_name,vlan_id,vlan_name, mac_address,port_number,port_name,scan_date,authorized) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', - array( - $device['site_id'], - $device['device_id'], - $device['hostname'], - $device['device_name'], - $port_value['vlan_id'], - $port_value['vlan_name'], - $port_value['mac_address'], - $port_value['port_number'], - $port_value['port_name'], - $scan_date, - $authorized_mac - ) - ); - } - } - } -} - -/* db_check_auth - This function checks whether the mac address exists in the mac_track+macauth table -*/ -function db_check_auth($mac_address) { - $query = db_fetch_cell_prepared('SELECT mac_id + [ + $device['site_id'], + $device['device_id'], + $device['hostname'], + $device['device_name'], + $port_value['vlan_id'], + $port_value['vlan_name'], + $port_value['mac_address'], + $port_value['port_number'], + $port_value['port_name'], + $scan_date, + $authorized_mac, + ] + ); + } + } + } +} + +// db_check_auth - This function checks whether the mac address exists in the mac_track+macauth table +function db_check_auth($mac_address) +{ + return db_fetch_cell_prepared( + 'SELECT mac_id FROM mac_track_macauth WHERE mac_address LIKE ?', - array('%' . $mac_address . '%')); - - return $query; + ['%'.$mac_address.'%'] + ); } -/* db_check_for_ip - This function checks whether the mac address has a matching IP address in the mac_track_arp table -*/ -function db_check_for_ip($mac_address) { - $query = db_fetch_cell_prepared('SELECT ip_address +// db_check_for_ip - This function checks whether the mac address has a matching IP address in the mac_track_arp table +function db_check_for_ip($mac_address) +{ + return db_fetch_cell_prepared( + 'SELECT ip_address FROM mac_track_arp WHERE mac_address LIKE ?', - array('%' . $mac_address . '%')); - return $query; + ['%'.$mac_address.'%'] + ); } /** * perform_mactrack_db_maint - This utility removes stale records from the database. */ -function perform_mactrack_db_maint() { - global $database_default; - - /* remove stale records from the poller database */ - $retention = read_config_option('mt_data_retention'); - if (is_numeric($retention)) { - $retention_date = date('Y-m-d H:i:s', time() - ($retention * 86400)); - $days = $retention; - } else { - switch ($retention) { - case '2days': - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); - break; - case '5days': - $retention_date = date('Y-m-d H:i:s', strtotime('-5 Days')); - break; - case '1week': - $retention_date = date('Y-m-d H:i:s', strtotime('-1 Week')); - break; - case '2weeks': - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Week')); - break; - case '3weeks': - $retention_date = date('Y-m-d H:i:s', strtotime('-3 Week')); - break; - case '1month': - $retention_date = date('Y-m-d H:i:s', strtotime('-1 Month')); - break; - case '2months': - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Months')); - break; - default: - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); - } - - $days = ceil((time() - strtotime($retention_date)) / 86400); - } - - set_config_option('mt_data_retention', $days); - - mactrack_debug('Started deleting old records from the main database.'); - - $syntax = db_fetch_row('SHOW CREATE TABLE mac_track_ports'); - if (substr_count($syntax['Create Table'], 'PARTITION')) { - $partitioned = true; - } else { - $partitioned = false; - } - - /* delete old syslog and syslog soft messages */ - if ($retention > 0 || $partitioned) { - if (!$partitioned) { - db_execute_prepared('DELETE QUICK FROM mac_track_ports WHERE scan_date < ?', array($retention_date)); - db_execute('OPTIMIZE TABLE mac_track_ports'); - } else { - $syslog_deleted = 0; - $number_of_partitions = db_fetch_assoc_prepared('SELECT * +function perform_mactrack_db_maint() +{ + global $database_default; + + // remove stale records from the poller database + $retention = read_config_option('mt_data_retention'); + if (is_numeric($retention)) { + $retention_date = date('Y-m-d H:i:s', time() - ($retention * 86400)); + $days = $retention; + } else { + switch ($retention) { + case '2days': + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); + + break; + + case '5days': + $retention_date = date('Y-m-d H:i:s', strtotime('-5 Days')); + + break; + + case '1week': + $retention_date = date('Y-m-d H:i:s', strtotime('-1 Week')); + + break; + + case '2weeks': + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Week')); + + break; + + case '3weeks': + $retention_date = date('Y-m-d H:i:s', strtotime('-3 Week')); + + break; + + case '1month': + $retention_date = date('Y-m-d H:i:s', strtotime('-1 Month')); + + break; + + case '2months': + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Months')); + + break; + + default: + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); + } + + $days = ceil((time() - strtotime($retention_date)) / 86400); + } + + set_config_option('mt_data_retention', $days); + + mactrack_debug('Started deleting old records from the main database.'); + + $syntax = db_fetch_row('SHOW CREATE TABLE mac_track_ports'); + if (substr_count($syntax['Create Table'], 'PARTITION')) { + $partitioned = true; + } else { + $partitioned = false; + } + + // delete old syslog and syslog soft messages + if ($retention > 0 || $partitioned) { + if (!$partitioned) { + db_execute_prepared('DELETE QUICK FROM mac_track_ports WHERE scan_date < ?', [$retention_date]); + db_execute('OPTIMIZE TABLE mac_track_ports'); + } else { + $syslog_deleted = 0; + $number_of_partitions = db_fetch_assoc_prepared( + 'SELECT * FROM `information_schema`.`partitions` WHERE table_schema = ? AND table_name="mac_track_ports" ORDER BY partition_ordinal_position', - array($database_default)); - - /* - $time = time(); - $now = date('Y-m-d', $time); - $format = date('Ymd', $time); - $cur_day = db_fetch_row("SELECT TO_DAYS('$now') AS today"); - $cur_day = $cur_day['today']; - - $lday_ts = read_config_option('mactrack_lastday_timestamp'); - $lnow = date('Y-m-d', $lday_ts); - $lformat = date('Ymd', $lday_ts); - $last_day = db_fetch_row("SELECT TO_DAYS('$lnow') AS today"); - $last_day = $last_day['today']; - */ - - $tday_ts = strtotime('Today'); - $tday = date('Y-m-d', $tday_ts); - $tdformat = date('Ymd', $tday_ts); - $cur_day = db_fetch_row("SELECT TO_DAYS('$tday') AS today"); - $cur_day = $cur_day['today']; - - $lday_ts = strtotime('Yesterday'); - $lday = date('Y-m-d', $lday_ts); - $ldformat = date('Ymd', $lday_ts); - $last_day = db_fetch_row("SELECT TO_DAYS('$lday') AS today"); - $last_day = $last_day['today']; - - mactrack_debug("There are currently '" . cacti_sizeof($number_of_partitions) . "' Mactrack Partitions, We will keep '$days' of them."); - mactrack_debug("The current day is '$tday($cur_day)', the last day is '$lday($last_day)'"); - - if ($cur_day != $last_day) { - //set_config_option('mactrack_lastday_timestamp', $time); //no use - - if ($lday_ts != '') { - cacti_log("MACTRACK: Creating new partition 'd" . $ldformat . "'", false, "SYSTEM"); - mactrack_debug("Creating new partition 'd" . $ldformat . "'"); - db_execute("ALTER TABLE mac_track_ports REORGANIZE PARTITION dMaxValue INTO ( - PARTITION d" . $ldformat . " VALUES LESS THAN ($cur_day), + [$database_default] + ); + + /* + $time = time(); + $now = date('Y-m-d', $time); + $format = date('Ymd', $time); + $cur_day = db_fetch_row("SELECT TO_DAYS('$now') AS today"); + $cur_day = $cur_day['today']; + + $lday_ts = read_config_option('mactrack_lastday_timestamp'); + $lnow = date('Y-m-d', $lday_ts); + $lformat = date('Ymd', $lday_ts); + $last_day = db_fetch_row("SELECT TO_DAYS('$lnow') AS today"); + $last_day = $last_day['today']; + */ + + $tday_ts = strtotime('Today'); + $tday = date('Y-m-d', $tday_ts); + $tdformat = date('Ymd', $tday_ts); + $cur_day = db_fetch_row("SELECT TO_DAYS('{$tday}') AS today"); + $cur_day = $cur_day['today']; + + $lday_ts = strtotime('Yesterday'); + $lday = date('Y-m-d', $lday_ts); + $ldformat = date('Ymd', $lday_ts); + $last_day = db_fetch_row("SELECT TO_DAYS('{$lday}') AS today"); + $last_day = $last_day['today']; + + mactrack_debug("There are currently '".cacti_sizeof($number_of_partitions)."' Mactrack Partitions, We will keep '{$days}' of them."); + mactrack_debug("The current day is '{$tday}({$cur_day})', the last day is '{$lday}({$last_day})'"); + + if ($cur_day != $last_day) { + // set_config_option('mactrack_lastday_timestamp', $time); //no use + + if ('' != $lday_ts) { + cacti_log("MACTRACK: Creating new partition 'd".$ldformat."'", false, 'SYSTEM'); + mactrack_debug("Creating new partition 'd".$ldformat."'"); + db_execute('ALTER TABLE mac_track_ports REORGANIZE PARTITION dMaxValue INTO ( + PARTITION d'.$ldformat." VALUES LESS THAN ({$cur_day}), PARTITION dMaxValue VALUES LESS THAN MAXVALUE)"); - if ($days > 0) { - /* - $user_partitions = cacti_sizeof($number_of_partitions) - 1; - if ($user_partitions >= $days) { - $i = 0; - while ($user_partitions > $days) { - $oldest = $number_of_partitions[$i]; - cacti_log("MACTRACK: Removing old partition 'd" . $oldest["PARTITION_NAME"] . "'", false, "SYSTEM"); - mactrack_debug("Removing partition '" . $oldest['PARTITION_NAME'] . "'"); - db_execute("ALTER TABLE mac_track_ports DROP PARTITION " . $oldest['PARTITION_NAME']); - $i++; - $user_partitions--; - $mactrack_deleted++; - } - } - */ - - $old_day = date('Ymd', strtotime("- $days Days")); - $old_partitions = db_fetch_assoc_prepared('SELECT PARTITION_NAME + if ($days > 0) { + /* + $user_partitions = cacti_sizeof($number_of_partitions) - 1; + if ($user_partitions >= $days) { + $i = 0; + while ($user_partitions > $days) { + $oldest = $number_of_partitions[$i]; + cacti_log("MACTRACK: Removing old partition 'd" . $oldest["PARTITION_NAME"] . "'", false, "SYSTEM"); + mactrack_debug("Removing partition '" . $oldest['PARTITION_NAME'] . "'"); + db_execute("ALTER TABLE mac_track_ports DROP PARTITION " . $oldest['PARTITION_NAME']); + $i++; + $user_partitions--; + $mactrack_deleted++; + } + } + */ + + $old_day = date('Ymd', strtotime("- {$days} Days")); + $old_partitions = db_fetch_assoc_prepared( + 'SELECT PARTITION_NAME FROM `information_schema`.`partitions` WHERE table_schema = ? AND table_name="mac_track_ports" AND partition_name < ? ORDER BY partition_ordinal_position', - array($database_default, 'd' . $old_day)); - - if (cacti_sizeof($old_partitions) > 0) { - foreach ($old_partitions as $old_partition) { - cacti_log("MACTRACK: Removing old partition '" . $old_partition['PARTITION_NAME'] . "'", false, "SYSTEM"); - mactrack_debug("Removing partition '" . $old_partition['PARTITION_NAME'] . "'"); - db_execute("ALTER TABLE mac_track_ports DROP PARTITION " . $old_partition['PARTITION_NAME']); - } - } - } - } - } - } - } - - db_execute_prepared('DELETE FROM mac_track_ips + [$database_default, 'd'.$old_day] + ); + + if (cacti_sizeof($old_partitions) > 0) { + foreach ($old_partitions as $old_partition) { + cacti_log("MACTRACK: Removing old partition '".$old_partition['PARTITION_NAME']."'", false, 'SYSTEM'); + mactrack_debug("Removing partition '".$old_partition['PARTITION_NAME']."'"); + db_execute('ALTER TABLE mac_track_ports DROP PARTITION '.$old_partition['PARTITION_NAME']); + } + } + } + } + } + } + } + + db_execute_prepared( + 'DELETE FROM mac_track_ips WHERE scan_date < DATE_FORMAT(CURDATE() - ?,"%Y-%m-%d")', - array(read_config_option('mt_data_retention_ip'))); - db_execute('OPTIMIZE TABLE mac_track_ips'); + [read_config_option('mt_data_retention_ip')] + ); + db_execute('OPTIMIZE TABLE mac_track_ips'); - db_execute('REPLACE INTO mac_track_scan_dates + db_execute('REPLACE INTO mac_track_scan_dates (SELECT DISTINCT scan_date FROM mac_track_ports)'); - db_execute('DELETE FROM mac_track_scan_dates + db_execute('DELETE FROM mac_track_scan_dates WHERE scan_date NOT IN ( SELECT DISTINCT scan_date FROM mac_track_ports )'); - mactrack_debug('Finished deleting old records from the main database.'); -} - -function import_oui_database($type = 'ui', $oui_file = 'http://standards-oui.ieee.org/oui.txt') { - $oui_alternate = 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-L&format=txt'; - if ($type != 'ui') { - html_start_box(__('Mactrack Device Tracking OUI Database Import Results', 'mactrack'), '100%', '', '1', 'center', ''); - print '' . __('Getting OUI Database from IEEE', 'mactrack') . ''; - } else { - print __('Getting OUI Database from the IEEE', 'mactrack') . PHP_EOL; - } - - $proxy = read_config_option('settings_proxy_server'); - $proxy_user = read_config_option('settings_proxy_user'); - $proxy_password = read_config_option('settings_proxy_password'); - - if ($proxy != '') { - $default_opts = array( - 'http' => array( - 'proxy' => $proxy, - 'method' => 'GET', - ) - ); - - if ($proxy_user != '') { - $default_opts = array( - 'http' => array( - 'header' => 'Proxy-Authorization: Basic ' . base64_encode("$proxy_user:$proxy_password") - ) - ); - } - - $default = stream_context_set_default($default_opts); - } - - $oui_database = file($oui_file); - - if ($type != 'ui') print ''; - - if (is_array($oui_database)) { - print __('OUI Database Download from IEEE Complete', 'mactrack') . PHP_EOL; - } else { - print __('OUI Database Download from IEEE FAILED', 'mactrack') . PHP_EOL; - } - - if ($type != 'ui') print ''; - - if (is_array($oui_database)) { - db_execute('UPDATE mac_track_oui_database SET present=0'); - - /* initialize some variables */ - $begin_vendor = false; - $vendor_mac = ''; - $vendor_name = ''; - $vendor_address = ''; - $i = 0; - $sql = ''; - - if ($type != 'ui') print ''; - - if (cacti_sizeof($oui_database)) { - foreach ($oui_database as $row) { - $row = str_replace("\t", ' ', $row); - if ($begin_vendor && trim($row) == '') { - if (substr($vendor_address,0,1) == ',') $vendor_address = substr($vendor_address,1); - if (substr($vendor_name,0,1) == ',') $vendor_name = substr($vendor_name,1); - - $sql .= ($sql != '' ? ',':'') . - '(' . - db_qstr($vendor_mac) . ', ' . - db_qstr(ucwords(strtolower($vendor_name))) . ', ' . - db_qstr(str_replace("\n", ', ', ucwords(strtolower(trim($vendor_address))))) . ', 1)'; - - /* let the user know you are working */ - if ((($i % 1000) == 0) && ($type == 'ui')) { - print '.'; - - db_execute('REPLACE INTO mac_track_oui_database + mactrack_debug('Finished deleting old records from the main database.'); +} + +function import_oui_database($type = 'ui', $oui_file = 'http://standards-oui.ieee.org/oui.txt') +{ + $oui_alternate = 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-L&format=txt'; + if ('ui' != $type) { + html_start_box(__('Mactrack Device Tracking OUI Database Import Results', 'mactrack'), '100%', '', '1', 'center', ''); + echo ''.__('Getting OUI Database from IEEE', 'mactrack').''; + } else { + echo __('Getting OUI Database from the IEEE', 'mactrack').PHP_EOL; + } + + $proxy = read_config_option('settings_proxy_server'); + $proxy_user = read_config_option('settings_proxy_user'); + $proxy_password = read_config_option('settings_proxy_password'); + + if ('' != $proxy) { + $default_opts = [ + 'http' => [ + 'proxy' => $proxy, + 'method' => 'GET', + ], + ]; + + if ('' != $proxy_user) { + $default_opts = [ + 'http' => [ + 'header' => 'Proxy-Authorization: Basic '.base64_encode("{$proxy_user}:{$proxy_password}"), + ], + ]; + } + + $default = stream_context_set_default($default_opts); + } + + $oui_database = file($oui_file); + + if ('ui' != $type) { + echo ''; + } + + if (is_array($oui_database)) { + echo __('OUI Database Download from IEEE Complete', 'mactrack').PHP_EOL; + } else { + echo __('OUI Database Download from IEEE FAILED', 'mactrack').PHP_EOL; + } + + if ('ui' != $type) { + echo ''; + } + + if (is_array($oui_database)) { + db_execute('UPDATE mac_track_oui_database SET present=0'); + + // initialize some variables + $begin_vendor = false; + $vendor_mac = ''; + $vendor_name = ''; + $vendor_address = ''; + $i = 0; + $sql = ''; + + if ('ui' != $type) { + echo ''; + } + + if (cacti_sizeof($oui_database)) { + foreach ($oui_database as $row) { + $row = str_replace("\t", ' ', $row); + if ($begin_vendor && '' == trim($row)) { + if (',' == substr($vendor_address, 0, 1)) { + $vendor_address = substr($vendor_address, 1); + } + if (',' == substr($vendor_name, 0, 1)) { + $vendor_name = substr($vendor_name, 1); + } + + $sql .= ('' != $sql ? ',' : '') + .'(' + .db_qstr($vendor_mac).', ' + .db_qstr(ucwords(strtolower($vendor_name))).', ' + .db_qstr(str_replace("\n", ', ', ucwords(strtolower(trim($vendor_address))))).', 1)'; + + // let the user know you are working + if ((($i % 1000) == 0) && ('ui' == $type)) { + echo '.'; + + db_execute('REPLACE INTO mac_track_oui_database (vendor_mac, vendor_name, vendor_address, present) - VALUES ' . $sql); - - $sql = ''; - } - - $i++; - - /* reinitialize variables */ - $begin_vendor = false; - $vendor_mac = ''; - $vendor_name = ''; - $vendor_address = ''; - } else { - if ($begin_vendor) { - if (strpos($row, '(base 16)')) { - $address_start = strpos($row, '(base 16)') + 10; - $vendor_address .= trim(substr($row,$address_start)) . "\n"; - } else { - $vendor_address .= trim($row) . "\n"; - } - } else { - $vendor_address = ''; - } - } - - if (substr_count($row, '(hex)')) { - $begin_vendor = true; - $vendor_mac = str_replace('-', '', substr(trim($row), 0, 8)); - $hex_end = strpos($row, '(hex)') + 5; - $vendor_name= trim(substr($row,$hex_end)); - } - } - } - - if ($sql != '') { - db_execute('REPLACE INTO mac_track_oui_database + VALUES '.$sql); + + $sql = ''; + } + + ++$i; + + // reinitialize variables + $begin_vendor = false; + $vendor_mac = ''; + $vendor_name = ''; + $vendor_address = ''; + } else { + if ($begin_vendor) { + if (strpos($row, '(base 16)')) { + $address_start = strpos($row, '(base 16)') + 10; + $vendor_address .= trim(substr($row, $address_start))."\n"; + } else { + $vendor_address .= trim($row)."\n"; + } + } else { + $vendor_address = ''; + } + } + + if (substr_count($row, '(hex)')) { + $begin_vendor = true; + $vendor_mac = str_replace('-', '', substr(trim($row), 0, 8)); + $hex_end = strpos($row, '(hex)') + 5; + $vendor_name = trim(substr($row, $hex_end)); + } + } + } + + if ('' != $sql) { + db_execute('REPLACE INTO mac_track_oui_database (vendor_mac, vendor_name, vendor_address, present) - VALUES ' . $sql); - } - - if ($type != 'ui') print ''; - - /* count bogus records */ - $j = db_fetch_cell('SELECT count(*) FROM mac_track_oui_database WHERE present=0'); - - /* get rid of old records */ - db_execute('DELETE FROM mac_track_oui_database WHERE present=0'); - - /* set correct format */ - db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); - - /* report some information */ - if ($type != 'ui') print ''; - print PHP_EOL . __('There were \'%d\' Entries Added/Updated in the database.', $i, 'mactrack'); - if ($type != 'ui') print ''; - print PHP_EOL . __('There were \'%d\' Records Removed from the database.', $j, 'mactrack') . PHP_EOL; - if ($type != 'ui') print ''; - - if ($type != 'ui') html_end_box(); - } -} - -function get_netscreen_arp_table($site, &$device) { - global $debug, $scan_date; - - /* get the atifIndexes for the device */ - $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.3.1.1.1', $device, 6); - - if (cacti_sizeof($atifIndexes)) { - $ifIntcount = 1; - } else { - $ifIntcount = 0; - } - - if ($ifIntcount != 0) { - $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.4.22.1.1', $device, 5); - } - mactrack_debug(__('atifIndexes data collection complete', 'mactrack')); - - /* get the atPhysAddress for the device */ - if ($ifIntcount != 0) { - $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.2', $device, 5, true); - } else { - $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.2', $device, 6, true); - } - - /* convert the mac address if necessary */ - $keys = array_keys($atPhysAddress); - $i = 0; - if (cacti_sizeof($atPhysAddress)) { - foreach($atPhysAddress as $atAddress) { - $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); - $i++; - } - } - mactrack_debug(__('atPhysAddress data collection complete', 'mactrack')); - - /* get the atPhysAddress for the device */ - if ($ifIntcount != 0) { - $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.3', $device, 5); - } else { - $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.3', $device, 6); - } - mactrack_debug(__('atNetAddress data collection complete', 'mactrack')); - - /* get the ifNames for the device */ - $keys = array_keys($atifIndexes); - $i = 0; - if (cacti_sizeof($atifIndexes)) { - foreach($atifIndexes as $atifIndex) { - $atEntries[$i]['atifIndex'] = $atifIndex; - $atEntries[$i]['atPhysAddress'] = $atPhysAddress[$keys[$i]]; - $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$keys[$i]]); - $i++; - } - } - mactrack_debug(__('atEntries assembly complete.', 'mactrack')); - - /* output details to database */ - if (cacti_sizeof($atEntries)) { - foreach($atEntries as $atEntry) { - db_execute_prepared('REPLACE INTO mac_track_ips + VALUES '.$sql); + } + + if ('ui' != $type) { + echo ''; + } + + // count bogus records + $j = db_fetch_cell('SELECT count(*) FROM mac_track_oui_database WHERE present=0'); + + // get rid of old records + db_execute('DELETE FROM mac_track_oui_database WHERE present=0'); + + // set correct format + db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); + + // report some information + if ('ui' != $type) { + echo ''; + } + echo PHP_EOL.__('There were \'%d\' Entries Added/Updated in the database.', $i, 'mactrack'); + if ('ui' != $type) { + echo ''; + } + echo PHP_EOL.__('There were \'%d\' Records Removed from the database.', $j, 'mactrack').PHP_EOL; + if ('ui' != $type) { + echo ''; + } + + if ('ui' != $type) { + html_end_box(); + } + } +} + +function get_netscreen_arp_table($site, &$device) +{ + global $debug, $scan_date; + + // get the atifIndexes for the device + $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.3.1.1.1', $device, 6); + + if (cacti_sizeof($atifIndexes)) { + $ifIntcount = 1; + } else { + $ifIntcount = 0; + } + + if (0 != $ifIntcount) { + $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.4.22.1.1', $device, 5); + } + mactrack_debug(__('atifIndexes data collection complete', 'mactrack')); + + // get the atPhysAddress for the device + if (0 != $ifIntcount) { + $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.2', $device, 5, true); + } else { + $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.2', $device, 6, true); + } + + // convert the mac address if necessary + $keys = array_keys($atPhysAddress); + $i = 0; + if (cacti_sizeof($atPhysAddress)) { + foreach ($atPhysAddress as $atAddress) { + $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); + ++$i; + } + } + mactrack_debug(__('atPhysAddress data collection complete', 'mactrack')); + + // get the atPhysAddress for the device + if (0 != $ifIntcount) { + $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.3', $device, 5); + } else { + $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.3', $device, 6); + } + mactrack_debug(__('atNetAddress data collection complete', 'mactrack')); + + // get the ifNames for the device + $keys = array_keys($atifIndexes); + $i = 0; + if (cacti_sizeof($atifIndexes)) { + foreach ($atifIndexes as $atifIndex) { + $atEntries[$i]['atifIndex'] = $atifIndex; + $atEntries[$i]['atPhysAddress'] = $atPhysAddress[$keys[$i]]; + $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$keys[$i]]); + ++$i; + } + } + mactrack_debug(__('atEntries assembly complete.', 'mactrack')); + + // output details to database + if (cacti_sizeof($atEntries)) { + foreach ($atEntries as $atEntry) { + db_execute_prepared( + 'REPLACE INTO mac_track_ips (site_id,device_id,hostname,device_name,port_number, mac_address,ip_address,scan_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - array( - $device['site_id'], - $device['device_id'], - $device['hostname'], - $device['device_name'], - $atEntry['atifIndex'], - $atEntry['atPhysAddress'], - $atEntry['atNetAddress'], - $scan_date - ) - ); - } - } - - /* save ip information for the device */ - $device['ips_total'] = cacti_sizeof($atEntries); - - db_execute_prepared('UPDATE mac_track_devices + [ + $device['site_id'], + $device['device_id'], + $device['hostname'], + $device['device_name'], + $atEntry['atifIndex'], + $atEntry['atPhysAddress'], + $atEntry['atNetAddress'], + $scan_date, + ] + ); + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($atEntries); + + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - array($device['ips_total'], $device['device_id'])); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug(__('HOST: %s, IP address information collection complete', $device['hostname'], 'mactrack')); + mactrack_debug(__('HOST: %s, IP address information collection complete', $device['hostname'], 'mactrack')); } -function mactrack_interface_actions($device_id, $ifIndex, $show_rescan = true) { - global $config; +function mactrack_interface_actions($device_id, $ifIndex, $show_rescan = true) +{ + global $config; - $row = ''; - $rescan = ''; + $row = ''; + $rescan = ''; - $device = db_fetch_row_prepared('SELECT host_id, disabled + $device = db_fetch_row_prepared( + 'SELECT host_id, disabled FROM mac_track_devices WHERE device_id = ?', - array($device_id)); - - if ($show_rescan) { - if (api_user_realm_auth('mactrack_sites.php')) { - if ($device['disabled'] == '') { - $rescan = ""; - } - } - } - - if ($device['host_id'] != 0) { - /* get non-interface graphs */ - $graphs = db_fetch_assoc_prepared('SELECT DISTINCT gl.id AS local_graph_id + [$device_id] + ); + + if ($show_rescan) { + if (api_user_realm_auth('mactrack_sites.php')) { + if ('' == $device['disabled']) { + $rescan = ""; + } + } + } + + if (0 != $device['host_id']) { + // get non-interface graphs + $graphs = db_fetch_assoc_prepared( + 'SELECT DISTINCT gl.id AS local_graph_id FROM mac_track_interface_graphs AS mtig RIGHT JOIN graph_local AS gl ON gl.host_id=mtig.host_id AND gl.id=mtig.local_graph_id WHERE gl.host_id = ? AND mtig.device_id IS NULL', - array($device['host_id'])); - - if (cacti_sizeof($graphs)) { - $url = $config['url_path'] . 'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; - $list = ''; - foreach($graphs as $graph) { - $list .= ($list != '' ? ',': '') . $graph['local_graph_id']; - } - - $row .= ""; - } else { - $row .= ""; - } - - /* get interface graphs */ - $graphs = db_fetch_assoc_prepared('SELECT local_graph_id + [$device['host_id']] + ); + + if (cacti_sizeof($graphs)) { + $url = $config['url_path'].'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; + $list = ''; + foreach ($graphs as $graph) { + $list .= ('' != $list ? ',' : '').$graph['local_graph_id']; + } + + $row .= ""; + } else { + $row .= ""; + } + + // get interface graphs + $graphs = db_fetch_assoc_prepared( + 'SELECT local_graph_id FROM mac_track_interface_graphs WHERE host_id = ? AND ifIndex = ?', - array($device['host_id'], $ifIndex)); + [$device['host_id'], $ifIndex] + ); + + if (cacti_sizeof($graphs)) { + $url = $config['url_path'].'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; + $list = ''; + foreach ($graphs as $graph) { + $list .= ('' != $list ? ',' : '').$graph['local_graph_id']; + } + + $row .= ""; + } else { + $row .= ""; + } + } + + $row .= $rescan; + + return $row; +} + +function mactrack_format_interface_row($stat) +{ + global $config; + + // we will make a row string + $row = ''; + + // calculate a human readable uptime + if (0 == $stat['ifLastChange']) { + $upTime = __('Since Restart', 'mactrack'); + } else { + if ($stat['ifLastChange'] > $stat['sysUptime']) { + $upTime = __('Since Restart', 'mactrack'); + } else { + $time = $stat['sysUptime'] - $stat['ifLastChange']; + $days = intval($time / (60 * 60 * 24 * 100)); + $remainder = $time % (60 * 60 * 24 * 100); + $hours = intval($remainder / (60 * 60 * 100)); + $remainder = $remainder % (60 * 60 * 100); + $minutes = intval($remainder / (60 * 100)); + $upTime = $days.'d:'.$hours.'h:'.$minutes.'m'; + } + } + + ob_start(); + + form_selectable_cell(mactrack_interface_actions($stat['device_id'], $stat['ifIndex']), $stat['device_id']); + form_selectable_cell($stat['device_name'], $stat['device_id']); + form_selectable_cell(strtoupper($stat['device_type']), $stat['device_id']); + form_selectable_cell($stat['ifName'], $stat['device_id']); + form_selectable_cell($stat['ifDescr'], $stat['device_id']); + form_selectable_cell($stat['ifAlias'], $stat['device_id']); + form_selectable_cell(round($stat['inBound'], 1).' %', $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['outBound'], 1).' %', $stat['device_id'], '', 'right'); + form_selectable_cell(mactrack_display_Octets($stat['int_ifHCInOctets']), $stat['device_id'], '', 'right'); + form_selectable_cell(mactrack_display_Octets($stat['int_ifHCOutOctets']), $stat['device_id'], '', 'right'); + + if ('true' == get_request_var('totals') || 'on' == get_request_var('totals')) { + form_selectable_cell($stat['ifInErrors'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifInDiscards'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifInUnknownProtos'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifOutErrors'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifOutDiscards'], $stat['device_id'], '', 'right'); + } else { + form_selectable_cell(round($stat['int_ifInErrors'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifInDiscards'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifInUnknownProtos'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifOutErrors'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifOutDiscards'], 1), $stat['device_id'], '', 'right'); + } + + form_selectable_cell(1 == $stat['ifOperStatus'] ? __('Up', 'mactrack') : __('Down', 'mactrack'), $stat['device_id'], '', 'right'); + form_selectable_cell($upTime, $stat['device_id'], '', 'right'); + form_selectable_cell(mactrack_date($stat['last_rundate']), $stat['device_id'], '', 'right'); + + return ob_get_clean(); +} + +function mactrack_format_dot1x_row($port_result) +{ + global $config,$mactrack_device_status; + + // we will make a row string + $row = ''; + + if (3 != get_request_var('scan_date')) { + $scan_date = $port_result['scan_date']; + } else { + $scan_date = $port_result['max_scan_date']; + } + + $status = 'Unknown'; + if (array_key_exists($port_result['status'], $mactrack_device_status)) { + $status = $mactrack_device_status[$port_result['status']]; + } + + $row .= "".mactrack_interface_actions($port_result['device_id'], $port_result['port_number']).''; + $row .= ''.$port_result['device_name'].''; + $row .= ''.$port_result['hostname'].''; + $row .= ''.$port_result['username'].''; + $row .= ''.$port_result['ip_address'].''; - if (cacti_sizeof($graphs)) { - $url = $config['url_path'] . 'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; - $list = ''; - foreach($graphs as $graph) { - $list .= ($list != '' ? ',': '') . $graph['local_graph_id']; - } + if ('' != read_config_option('mt_reverse_dns')) { + $row .= ''.$port_result['dns_hostname'].''; + } + + $row .= ''.mactrack_format_mac($port_result['mac_address']).''; + $row .= ''.$port_result['ifName'].''; + $row .= ''.(2 == $port_result['domain'] ? __('Data', 'mactrack') : __('Voice', 'mactrack')).''; + $row .= ''.$status.''; + $row .= "".$scan_date.''; + + return $row; +} + +function mactrack_display_Octets($octets) +{ + $suffix = ''; + while ($octets > 1024) { + $octets = $octets / 1024; + + switch ($suffix) { + case '': + $suffix = 'k'; + + break; + + case 'k': + $suffix = 'm'; + + break; + + case 'M': + $suffix = 'G'; + + break; + + case 'G': + $suffix = 'P'; - $row .= ""; - } else { - $row .= ""; - } - } - - $row .= $rescan; - - return $row; -} - -function mactrack_format_interface_row($stat) { - global $config; - - /* we will make a row string */ - $row = ''; - - /* calculate a human readable uptime */ - if ($stat['ifLastChange'] == 0) { - $upTime = __('Since Restart', 'mactrack'); - } else { - if ($stat['ifLastChange'] > $stat['sysUptime']) { - $upTime = __('Since Restart', 'mactrack'); - } else { - $time = $stat['sysUptime'] - $stat['ifLastChange']; - $days = intval($time / (60*60*24*100)); - $remainder = $time % (60*60*24*100); - $hours = intval($remainder / (60*60*100)); - $remainder = $remainder % (60*60*100); - $minutes = intval($remainder / (60*100)); - $upTime = $days . 'd:' . $hours . 'h:' . $minutes . 'm'; - } - } - - ob_start(); - - form_selectable_cell(mactrack_interface_actions($stat['device_id'], $stat['ifIndex']), $stat['device_id']); - form_selectable_cell($stat['device_name'], $stat['device_id']); - form_selectable_cell(strtoupper($stat['device_type']), $stat['device_id']); - form_selectable_cell($stat['ifName'], $stat['device_id']); - form_selectable_cell($stat['ifDescr'], $stat['device_id']); - form_selectable_cell($stat['ifAlias'], $stat['device_id']); - form_selectable_cell(round($stat['inBound'],1) . ' %', $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['outBound'],1) . ' %', $stat['device_id'], '', 'right'); - form_selectable_cell(mactrack_display_Octets($stat['int_ifHCInOctets']), $stat['device_id'], '', 'right'); - form_selectable_cell(mactrack_display_Octets($stat['int_ifHCOutOctets']), $stat['device_id'], '', 'right'); - - if (get_request_var('totals') == 'true' || get_request_var('totals') == 'on') { - form_selectable_cell($stat['ifInErrors'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifInDiscards'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifInUnknownProtos'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifOutErrors'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifOutDiscards'], $stat['device_id'], '', 'right'); - } else { - form_selectable_cell(round($stat['int_ifInErrors'],1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifInDiscards'],1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifInUnknownProtos'],1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifOutErrors'],1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifOutDiscards'],1), $stat['device_id'], '', 'right'); - } - - form_selectable_cell($stat['ifOperStatus'] == 1 ? __('Up', 'mactrack'):__('Down', 'mactrack'), $stat['device_id'], '', 'right'); - form_selectable_cell($upTime, $stat['device_id'], '', 'right'); - form_selectable_cell(mactrack_date($stat['last_rundate']), $stat['device_id'], '', 'right'); - - return ob_get_clean(); -} - -function mactrack_format_dot1x_row($port_result) { - global $config,$mactrack_device_status; - - /* we will make a row string */ - $row = ''; - - if (get_request_var('scan_date') != 3) { - $scan_date = $port_result['scan_date']; - } else { - $scan_date = $port_result['max_scan_date']; - } - - $status = 'Unknown'; - if (array_key_exists($port_result['status'],$mactrack_device_status)) { - $status = $mactrack_device_status[$port_result['status']]; - } - - $row .= "" . mactrack_interface_actions($port_result['device_id'], $port_result['port_number']) . ''; - $row .= '' . $port_result['device_name'] . ''; - $row .= '' . $port_result['hostname'] . ''; - $row .= '' . $port_result['username'] . ''; - $row .= '' . $port_result['ip_address'] . ''; - - if (read_config_option('mt_reverse_dns') != '') { - $row .= '' . $port_result['dns_hostname'] . ''; - } - - $row .= '' . mactrack_format_mac($port_result['mac_address']) . ''; - $row .= '' . $port_result['ifName'] . ''; - $row .= '' . ($port_result['domain'] == 2 ? __('Data', 'mactrack'):__('Voice', 'mactrack')) . ''; - $row .= '' . $status . ''; - $row .= "" . $scan_date . ''; - - return $row; -} - -function mactrack_display_Octets($octets) { - $suffix = ''; - while ($octets > 1024) { - $octets = $octets / 1024; - switch($suffix) { - case '': - $suffix = 'k'; - break; - case 'k': - $suffix = 'm'; - break; - case 'M': - $suffix = 'G'; - break; - case 'G': - $suffix = 'P'; - break 2; - default: - $suffix = ''; - break 2; - } - } - - $octets = round($octets,4); - $octets = substr($octets,0,5); - - return $octets . ' ' . $suffix; -} - -function mactrack_rescan($web = false) { - global $config; - - $device_id = get_request_var('device_id'); - $ifIndex = get_request_var('ifIndex'); - - $dbinfo = db_fetch_row_prepared('SELECT * + break 2; + + default: + $suffix = ''; + + break 2; + } + } + + $octets = round($octets, 4); + $octets = substr($octets, 0, 5); + + return $octets.' '.$suffix; +} + +function mactrack_rescan($web = false) +{ + global $config; + + $device_id = get_request_var('device_id'); + $ifIndex = get_request_var('ifIndex'); + + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mac_track_devices WHERE device_id = ?', - array($device_id)); + [$device_id] + ); - $data = array(); + $data = []; - if (cacti_sizeof($dbinfo)) { - if ($dbinfo['disabled'] == '') { - /* log the transaction to the database */ - mactrack_log_action(__('Device Rescan \'%s\'', $dbinfo['hostname'], 'mactrack')); + if (cacti_sizeof($dbinfo)) { + if ('' == $dbinfo['disabled']) { + // log the transaction to the database + mactrack_log_action(__('Device Rescan \'%s\'', $dbinfo['hostname'], 'mactrack')); - /* create the command script */ - $command_string = $config['base_path'] . '/plugins/mactrack/mactrack_scanner.php'; - $extra_args = ' -id=' . $dbinfo['device_id'] . ($web ? ' --web':''); + // create the command script + $command_string = $config['base_path'].'/plugins/mactrack/mactrack_scanner.php'; + $extra_args = ' -id='.$dbinfo['device_id'].($web ? ' --web' : ''); - /* print out the type, and device_id */ - $data['device_id'] = get_request_var('device_id'); - $data['ifIndex'] = $ifIndex; + // print out the type, and device_id + $data['device_id'] = get_request_var('device_id'); + $data['ifIndex'] = $ifIndex; - /* add the cacti header */ - ob_start(); + // add the cacti header + ob_start(); - /* execute the command, and show the results */ - $command = read_config_option('path_php_binary') . ' -q ' . $command_string . $extra_args; - passthru($command); + // execute the command, and show the results + $command = read_config_option('path_php_binary').' -q '.$command_string.$extra_args; + passthru($command); - $data['content'] = ob_get_clean(); - } - } + $data['content'] = ob_get_clean(); + } + } - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - print json_encode($data); + echo json_encode($data); } -function mactrack_site_scan($web = false) { - global $config, $web; +function mactrack_site_scan($web = false) +{ + global $config, $web; - $site_id = get_request_var('site_id'); + $site_id = get_request_var('site_id'); - $dbinfo = db_fetch_row_prepared('SELECT * + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mac_track_sites WHERE site_id = ?', - array($site_id)); + [$site_id] + ); - $data = array(); + $data = []; - if (cacti_sizeof($dbinfo)) { - /* log the transaction to the database */ - mactrack_log_action(__('Site scan \'%s\'', $dbinfo['site_name'], 'mactrack')); + if (cacti_sizeof($dbinfo)) { + // log the transaction to the database + mactrack_log_action(__('Site scan \'%s\'', $dbinfo['site_name'], 'mactrack')); - /* create the command script */ - $command_string = $config['base_path'] . '/plugins/mactrack/poller_mactrack.php'; - $extra_args = ' --web -sid=' . $dbinfo['site_id']; + // create the command script + $command_string = $config['base_path'].'/plugins/mactrack/poller_mactrack.php'; + $extra_args = ' --web -sid='.$dbinfo['site_id']; - /* print out the type, and device_id */ - $data['site_id'] = $site_id; + // print out the type, and device_id + $data['site_id'] = $site_id; - /* add the cacti header */ - ob_start(); + // add the cacti header + ob_start(); - /* execute the command, and show the results */ - $command = read_config_option('path_php_binary') . ' -q ' . $command_string . $extra_args; - passthru($command); + // execute the command, and show the results + $command = read_config_option('path_php_binary').' -q '.$command_string.$extra_args; + passthru($command); - $data['content'] = ob_get_clean(); - } + $data['content'] = ob_get_clean(); + } - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - print json_encode($data); + echo json_encode($data); } -function mactrack_enable() { - /* ================= input validation ================= */ - get_filter_request_var('device_id'); - /* ==================================================== */ +function mactrack_enable() +{ + // ================= input validation ================= + get_filter_request_var('device_id'); + // ==================================================== - $dbinfo = db_fetch_row_prepared('SELECT * + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mac_track_devices WHERE device_id = ?', - array(get_request_var('device_id'))); + [get_request_var('device_id')] + ); - $data = array(); + $data = []; - /* log the transaction to the database */ - mactrack_log_action(__('Device Enable \'%s\'', $dbinfo['hostname'], 'mactrack')); + // log the transaction to the database + mactrack_log_action(__('Device Enable \'%s\'', $dbinfo['hostname'], 'mactrack')); - db_execute_prepared('UPDATE mac_track_devices + db_execute_prepared( + 'UPDATE mac_track_devices SET disabled = "" WHERE device_id = ?', - array(get_request_var('device_id'))); + [get_request_var('device_id')] + ); - /* get the new html */ - $html = mactrack_format_device_row($dbinfo); + // get the new html + $html = mactrack_format_device_row($dbinfo); - /* send the response back to the browser */ - $data['device_id'] = get_request_var('device_id'); - $data['content'] = $html; + // send the response back to the browser + $data['device_id'] = get_request_var('device_id'); + $data['content'] = $html; - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - print json_encode($data); + echo json_encode($data); } -function mactrack_disable() { - /* ================= input validation ================= */ - get_filter_request_var('device_id'); - /* ==================================================== */ +function mactrack_disable() +{ + // ================= input validation ================= + get_filter_request_var('device_id'); + // ==================================================== - $dbinfo = db_fetch_row_prepared('SELECT * + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mactrack_devices WHERE device_id = ?', - array(get_request_var('device_id'))); + [get_request_var('device_id')] + ); - $data = array(); + $data = []; - /* log the transaction to the database */ - mactrack_log_action(__('Device Disable \'%d\'', $dbinfo['hostname'], 'mactrack')); + // log the transaction to the database + mactrack_log_action(__('Device Disable \'%d\'', $dbinfo['hostname'], 'mactrack')); - db_execute_prepared('UPDATE mactack_devices + db_execute_prepared( + 'UPDATE mactack_devices SET disabled="on" WHERE device_id = ?', - array(get_request_var('device_id'))); + [get_request_var('device_id')] + ); - /* get the new html */ - $html = mactrack_format_device_row($stat); + // get the new html + $html = mactrack_format_device_row($stat); - /* send the response back to the browser */ - $data['device_id'] = get_request_var('device_id'); - $data['content'] = $html; + // send the response back to the browser + $data['device_id'] = get_request_var('device_id'); + $data['content'] = $html; - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - print json_encode($data); + echo json_encode($data); } -function mactrack_log_action($message) { - $user = db_fetch_row_prepared('SELECT username, full_name +function mactrack_log_action($message) +{ + $user = db_fetch_row_prepared( + 'SELECT username, full_name FROM user_auth WHERE id = ?', - array($_SESSION['sess_user_id'])); - - cacti_log('MACTRACK: ' . $message . ", by '" . $user['full_name'] . '(' . $user['username'] . ")'", false, 'SYSTEM'); -} - -function mactrack_date($date) { - $year = date('Y'); - return (substr_count($date, $year) ? substr($date,5) : $date); -} - -function mactrack_int_row_class($stat) { - if ($stat['int_errors_present'] == '1') { - return 'int_errors'; - } elseif ($stat['int_discards_present'] == '1') { - return 'int_discards'; - } elseif ($stat['ifOperStatus'] == '1' && $stat['ifAlias'] == '') { - return 'int_up_wo_alias'; - } elseif ($stat['ifOperStatus'] == '0') { - return 'int_down'; - } else { - return 'int_up'; - } -} - -function mactrack_dot1x_row_class($port_result) { - if ($port_result['status'] == '7') { - return 'dot1x_authn_failed'; - } elseif ($port_result['status'] == '5') { - return 'dot1x_auth_failed'; - } elseif ($port_result['status'] == '3') { - return 'dot1x_auth_no_method'; - } elseif ($port_result['status'] == '2') { - return 'dot1x_running'; - } elseif ($port_result['status'] == '1') { - return 'dot1x_idle'; - } elseif ($port_result['status'] == '4') { - return 'dot1x_auth_success'; - } else { - return 'dot1x_authn_success'; - } + [$_SESSION['sess_user_id']] + ); + + cacti_log('MACTRACK: '.$message.", by '".$user['full_name'].'('.$user['username'].")'", false, 'SYSTEM'); +} + +function mactrack_date($date) +{ + $year = date('Y'); + + return substr_count($date, $year) ? substr($date, 5) : $date; +} + +function mactrack_int_row_class($stat) +{ + if ('1' == $stat['int_errors_present']) { + return 'int_errors'; + } + if ('1' == $stat['int_discards_present']) { + return 'int_discards'; + } + if ('1' == $stat['ifOperStatus'] && '' == $stat['ifAlias']) { + return 'int_up_wo_alias'; + } + if ('0' == $stat['ifOperStatus']) { + return 'int_down'; + } + + return 'int_up'; +} + +function mactrack_dot1x_row_class($port_result) +{ + if ('7' == $port_result['status']) { + return 'dot1x_authn_failed'; + } + if ('5' == $port_result['status']) { + return 'dot1x_auth_failed'; + } + if ('3' == $port_result['status']) { + return 'dot1x_auth_no_method'; + } + if ('2' == $port_result['status']) { + return 'dot1x_running'; + } + if ('1' == $port_result['status']) { + return 'dot1x_idle'; + } + if ('4' == $port_result['status']) { + return 'dot1x_auth_success'; + } + + return 'dot1x_authn_success'; } /* mactrack_create_sql_filter - this routine will take a filter string and process it into a @@ -3148,334 +3561,360 @@ function mactrack_dot1x_row_class($port_result) { @arg $fields - (array) A list of field names to include in the where clause. They can also contain the table name in cases where joins are important. @returns - (string) The formatted SQL syntax */ -function mactrack_create_sql_filter($filter, $fields) { - $query = ''; - - /* field names are required */ - if (!cacti_sizeof($fields)) return; - - /* the filter must be non-blank */ - if ($filter == '') { - return; - } - - $elements = explode(' ', $filter); - - foreach($elements as $element) { - if (substr($element, 0, 1) == '-') { - $filter = substr($element, 1); - $type = 'NOT'; - $operator = 'AND'; - } else { - $filter = $element; - $type = ''; - $operator = 'OR'; - } - - $field_no = 1; - foreach ($fields as $field) { - if ($field_no == 1 && $query != '') { - $query .= ') AND ('; - } elseif ($field_no == 1) { - $query .= '('; - } - - $query .= ($field_no == 1 ? '':" $operator ") . "($field $type LIKE '%" . $filter . "%')"; - - $field_no++; - } - } - - return $query . ')'; -} - -function mactrack_display_hours($value) { - if ($value == '' || $value == 'disabled') { - return __('N/A', 'mactrack'); - } elseif ($value < 60) { - return __('%d Minutes', round($value,0), 'mactrack'); - } else { - $value = $value / 60; - if ($value < 24) { - return __('%d Hours', round($value,0), 'mactrack'); - } else { - $value = $value / 24; - if ($value < 7) { - return __('%d Days', round($value,0), 'mactrack'); - } else { - $value = $value / 7; - return __('%d Weeks', round($value,0), 'mactrack'); - } - } - } +function mactrack_create_sql_filter($filter, $fields) +{ + $query = ''; + + // field names are required + if (!cacti_sizeof($fields)) { + return; + } + + // the filter must be non-blank + if ('' == $filter) { + return; + } + + $elements = explode(' ', $filter); + + foreach ($elements as $element) { + if ('-' == substr($element, 0, 1)) { + $filter = substr($element, 1); + $type = 'NOT'; + $operator = 'AND'; + } else { + $filter = $element; + $type = ''; + $operator = 'OR'; + } + + $field_no = 1; + foreach ($fields as $field) { + if (1 == $field_no && '' != $query) { + $query .= ') AND ('; + } elseif (1 == $field_no) { + $query .= '('; + } + + $query .= (1 == $field_no ? '' : " {$operator} ")."({$field} {$type} LIKE '%".$filter."%')"; + + ++$field_no; + } + } + + return $query.')'; +} + +function mactrack_display_hours($value) +{ + if ('' == $value || 'disabled' == $value) { + return __('N/A', 'mactrack'); + } + if ($value < 60) { + return __('%d Minutes', round($value, 0), 'mactrack'); + } + $value = $value / 60; + if ($value < 24) { + return __('%d Hours', round($value, 0), 'mactrack'); + } + $value = $value / 24; + if ($value < 7) { + return __('%d Days', round($value, 0), 'mactrack'); + } + $value = $value / 7; + + return __('%d Weeks', round($value, 0), 'mactrack'); +} + +function mactrack_display_stats() +{ + // check if scanning is running + $processes = db_fetch_cell('SELECT COUNT(*) FROM mac_track_processes'); + $timing = read_config_option('mt_collection_timing', true); + $frequency = 0; + + if ('disabled' != $timing) { + $frequency = $timing * 60; + } + + $mactrack_stats = read_config_option('stats_mactrack', true); + + $time = __('Not Recorded', 'mactrack'); + $proc = __('N/A', 'mactrack'); + $devs = __('N/A', 'mactrack'); + if ('' != $mactrack_stats) { + $stats = explode(' ', $mactrack_stats); + + if (cacti_sizeof(3 == $stats)) { + $time = explode(':', $stats[0]); + $time = $time[1]; + $time = round($time, 1); + + $proc = explode(':', $stats[1]); + $proc = $proc[1]; + + $devs = explode(':', $stats[2]); + $devs = $devs[1]; + } + } + + if ($processes > 0) { + $message = __('Status: Running, Processes: %d, Progress: %s, LastRuntime: %2.1f', $processes, read_config_option('mactrack_process_status', true), $time, 'mactrack'); + } else { + $message = __( + 'Status: Idle, LastRuntime: %2.1f seconds, Processes: %d processes, Devices: %d, Next Run Time: %s', + $time, + $proc, + $devs, + 'disabled' != $timing ? date('Y-m-d H:i:s', strtotime(read_config_option('mt_scan_date', true)) + $frequency) : __('Disabled', 'mactrack'), + 'mactrack' + ); + } + + html_start_box('', '100%', '', '3', 'center', ''); + + echo ''; + echo ''.__('Scanning Rate: Every %s', mactrack_display_hours(read_config_option('mt_collection_timing')), 'mactrack').', '.$message.''; + echo ''; + + html_end_box(); +} + +function mactrack_legend_row($class, $text) +{ + echo "{$text}"; +} + +function mactrack_format_device_row($device, $actions = false) +{ + global $config, $mactrack_device_types; + + // viewer level + if ($actions) { + $row = ""; + + // admin level + if (api_user_realm_auth('mactrack_sites.php')) { + if ('' == $device['disabled']) { + $row .= ""; + } else { + $row .= ""; + } + } + + echo "".$row.''; + } + + form_selectable_cell(filter_value($device['device_name'], get_request_var('filter'), 'mactrack_devices.php?action=edit&device_id='.$device['device_id']), $device['device_id']); + form_selectable_cell($device['site_name'], $device['device_id']); + form_selectable_cell(get_colored_device_status('on' == $device['disabled'] ? true : false, $device['snmp_status']), $device['device_id']); + form_selectable_cell(filter_value($device['hostname'], get_request_var('filter')), $device['device_id']); + form_selectable_cell('' == $device['device_type'] ? __('Not Detected', 'mactrack') : $device['device_type'], $device['device_id']); + form_selectable_cell('1' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ips_total'], -1), $device['device_id'], '', 'right'); + form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ports_total'], -1), $device['device_id'], '', 'right'); + form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ports_active'], -1), $device['device_id'], '', 'right'); + form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ports_trunk'], -1), $device['device_id'], '', 'right'); + form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['macs_active'], -1), $device['device_id'], '', 'right'); + form_selectable_cell(number_format($device['last_runduration'], 1), $device['device_id'], '', 'right'); + form_checkbox_cell($device['device_name'], $device['device_id']); + form_end_row(); +} + +function mactrack_mail($to, $fromemail, $fromname, $subject, $message, $headers = '') +{ + global $config; + + $v = plugin_mactrack_version(); + $headers = [ + 'X-Mailer' => 'Cacti-MacTrack-v'.$v['version'], + 'User-Agent' => 'Cacti-MacTrack-v'.$v['version'], + ]; + + $from[0]['email'] = $fromemail; + $from[0]['name'] = $fromname; + + if (false !== strpos($to, ';')) { + $to = explode(';', $to); + } + + mailer($from, $to, '', '', '', $subject, $message, '', '', $headers); +} + +function mactrack_sanitize_load_report() +{ + if (!isset_request_var('report')) { + if (isset($_SESSION['sess_mt_tab']) && '' != $_SESSION['sess_mt_tab']) { + set_request_var('report', $_SESSION['sess_mt_tab']); + } else { + set_request_var('report', read_user_setting('default_mactrack_tab')); + } + + if ('' == get_request_var('report')) { + set_request_var('report', 'sites'); + } + } else { + set_request_var('report', sanitize_search_string(get_nfilter_request_var('report'))); + } + + $_SESSION['sess_mt_tab'] = get_request_var('report'); } -function mactrack_display_stats() { - /* check if scanning is running */ - $processes = db_fetch_cell('SELECT COUNT(*) FROM mac_track_processes'); - $timing = read_config_option('mt_collection_timing', true); - $frequency = 0; - - if ($timing != 'disabled') { - $frequency = $timing * 60; - } - - $mactrack_stats = read_config_option('stats_mactrack', true); +function mactrack_tabs() +{ + global $config; + + // present a tabbed interface + $tabs_mactrack = [ + 'sites' => __('Sites', 'mactrack'), + 'devices' => __('Devices', 'mactrack'), + 'ips' => __('IP Ranges', 'mactrack'), + 'arp' => __('IP Address', 'mactrack'), + 'macs' => __('MAC Address', 'mactrack'), + 'interfaces' => __('Interfaces', 'mactrack'), + 'dot1x' => __('Dot1x', 'mactrack'), + 'graphs' => __('Graphs', 'mactrack'), + ]; - $time = __('Not Recorded', 'mactrack'); - $proc = __('N/A', 'mactrack'); - $devs = __('N/A', 'mactrack'); - if ($mactrack_stats != '') { - $stats = explode(' ', $mactrack_stats); + mactrack_sanitize_load_report(); - if (cacti_sizeof($stats == 3)) { - $time = explode(':', $stats[0]); - $time = $time[1]; - $time = round($time, 1); + // set the default tab + $current_tab = get_nfilter_request_var('report'); - $proc = explode(':', $stats[1]); - $proc = $proc[1]; + // draw the tabs + echo "
'; +} - if ($processes > 0) { - $message = __('Status: Running, Processes: %d, Progress: %s, LastRuntime: %2.1f', $processes, read_config_option('mactrack_process_status', true), $time, 'mactrack'); - } else { - $message = __('Status: Idle, LastRuntime: %2.1f seconds, Processes: %d processes, Devices: %d, Next Run Time: %s', - $time, $proc , $devs, - ($timing != 'disabled' ? date('Y-m-d H:i:s', strtotime(read_config_option('mt_scan_date', true)) + $frequency):__('Disabled', 'mactrack')), 'mactrack'); - } +function mactrack_get_vendor_name($mac) +{ + $vendor_mac = substr($mac, 0, 8); - html_start_box('', '100%', '', '3', 'center', ''); + $vendor_name = db_fetch_cell_prepared('SELECT vendor_name FROM mac_track_oui_database WHERE vendor_mac = ?', [$vendor_mac]); - print ''; - print '' . __('Scanning Rate: Every %s', mactrack_display_hours(read_config_option('mt_collection_timing')), 'mactrack') . ', ' . $message . ''; - print ''; + if ('' != $vendor_name) { + return $vendor_name; + } - html_end_box(); + return __('Unknown', 'mactrack'); } -function mactrack_legend_row($class, $text) { - print "$text"; -} - -function mactrack_format_device_row($device, $actions=false) { - global $config, $mactrack_device_types; - - /* viewer level */ - if ($actions) { - $row = ""; - - /* admin level */ - if (api_user_realm_auth('mactrack_sites.php')) { - if ($device['disabled'] == '') { - $row .= ""; - } else { - $row .= ""; - } - } - - print "" . $row . ""; - } - - form_selectable_cell(filter_value($device['device_name'], get_request_var('filter'), "mactrack_devices.php?action=edit&device_id=" . $device['device_id']), $device['device_id']); - form_selectable_cell($device['site_name'], $device['device_id']); - form_selectable_cell(get_colored_device_status(($device['disabled'] == 'on' ? true : false), $device['snmp_status']), $device['device_id']); - form_selectable_cell(filter_value($device['hostname'], get_request_var('filter')), $device['device_id']); - form_selectable_cell(($device['device_type'] == '' ? __('Not Detected', 'mactrack') : $device['device_type']), $device['device_id']); - form_selectable_cell(($device['scan_type'] == '1' ? __('N/A', 'mactrack') : number_format_i18n($device['ips_total'], -1)), $device['device_id'], '', 'right'); - form_selectable_cell(($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['ports_total'], -1)), $device['device_id'], '', 'right'); - form_selectable_cell(($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['ports_active'], -1)), $device['device_id'], '', 'right'); - form_selectable_cell(($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['ports_trunk'], -1)), $device['device_id'], '', 'right'); - form_selectable_cell(($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['macs_active'], -1)), $device['device_id'], '', 'right'); - form_selectable_cell(number_format($device['last_runduration'], 1), $device['device_id'], '', 'right'); - form_checkbox_cell($device['device_name'], $device['device_id']); - form_end_row(); - -} - -function mactrack_mail($to, $fromemail, $fromname, $subject, $message, $headers = '') { - global $config; - - $v = plugin_mactrack_version(); - $headers = array( - 'X-Mailer' => 'Cacti-MacTrack-v' . $v['version'], - 'User-Agent' => 'Cacti-MacTrack-v' . $v['version'] - ); - - $from[0]['email'] = $fromemail; - $from[0]['name'] = $fromname; - - if (strpos($to, ';') !== false) { - $to = explode(';', $to); - } +function mactrack_site_filter($page = 'mactrack_sites.php') +{ + global $item_rows; - mailer($from, $to, '', '', '', $subject, $message, '', '', $headers); -} - -function mactrack_sanitize_load_report() { - if (!isset_request_var('report')) { - if (isset($_SESSION['sess_mt_tab']) && $_SESSION['sess_mt_tab'] != '') { - set_request_var('report', $_SESSION['sess_mt_tab']); - } else { - set_request_var('report', read_user_setting('default_mactrack_tab')); - } - - if (get_request_var('report') == '') { - set_request_var('report', 'sites'); - } - } else { - set_request_var('report', sanitize_search_string(get_nfilter_request_var('report'))); - } - - $_SESSION['sess_mt_tab'] = get_request_var('report'); -} - -function mactrack_tabs() { - global $config; - - /* present a tabbed interface */ - $tabs_mactrack = array( - 'sites' => __('Sites', 'mactrack'), - 'devices' => __('Devices', 'mactrack'), - 'ips' => __('IP Ranges', 'mactrack'), - 'arp' => __('IP Address', 'mactrack'), - 'macs' => __('MAC Address', 'mactrack'), - 'interfaces' => __('Interfaces', 'mactrack'), - 'dot1x' => __('Dot1x', 'mactrack'), - 'graphs' => __('Graphs', 'mactrack') - ); - - mactrack_sanitize_load_report(); - - /* set the default tab */ - $current_tab = get_nfilter_request_var('report'); - - /* draw the tabs */ - print "
"; -} - -function mactrack_get_vendor_name($mac) { - $vendor_mac = substr($mac,0,8); - - $vendor_name = db_fetch_cell_prepared('SELECT vendor_name FROM mac_track_oui_database WHERE vendor_mac = ?', array($vendor_mac)); - - if ($vendor_name != '') { - return $vendor_name; - } else { - return __('Unknown', 'mactrack'); - } -} - -function mactrack_site_filter($page = 'mactrack_sites.php') { - global $item_rows; - - ?> + ?>
+ if (!('false' == get_request_var('detail'))) { ?>
- + - '> + '> - + - onClick='applyFilter()'> + onClick='applyFilter()'> - + - - - + + +
- + - +
+ if ('false' == get_request_var('detail')) { ?> @@ -3483,7 +3922,7 @@ function mactrack_site_filter($page = 'mactrack_sites.php') { " . __('You must select at least one SNMP Option.', 'mactrack') . "\n"; - $save_html = ""; - } else { - $save_html = ""; + if (!isset($mactrack_array)) { + echo "".__('You must select at least one SNMP Option.', 'mactrack')."\n"; + $save_html = ''; + } else { + $save_html = "'; - if (get_nfilter_request_var("drp_action") == '1') { /* delete */ - print " + if ('1' == get_nfilter_request_var('drp_action')) { // delete + echo " -

" . __('Click \'Continue\' to delete the following SNMP Option(s).', 'mactrack') . "

-
    $snmp_groups
+

".__('Click \'Continue\' to delete the following SNMP Option(s).', 'mactrack')."

+
    {$snmp_groups}
"; - } elseif (get_nfilter_request_var("drp_action") == '2') { /* duplicate */ - print " + } elseif ('2' == get_nfilter_request_var('drp_action')) { // duplicate + echo " -

" . __('Click \'Continue\' to duplicate the following SNMP Option(s). You can optionally change the title format for the new SNMP Options.', 'mactrack') . "

-
    $snmp_groups
-

" . __('Name Format:', 'mactrack') . '
'; form_text_box('name_format', __(' (1)', 'mactrack'), '', '255', '30', 'text'); print "

+

".__('Click \'Continue\' to duplicate the following SNMP Option(s). You can optionally change the title format for the new SNMP Options.', 'mactrack')."

+
    {$snmp_groups}
+

".__('Name Format:', 'mactrack').'
'; + form_text_box('name_format', __(' (1)', 'mactrack'), '', '255', '30', 'text'); + echo '

- "; - } - } + '; + } + } - print " + echo " - - - - $save_html + + + + {$save_html} "; - html_end_box(); + html_end_box(); - bottom_footer(); + bottom_footer(); } /* -------------------------- mactrack Item Functions -------------------------- */ -function mactrack_snmp_item_movedown() { - /* ================= input validation ================= */ - get_filter_request_var('item_id'); - get_filter_request_var('id'); - /* ==================================================== */ - - move_item_down('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id=' . get_request_var('id')); +function mactrack_snmp_item_movedown() +{ + // ================= input validation ================= + get_filter_request_var('item_id'); + get_filter_request_var('id'); + // ==================================================== + + move_item_down('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id='.get_request_var('id')); } -function mactrack_snmp_item_moveup() { - /* ================= input validation ================= */ - get_filter_request_var('item_id'); - get_filter_request_var('id'); - /* ==================================================== */ +function mactrack_snmp_item_moveup() +{ + // ================= input validation ================= + get_filter_request_var('item_id'); + get_filter_request_var('id'); + // ==================================================== - move_item_up('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id=' . get_request_var('id')); + move_item_up('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id='.get_request_var('id')); } -function mactrack_snmp_item_remove() { - /* ================= input validation ================= */ - get_filter_request_var('item_id'); - /* ==================================================== */ +function mactrack_snmp_item_remove() +{ + // ================= input validation ================= + get_filter_request_var('item_id'); + // ==================================================== - db_execute_prepared('DELETE FROM mac_track_snmp_items + db_execute_prepared( + 'DELETE FROM mac_track_snmp_items WHERE id = ?', - array(get_request_var('item_id'))); + [get_request_var('item_id')] + ); } -function mactrack_snmp_item_edit() { - global $config; - global $fields_mactrack_snmp_item_edit; +function mactrack_snmp_item_edit() +{ + global $config; + global $fields_mactrack_snmp_item_edit; - /* ================= input validation ================= */ - get_filter_request_var('id'); - get_filter_request_var('item_id'); - /* ==================================================== */ + // ================= input validation ================= + get_filter_request_var('id'); + get_filter_request_var('item_id'); + // ==================================================== - # fetch the current mactrack snmp record - $snmp_option = db_fetch_row_prepared('SELECT * + // fetch the current mactrack snmp record + $snmp_option = db_fetch_row_prepared( + 'SELECT * FROM mac_track_snmp WHERE id = ?', - array(get_request_var('id'))); + [get_request_var('id')] + ); - # if an existing item was requested, fetch data for it - if (get_request_var('item_id', '') !== '') { - $mactrack_snmp_item = db_fetch_row_prepared('SELECT * + // if an existing item was requested, fetch data for it + if ('' !== get_request_var('item_id', '')) { + $mactrack_snmp_item = db_fetch_row_prepared( + 'SELECT * FROM mac_track_snmp_items WHERE id = ?', - array(get_request_var('item_id'))); - - $header_label = __('SNMP Options [edit %s]', $snmp_option['name'], 'mactrack'); - } else { - $header_label = __('SNMP Options [new]', 'mactrack'); + [get_request_var('item_id')] + ); - $mactrack_snmp_item = array(); - $mactrack_snmp_item['snmp_id'] = get_request_var('id'); - $mactrack_snmp_item['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id=' . get_request_var('id')); - } + $header_label = __('SNMP Options [edit %s]', $snmp_option['name'], 'mactrack'); + } else { + $header_label = __('SNMP Options [new]', 'mactrack'); - form_start(get_current_page(), 'mactrack_item_edit'); + $mactrack_snmp_item = []; + $mactrack_snmp_item['snmp_id'] = get_request_var('id'); + $mactrack_snmp_item['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id='.get_request_var('id')); + } + form_start(get_current_page(), 'mactrack_item_edit'); - html_start_box($header_label, '100%', '', '3', 'center', ''); + html_start_box($header_label, '100%', '', '3', 'center', ''); - draw_edit_form( - array( - 'config' => array('no_form_tag' => true), - 'fields' => inject_form_variables($fields_mactrack_snmp_item_edit, (isset($mactrack_snmp_item) ? $mactrack_snmp_item : array())) - ) - ); + draw_edit_form( + [ + 'config' => ['no_form_tag' => true], + 'fields' => inject_form_variables($fields_mactrack_snmp_item_edit, isset($mactrack_snmp_item) ? $mactrack_snmp_item : []), + ] + ); - html_end_box(); + html_end_box(); - form_hidden_box('item_id', (isset_request_var('item_id') ? get_request_var('item_id') : '0'), ''); - form_hidden_box('id', (isset($mactrack_snmp_item['snmp_id']) ? $mactrack_snmp_item['snmp_id'] : '0'), ''); - form_hidden_box('save_component_mactrack_snmp_item', '1', ''); + form_hidden_box('item_id', isset_request_var('item_id') ? get_request_var('item_id') : '0', ''); + form_hidden_box('id', isset($mactrack_snmp_item['snmp_id']) ? $mactrack_snmp_item['snmp_id'] : '0', ''); + form_hidden_box('save_component_mactrack_snmp_item', '1', ''); - form_save_button(htmlspecialchars('mactrack_snmp.php?action=edit&id=' . get_request_var('id'))); + form_save_button(htmlspecialchars('mactrack_snmp.php?action=edit&id='.get_request_var('id'))); - ?> + ?> $previous_base_start_time) { - unset($last_run_time); - } - } - - /* see if the user desires a new db maintenance time */ - /* - if (!empty($previous_db_maint_time)) { - if ($database_maint_time <> $previous_db_maint_time) { - unset($last_db_maint_time); - } - } - */ - - /* determine the next start time */ - $current_time = strtotime('now'); - if (empty($last_run_time)) { - $collection_never_completed = true; - if ($current_time > strtotime($base_start_time)) { - /* if timer expired within a polling interval, then poll */ - if (($current_time - 300) < strtotime($base_start_time)) { - $next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time); - } else { - $next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time) + 3600*24; - } - } else { - $next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time); - } - } else { - $collection_never_completed = false; - $next_run_time = $last_run_time + $seconds_offset; - } - - /* determine the next db maintenance time */ - /* - if (empty($last_db_maint_time)) { - if (strtotime($base_start_time) < $current_time) { - $next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time) + 3600*24; - } else { - $next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time); - } - } else { - $next_db_maint_time = $last_db_maint_time + 24*3600; - } - */ - - $db_maint_time = strtotime($database_maint_time); - if ($last_db_maint_time < $db_maint_time) { - $next_db_maint_time = $db_maint_time; - } else { - $next_db_maint_time = strtotime('Tomorrow '. $database_maint_time); - } - - $time_till_next_run = $next_run_time - $current_time; - $time_till_next_db_maint = $next_db_maint_time - $current_time; - } - - html_start_box(__('Mactrack Process Status', 'mactrack'), '100%', '', '1', 'center', ''); - ?> +function mactrack_display_run_status() +{ + global $config, $refresh_interval, $mactrack_poller_frequencies; + + $collection_timing = read_config_option('mt_collection_timing', true); + + if ('disabled' != $collection_timing) { + $seconds_offset = $collection_timing * 60; + // find out if it's time to collect device information + $base_start_time = read_config_option('mt_base_time', true); + $database_maint_time = read_config_option('mt_maint_time', true); + $last_run_time = read_config_option('mt_last_run_time', true); + $last_db_maint_time = read_config_option('mt_last_db_maint_time', true); + $previous_base_start_time = read_config_option('mt_prev_base_time', true); + $previous_db_maint_time = read_config_option('mt_prev_db_maint_time', true); + + // see if the user desires a new start time + if (!empty($previous_base_start_time)) { + if ($base_start_time != $previous_base_start_time) { + unset($last_run_time); + } + } + + // see if the user desires a new db maintenance time + /* + if (!empty($previous_db_maint_time)) { + if ($database_maint_time <> $previous_db_maint_time) { + unset($last_db_maint_time); + } + } + */ + + // determine the next start time + $current_time = strtotime('now'); + if (empty($last_run_time)) { + $collection_never_completed = true; + if ($current_time > strtotime($base_start_time)) { + // if timer expired within a polling interval, then poll + if (($current_time - 300) < strtotime($base_start_time)) { + $next_run_time = strtotime(date('Y-m-d').' '.$base_start_time); + } else { + $next_run_time = strtotime(date('Y-m-d').' '.$base_start_time) + 3600 * 24; + } + } else { + $next_run_time = strtotime(date('Y-m-d').' '.$base_start_time); + } + } else { + $collection_never_completed = false; + $next_run_time = $last_run_time + $seconds_offset; + } + + // determine the next db maintenance time + /* + if (empty($last_db_maint_time)) { + if (strtotime($base_start_time) < $current_time) { + $next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time) + 3600*24; + } else { + $next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time); + } + } else { + $next_db_maint_time = $last_db_maint_time + 24*3600; + } + */ + + $db_maint_time = strtotime($database_maint_time); + if ($last_db_maint_time < $db_maint_time) { + $next_db_maint_time = $db_maint_time; + } else { + $next_db_maint_time = strtotime('Tomorrow '.$database_maint_time); + } + + $time_till_next_run = $next_run_time - $current_time; + $time_till_next_db_maint = $next_db_maint_time - $current_time; + } + + html_start_box(__('Mactrack Process Status', 'mactrack'), '100%', '', '1', 'center', ''); + ?> \n"; - print "\n"; - if (file_exists($config['base_path'] . '/plugins/mactrack/themes/' . get_selected_theme() . '/mactrack.css')) { - print "\n"; - } else { - print "\n"; - } +function mactrack_page_head() +{ + global $config; + + echo "\n"; + echo "\n"; + if (file_exists($config['base_path'].'/plugins/mactrack/themes/'.get_selected_theme().'/mactrack.css')) { + echo "\n"; + } else { + echo "\n"; + } } -function mactrack_poller_bottom() { - global $config; +function mactrack_poller_bottom() +{ + global $config; - $command_string = read_config_option('path_php_binary'); - $extra_args = '-q ' . $config['base_path'] . '/plugins/mactrack/poller_mactrack.php'; - exec_background($command_string, $extra_args); + $command_string = read_config_option('path_php_binary'); + $extra_args = '-q '.$config['base_path'].'/plugins/mactrack/poller_mactrack.php'; + exec_background($command_string, $extra_args); } -function mactrack_config_settings() { - global $tabs, $settings, $settings_user, $tabs_graphs, $snmp_versions, $mactrack_poller_frequencies, - $mactrack_data_retention, $mactrack_macauth_frequencies, $mactrack_update_policies; - - $tabs['mactrack'] = __('Mactrack', 'mactrack'); - - $settings['mactrack'] = array( - 'mactrack_hdr_timing' => array( - 'friendly_name' => __('General Settings', 'mactrack'), - 'method' => 'spacer', - ), - 'mt_collection_timing' => array( - 'friendly_name' => __('Scanning Frequency', 'mactrack'), - 'description' => __('Choose when to collect MAC and IP Addresses and Interface statistics from your network devices.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'disabled', - 'array' => $mactrack_poller_frequencies, - ), - 'mt_processes' => array( - 'friendly_name' => __('Concurrent Processes', 'mactrack'), - 'description' => __('Specify how many devices will be polled simultaneously until all devices have been polled.', 'mactrack'), - 'default' => '7', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '4' - ), - 'mt_script_runtime' => array( - 'friendly_name' => __('Scanner Max Runtime', 'mactrack'), - 'description' => __('Specify the number of minutes a device scanning function will be allowed to run prior to the system assuming it has been completed. This setting will correct for abended scanning jobs.', 'mactrack'), - 'default' => '20', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '4' - ), - 'mt_base_time' => array( - 'friendly_name' => __('Start Time for Data Collection', 'mactrack'), - 'description' => __('When would you like the first data collection to take place. All future data collection times will be based upon this start time. A good example would be 12:00AM.', 'mactrack'), - 'default' => '1:00am', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '8' - ), - 'mt_maint_time' => array( - 'friendly_name' => __('Database Maintenance Time', 'mactrack'), - 'description' => __('When should old database records be removed from the database. Please note that no access will be permitted to the port database while this action is taking place.', 'mactrack'), - 'default' => '12:00am', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '8' - ), - 'mt_maint_confirm' => array( - 'friendly_name' => __('Confirm Utilities Prompt', 'mactrack'), - 'description' => __('When using utilities, prompt for verification', 'mactrack'), - 'default' => read_config_option('deletion_verification'), - 'method' => 'checkbox', - ), - 'mt_data_retention' => array( - 'friendly_name' => __('Data Retention', 'mactrack'), - 'description' => __('How long should port MAC details be retained in the database.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '14', - 'array' => $mactrack_data_retention, - ), - 'mt_data_retention_ip' => array( - 'friendly_name' => __('Data Retention IPs', 'mactrack'), - 'description' => __('How long should discovered IPs details be retained in the database.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '3', - 'array' => $mactrack_data_retention, - ), - 'mt_ignorePorts_delim' => array( - 'friendly_name' => __('Switch Level Ignore Ports Delimiter', 'mactrack'), - 'description' => __('What delimiter should Mactrack use when parsing the Ignore Ports string for each switch.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '-1', - 'array' => array( - '-1' => __('Auto Detect', 'mactrack'), - ':' => __('Colon [:]', 'mactrack'), - '|' => __('Pipe [|]', 'mactrack'), - ' ' => __('Space [ ]', 'mactrack') - ) - ), - 'mt_mac_format' => array( - 'friendly_name' => __('Mac Address Output Format', 'mactrack'), - 'description' => __('Format used for display.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'aa:bb:cc:dd:ee:ff', - 'array' => array( - 'aa:bb:cc:dd:ee:ff' => 'aa:bb:cc:dd:ee:ff', - 'aa-bb-cc-dd-ee-ff' => 'aa-bb-cc-dd-ee-ff', - 'aabb-ccdd-eeff' => 'aabb-ccdd-eeff', - 'aabbccddeeff' => 'aabbccddeeff', - 'aabb.ccdd.eeff' => 'aabb.ccdd.eeff' - ) - ), - 'mt_ignorePorts' => array( - 'method' => 'textbox', - 'friendly_name' => __('Ports to Ignore', 'mactrack'), - 'description' => __('Provide a regular expression of ifNames or ifDescriptions of ports to ignore in the interface list. For example, (Vlan|Loopback|Null).', 'mactrack'), - 'class' => 'textAreaNotes', - 'defaults' => '(Vlan|Loopback|Null)', - 'max_length' => '255', - 'size' => '80' - ), - 'mt_interface_high' => array( - 'friendly_name' => __('Bandwidth Usage Threshold', 'mactrack'), - 'description' => __('When reviewing network interface statistics, what bandwidth threshold do you want to view by default.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '70', - 'array' => array( - '-1' => __('N/A', 'mactrack'), - '10' => __('%d Percent', 10, 'mactrack'), - '20' => __('%d Percent', 20, 'mactrack'), - '30' => __('%d Percent', 30, 'mactrack'), - '40' => __('%d Percent', 40, 'mactrack'), - '50' => __('%d Percent', 50, 'mactrack'), - '60' => __('%d Percent', 60, 'mactrack'), - '70' => __('%d Percent', 70, 'mactrack'), - '80' => __('%d Percent', 80, 'mactrack'), - '90' => __('%d Percent', 90, 'mactrack') - ) - ), - 'mt_hdr_rdns' => array( - 'friendly_name' => __('DNS Settings', 'mactrack'), - 'method' => 'spacer', - ), - 'mt_reverse_dns' => array( - 'friendly_name' => __('Perform Reverse DNS Name Resolution', 'mactrack'), - 'description' => __('Should Mactrack perform reverse DNS lookup of the IP addresses associated with ports. CAUTION: If DNS is not properly setup, this will slow scan time significantly.', 'mactrack'), - 'default' => '', - 'method' => 'checkbox' - ), - 'mt_dns_primary' => array( - 'friendly_name' => __('Primary DNS IP Address', 'mactrack'), - 'description' => __('Enter the primary DNS IP Address to utilize for reverse lookups.', 'mactrack'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '18' - ), - 'mt_dns_secondary' => array( - 'friendly_name' => __('Secondary DNS IP Address', 'mactrack'), - 'description' => __('Enter the secondary DNS IP Address to utilize for reverse lookups.', 'mactrack'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '18' - ), - 'mt_dns_timeout' => array( - 'friendly_name' => __('DNS Timeout', 'mactrack'), - 'description' => __('Please enter the DNS timeout in milliseconds. Mactrack uses a PHP based DNS resolver.', 'mactrack'), - 'method' => 'textbox', - 'default' => '500', - 'max_length' => '10', - 'size' => '4' - ), - 'mt_dns_prime_interval' => array( - 'friendly_name' => __('DNS Prime Interval', 'mactrack'), - 'description' => __('How often, in seconds do Mactrack scanning IP\'s need to be resolved to MAC addresses for DNS resolution. Using a larger number when you have several thousand devices will increase performance.', 'mactrack'), - 'method' => 'textbox', - 'default' => '120', - 'max_length' => '10', - 'size' => '4' - ), - 'mactrack_hdr_notification' => array( - 'friendly_name' => __('Notification Settings', 'mactrack'), - 'method' => 'spacer', - ), - 'mt_from_email' => array( - 'friendly_name' => __('Source Address', 'mactrack'), - 'description' => __('The source Email address for Mactrack Emails.', 'mactrack'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '100', - 'size' => '30' - ), - 'mt_from_name' => array( - 'friendly_name' => __('Source Email Name', 'mactrack'), - 'description' => __('The Source Email name for Mactrack Emails.', 'mactrack'), - 'method' => 'textbox', - 'default' => __('MACTrack Administrator', 'mactrack'), - 'max_length' => '100', - 'size' => '30' - ), - 'mt_macwatch_description' => array( - 'friendly_name' => __('MacWatch Default Body', 'mactrack'), - 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain ' . - 'any valid html tags. It also supports replacement tags that will be processed when sending an Email. ' . - 'Valid tags include , , , , , , , .', 'mactrack')), - 'method' => 'textarea', - 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), - 'class' => 'textAreaNotes', - 'max_length' => '512', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - ), - 'mt_macauth_emails' => array( - 'friendly_name' => __('MacAuth Report Email Addresses', 'mactrack'), - 'description' => __('A comma delimited list of users to receive the MacAuth Email notifications.', 'mactrack'), - 'method' => 'textarea', - 'default' => '', - 'class' => 'textAreaNotes', - 'max_length' => '255', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - ), - 'mt_macauth_email_frequency' => array( - 'friendly_name' => __('MacAuth Report Frequency', 'mactrack'), - 'description' => __('How often will the MacAuth Reports be Emailed.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'disabled', - 'array' => $mactrack_macauth_frequencies, - ), - 'mactrack_hdr_arpwatch' => array( - 'friendly_name' => __('Mactrack ArpWatch Settings', 'mactrack'), - 'method' => 'spacer', - ), - 'mt_arpwatch' => array( - 'friendly_name' => __('Enable ArpWatch', 'mactrack'), - 'description' => __('Should Mactrack also use ArpWatch data to supplement Mac to IP/DNS resolution?', 'mactrack'), - 'default' => '', - 'method' => 'checkbox' - ), - 'mt_arpwatch_path' => array( - 'friendly_name' => __('ArpWatch Database Path', 'mactrack'), - 'description' => __('The location of the ArpWatch Database file on the Cacti server.', 'mactrack'), - 'method' => 'filepath', - 'default' => '', - 'max_length' => '255', - 'size' => '60' - ), - 'mactrack_hdr_general' => array( - 'friendly_name' => __('SNMP Presets', 'mactrack'), - 'method' => 'spacer', - ), - 'mt_update_policy' => array( - 'friendly_name' => __('Update Policy for SNMP Options', 'mactrack'), - 'description' => __('Policy for synchronization of SNMP Options between Cacti devices and Mactrack Devices.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 1, - 'array' => $mactrack_update_policies, - ), - 'mt_snmp_ver' => array( - 'friendly_name' => __('Version', 'mactrack'), - 'description' => __('Default SNMP version for all new hosts.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '2', - 'array' => $snmp_versions, - ), - 'mt_snmp_community' => array( - 'friendly_name' => __('Community', 'mactrack'), - 'description' => __('Default SNMP read community for all new hosts.', 'mactrack'), - 'method' => 'textbox', - 'default' => 'public', - 'max_length' => '100', - 'size' => '20' - ), - 'mt_snmp_communities' => array( - 'friendly_name' => __('Communities', 'mactrack'), - 'description' => __('Fill in the list of available SNMP read strings to test for this device. Each read string must be separated by a colon \':\'. These read strings will be tested sequentially if the primary read string is invalid.', 'mactrack'), - 'method' => 'textbox', - 'default' => 'public:private:secret', - 'max_length' => '255' - ), - 'mt_snmp_port' => array( - 'friendly_name' => __('Port', 'mactrack'), - 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), - 'method' => 'textbox', - 'default' => '161', - 'max_length' => '10', - 'size' => '4' - ), - 'mt_snmp_timeout' => array( - 'friendly_name' => __('Timeout', 'mactrack'), - 'description' => __('Default SNMP timeout in milli-seconds.', 'mactrack'), - 'method' => 'textbox', - 'default' => '500', - 'max_length' => '10', - 'size' => '4' - ), - 'mt_snmp_retries' => array( - 'friendly_name' => __('Retries', 'mactrack'), - 'description' => __('The number times the SNMP poller will attempt to reach the host before failing.', 'mactrack'), - 'method' => 'textbox', - 'default' => '3', - 'max_length' => '10', - 'size' => '4' - ) - ); - - $ts = array(); - foreach ($settings['path'] as $t => $ta) { - $ts[$t] = $ta; - if ($t == 'path_snmpget') { - $ts['path_snmpbulkwalk'] = array( - 'friendly_name' => __('snmpbulkwalk Binary Path', 'mactrack'), - 'description' => __('The path to your snmpbulkwalk binary.', 'mactrack'), - 'method' => 'textbox', - 'max_length' => '255' - ); - } - } - $settings['path']=$ts; - - $tabs_graphs += array('mactrack' => __('MacTrack Settings', 'mactrack')); - - $settings_user += array( - 'mactrack' => array( - 'default_mactrack_tab' => array( - 'friendly_name' => __('Default Tab', 'mactrack'), - 'description' => __('Which MacTrack tab would you want to be your Default tab every time you goto the MacTrack second.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'sites', - 'array' => array( - 'sites' => __('Sites', 'mactrack'), - 'devices' => __('Devices', 'mactrack'), - 'ips' => __('IP Addresses', 'mactrack'), - 'macs' => __('Mac Addresses', 'mactrack'), - 'interfaces' => __('Interfaces', 'mactrack'), - 'dot1x' => __('dot1x Deta', 'mactrack') - ) - ) - ) - ); - - $settings['mail'] += array( - 'settings_proxy_header' => array( - 'friendly_name' => __('Internet Proxy Settings'), - 'collapsible' => 'true', - 'method' => 'spacer', - ), - 'settings_proxy_server' => array( - 'friendly_name' => __('Internet Proxy Address'), - 'description' => __('For either core Cacti Services or Plugins that require internet access, enter the proxy server and port here in the following format IP:PORT. For example 192.168.1.1:8080.'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '30' - ), - 'settings_proxy_user' => array( - 'friendly_name' => __('Internet Proxy User'), - 'description' => __('If your Internet Proxy requires a username, enter it here.'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '10' - ), - 'settings_proxy_password' => array( - 'friendly_name' => __('Internet Proxy Password'), - 'description' => __('If your Internet Proxy requires a password, enter it here.'), - 'method' => 'textbox_password', - 'default' => '', - 'max_length' => '30', - 'size' => '10' - ), - ); - - mactrack_check_upgrade(); +function mactrack_config_settings() +{ + global $tabs, $settings, $settings_user, $tabs_graphs, $snmp_versions, $mactrack_poller_frequencies, + $mactrack_data_retention, $mactrack_macauth_frequencies, $mactrack_update_policies; + + $tabs['mactrack'] = __('Mactrack', 'mactrack'); + + $settings['mactrack'] = [ + 'mactrack_hdr_timing' => [ + 'friendly_name' => __('General Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_collection_timing' => [ + 'friendly_name' => __('Scanning Frequency', 'mactrack'), + 'description' => __('Choose when to collect MAC and IP Addresses and Interface statistics from your network devices.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'disabled', + 'array' => $mactrack_poller_frequencies, + ], + 'mt_processes' => [ + 'friendly_name' => __('Concurrent Processes', 'mactrack'), + 'description' => __('Specify how many devices will be polled simultaneously until all devices have been polled.', 'mactrack'), + 'default' => '7', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_script_runtime' => [ + 'friendly_name' => __('Scanner Max Runtime', 'mactrack'), + 'description' => __('Specify the number of minutes a device scanning function will be allowed to run prior to the system assuming it has been completed. This setting will correct for abended scanning jobs.', 'mactrack'), + 'default' => '20', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_base_time' => [ + 'friendly_name' => __('Start Time for Data Collection', 'mactrack'), + 'description' => __('When would you like the first data collection to take place. All future data collection times will be based upon this start time. A good example would be 12:00AM.', 'mactrack'), + 'default' => '1:00am', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '8', + ], + 'mt_maint_time' => [ + 'friendly_name' => __('Database Maintenance Time', 'mactrack'), + 'description' => __('When should old database records be removed from the database. Please note that no access will be permitted to the port database while this action is taking place.', 'mactrack'), + 'default' => '12:00am', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '8', + ], + 'mt_maint_confirm' => [ + 'friendly_name' => __('Confirm Utilities Prompt', 'mactrack'), + 'description' => __('When using utilities, prompt for verification', 'mactrack'), + 'default' => read_config_option('deletion_verification'), + 'method' => 'checkbox', + ], + 'mt_data_retention' => [ + 'friendly_name' => __('Data Retention', 'mactrack'), + 'description' => __('How long should port MAC details be retained in the database.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '14', + 'array' => $mactrack_data_retention, + ], + 'mt_data_retention_ip' => [ + 'friendly_name' => __('Data Retention IPs', 'mactrack'), + 'description' => __('How long should discovered IPs details be retained in the database.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '3', + 'array' => $mactrack_data_retention, + ], + 'mt_ignorePorts_delim' => [ + 'friendly_name' => __('Switch Level Ignore Ports Delimiter', 'mactrack'), + 'description' => __('What delimiter should Mactrack use when parsing the Ignore Ports string for each switch.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '-1', + 'array' => [ + '-1' => __('Auto Detect', 'mactrack'), + ':' => __('Colon [:]', 'mactrack'), + '|' => __('Pipe [|]', 'mactrack'), + ' ' => __('Space [ ]', 'mactrack'), + ], + ], + 'mt_mac_format' => [ + 'friendly_name' => __('Mac Address Output Format', 'mactrack'), + 'description' => __('Format used for display.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'aa:bb:cc:dd:ee:ff', + 'array' => [ + 'aa:bb:cc:dd:ee:ff' => 'aa:bb:cc:dd:ee:ff', + 'aa-bb-cc-dd-ee-ff' => 'aa-bb-cc-dd-ee-ff', + 'aabb-ccdd-eeff' => 'aabb-ccdd-eeff', + 'aabbccddeeff' => 'aabbccddeeff', + 'aabb.ccdd.eeff' => 'aabb.ccdd.eeff', + ], + ], + 'mt_ignorePorts' => [ + 'method' => 'textbox', + 'friendly_name' => __('Ports to Ignore', 'mactrack'), + 'description' => __('Provide a regular expression of ifNames or ifDescriptions of ports to ignore in the interface list. For example, (Vlan|Loopback|Null).', 'mactrack'), + 'class' => 'textAreaNotes', + 'defaults' => '(Vlan|Loopback|Null)', + 'max_length' => '255', + 'size' => '80', + ], + 'mt_interface_high' => [ + 'friendly_name' => __('Bandwidth Usage Threshold', 'mactrack'), + 'description' => __('When reviewing network interface statistics, what bandwidth threshold do you want to view by default.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '70', + 'array' => [ + '-1' => __('N/A', 'mactrack'), + '10' => __('%d Percent', 10, 'mactrack'), + '20' => __('%d Percent', 20, 'mactrack'), + '30' => __('%d Percent', 30, 'mactrack'), + '40' => __('%d Percent', 40, 'mactrack'), + '50' => __('%d Percent', 50, 'mactrack'), + '60' => __('%d Percent', 60, 'mactrack'), + '70' => __('%d Percent', 70, 'mactrack'), + '80' => __('%d Percent', 80, 'mactrack'), + '90' => __('%d Percent', 90, 'mactrack'), + ], + ], + 'mt_hdr_rdns' => [ + 'friendly_name' => __('DNS Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_reverse_dns' => [ + 'friendly_name' => __('Perform Reverse DNS Name Resolution', 'mactrack'), + 'description' => __('Should Mactrack perform reverse DNS lookup of the IP addresses associated with ports. CAUTION: If DNS is not properly setup, this will slow scan time significantly.', 'mactrack'), + 'default' => '', + 'method' => 'checkbox', + ], + 'mt_dns_primary' => [ + 'friendly_name' => __('Primary DNS IP Address', 'mactrack'), + 'description' => __('Enter the primary DNS IP Address to utilize for reverse lookups.', 'mactrack'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '18', + ], + 'mt_dns_secondary' => [ + 'friendly_name' => __('Secondary DNS IP Address', 'mactrack'), + 'description' => __('Enter the secondary DNS IP Address to utilize for reverse lookups.', 'mactrack'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '18', + ], + 'mt_dns_timeout' => [ + 'friendly_name' => __('DNS Timeout', 'mactrack'), + 'description' => __('Please enter the DNS timeout in milliseconds. Mactrack uses a PHP based DNS resolver.', 'mactrack'), + 'method' => 'textbox', + 'default' => '500', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_dns_prime_interval' => [ + 'friendly_name' => __('DNS Prime Interval', 'mactrack'), + 'description' => __('How often, in seconds do Mactrack scanning IP\'s need to be resolved to MAC addresses for DNS resolution. Using a larger number when you have several thousand devices will increase performance.', 'mactrack'), + 'method' => 'textbox', + 'default' => '120', + 'max_length' => '10', + 'size' => '4', + ], + 'mactrack_hdr_notification' => [ + 'friendly_name' => __('Notification Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_from_email' => [ + 'friendly_name' => __('Source Address', 'mactrack'), + 'description' => __('The source Email address for Mactrack Emails.', 'mactrack'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '100', + 'size' => '30', + ], + 'mt_from_name' => [ + 'friendly_name' => __('Source Email Name', 'mactrack'), + 'description' => __('The Source Email name for Mactrack Emails.', 'mactrack'), + 'method' => 'textbox', + 'default' => __('MACTrack Administrator', 'mactrack'), + 'max_length' => '100', + 'size' => '30', + ], + 'mt_macwatch_description' => [ + 'friendly_name' => __('MacWatch Default Body', 'mactrack'), + 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain ' + .'any valid html tags. It also supports replacement tags that will be processed when sending an Email. ' + .'Valid tags include , , , , , , , .', 'mactrack')), + 'method' => 'textarea', + 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), + 'class' => 'textAreaNotes', + 'max_length' => '512', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + ], + 'mt_macauth_emails' => [ + 'friendly_name' => __('MacAuth Report Email Addresses', 'mactrack'), + 'description' => __('A comma delimited list of users to receive the MacAuth Email notifications.', 'mactrack'), + 'method' => 'textarea', + 'default' => '', + 'class' => 'textAreaNotes', + 'max_length' => '255', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + ], + 'mt_macauth_email_frequency' => [ + 'friendly_name' => __('MacAuth Report Frequency', 'mactrack'), + 'description' => __('How often will the MacAuth Reports be Emailed.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'disabled', + 'array' => $mactrack_macauth_frequencies, + ], + 'mactrack_hdr_arpwatch' => [ + 'friendly_name' => __('Mactrack ArpWatch Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_arpwatch' => [ + 'friendly_name' => __('Enable ArpWatch', 'mactrack'), + 'description' => __('Should Mactrack also use ArpWatch data to supplement Mac to IP/DNS resolution?', 'mactrack'), + 'default' => '', + 'method' => 'checkbox', + ], + 'mt_arpwatch_path' => [ + 'friendly_name' => __('ArpWatch Database Path', 'mactrack'), + 'description' => __('The location of the ArpWatch Database file on the Cacti server.', 'mactrack'), + 'method' => 'filepath', + 'default' => '', + 'max_length' => '255', + 'size' => '60', + ], + 'mactrack_hdr_general' => [ + 'friendly_name' => __('SNMP Presets', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_update_policy' => [ + 'friendly_name' => __('Update Policy for SNMP Options', 'mactrack'), + 'description' => __('Policy for synchronization of SNMP Options between Cacti devices and Mactrack Devices.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 1, + 'array' => $mactrack_update_policies, + ], + 'mt_snmp_ver' => [ + 'friendly_name' => __('Version', 'mactrack'), + 'description' => __('Default SNMP version for all new hosts.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '2', + 'array' => $snmp_versions, + ], + 'mt_snmp_community' => [ + 'friendly_name' => __('Community', 'mactrack'), + 'description' => __('Default SNMP read community for all new hosts.', 'mactrack'), + 'method' => 'textbox', + 'default' => 'public', + 'max_length' => '100', + 'size' => '20', + ], + 'mt_snmp_communities' => [ + 'friendly_name' => __('Communities', 'mactrack'), + 'description' => __('Fill in the list of available SNMP read strings to test for this device. Each read string must be separated by a colon \':\'. These read strings will be tested sequentially if the primary read string is invalid.', 'mactrack'), + 'method' => 'textbox', + 'default' => 'public:private:secret', + 'max_length' => '255', + ], + 'mt_snmp_port' => [ + 'friendly_name' => __('Port', 'mactrack'), + 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), + 'method' => 'textbox', + 'default' => '161', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_snmp_timeout' => [ + 'friendly_name' => __('Timeout', 'mactrack'), + 'description' => __('Default SNMP timeout in milli-seconds.', 'mactrack'), + 'method' => 'textbox', + 'default' => '500', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_snmp_retries' => [ + 'friendly_name' => __('Retries', 'mactrack'), + 'description' => __('The number times the SNMP poller will attempt to reach the host before failing.', 'mactrack'), + 'method' => 'textbox', + 'default' => '3', + 'max_length' => '10', + 'size' => '4', + ], + ]; + + $ts = []; + foreach ($settings['path'] as $t => $ta) { + $ts[$t] = $ta; + if ('path_snmpget' == $t) { + $ts['path_snmpbulkwalk'] = [ + 'friendly_name' => __('snmpbulkwalk Binary Path', 'mactrack'), + 'description' => __('The path to your snmpbulkwalk binary.', 'mactrack'), + 'method' => 'textbox', + 'max_length' => '255', + ]; + } + } + $settings['path'] = $ts; + + $tabs_graphs += ['mactrack' => __('MacTrack Settings', 'mactrack')]; + + $settings_user += [ + 'mactrack' => [ + 'default_mactrack_tab' => [ + 'friendly_name' => __('Default Tab', 'mactrack'), + 'description' => __('Which MacTrack tab would you want to be your Default tab every time you goto the MacTrack second.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'sites', + 'array' => [ + 'sites' => __('Sites', 'mactrack'), + 'devices' => __('Devices', 'mactrack'), + 'ips' => __('IP Addresses', 'mactrack'), + 'macs' => __('Mac Addresses', 'mactrack'), + 'interfaces' => __('Interfaces', 'mactrack'), + 'dot1x' => __('dot1x Deta', 'mactrack'), + ], + ], + ], + ]; + + $settings['mail'] += [ + 'settings_proxy_header' => [ + 'friendly_name' => __('Internet Proxy Settings'), + 'collapsible' => 'true', + 'method' => 'spacer', + ], + 'settings_proxy_server' => [ + 'friendly_name' => __('Internet Proxy Address'), + 'description' => __('For either core Cacti Services or Plugins that require internet access, enter the proxy server and port here in the following format IP:PORT. For example 192.168.1.1:8080.'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '30', + ], + 'settings_proxy_user' => [ + 'friendly_name' => __('Internet Proxy User'), + 'description' => __('If your Internet Proxy requires a username, enter it here.'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '10', + ], + 'settings_proxy_password' => [ + 'friendly_name' => __('Internet Proxy Password'), + 'description' => __('If your Internet Proxy requires a password, enter it here.'), + 'method' => 'textbox_password', + 'default' => '', + 'max_length' => '30', + 'size' => '10', + ], + ]; + + mactrack_check_upgrade(); } -function mactrack_draw_navigation_text($nav) { - $nav['mactrack_devices.php:'] = array( - 'title' => __('Mactrack Devices', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_devices.php', - 'level' => '1' - ); - - $nav['mactrack_devices.php:edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_devices.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_devices.php:import'] = array( - 'title' => __('(Import)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_devices.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_devices.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_devices.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_snmp.php:'] = array( - 'title' => __('Mactrack SNMP Options', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_snmp.php', - 'level' => '1' - ); - - $nav['mactrack_snmp.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_snmp.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_snmp.php:edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_snmp.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_snmp.php:item_edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_snmp.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_device_types.php:'] = array( - 'title' => __('Mactrack Device Types', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_device_types.php', - 'level' => '1' - ); - - $nav['mactrack_device_types.php:edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_device_types.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_device_types.php:import'] = array( - 'title' => __('(Import)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_device_types.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_device_types.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_device_types.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_sites.php:'] = array( - 'title' => __('Mactrack Sites', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_sites.php', - 'level' => '1' - ); - - $nav['mactrack_sites.php:edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_sites.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_sites.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_sites.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_macwatch.php:'] = array( - 'title' => __('Mac Address Tracking Utility', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_macwatch.php', - 'level' => '1' - ); - - $nav['mactrack_macwatch.php:edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macwatch.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_macwatch.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macwatch.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_macauth.php:'] = array( - 'title' => __('Mac Address Authorization Utility', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_macauth.php', - 'level' => '1' - ); - - $nav['mactrack_macauth.php:edit'] = array( - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macauth.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_macauth.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macauth.php:', - 'url' => '', - 'level' => '2' - ); - - $nav['mactrack_vendormacs.php:'] = array( - 'title' => __('Mactrack Vendor Macs', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_vendormacs.php', - 'level' => '1' - ); - - $nav['mactrack_view_macs.php:'] = array( - 'title' => __('Mactrack View Macs', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_macs.php', - 'level' => '0' - ); - - $nav['mactrack_view_macs.php:actions'] = array( - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'mactrack_view_macs.php:', - 'url' => '', - 'level' => '1' - ); - - $nav['mactrack_view_dot1x.php:'] = array( - 'title' => __('Mactrack Dot1x View', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_dot1x.php', - 'level' => '0' - ); - - $nav['mactrack_view_arp.php:'] = array( - 'title' => __('Mactrack IP Address Viewer', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_arp.php', - 'level' => '0' - ); - - $nav['mactrack_view_interfaces.php:'] = array( - 'title' => __('Mactrack View Interfaces', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_interfaces.php', - 'level' => '0' - ); - - $nav['mactrack_view_sites.php:'] = array( - 'title' => __('Mactrack View Sites', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_sites.php', - 'level' => '0' - ); - - $nav['mactrack_view_ips.php:'] = array( - 'title' => __('Mactrack View IP Ranges', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_ips.php', - 'level' => '0' - ); - - $nav['mactrack_view_devices.php:'] = array( - 'title' => __('Mactrack View Devices', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_devices.php', - 'level' => '0' - ); - - $nav['mactrack_utilities.php:'] = array( - 'title' => __('Mactrack Utilities', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '1' - ); - - $nav['mactrack_utilities.php:mactrack_utilities_perform_db_maint'] = array( - 'title' => __('Perform Database Maintenance', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_utilities.php:mactrack_utilities_purge_scanning_funcs'] = array( - 'title' => __('Refresh Scanning Functions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_utilities.php:mactrack_utilities_truncate_ports_table'] = array( - 'title' => __('Truncate Port Results Table', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_utilities.php:mactrack_utilities_purge_aggregated_data'] = array( - 'title' => __('Truncate Aggregated Port Results Table', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_utilities.php:mactrack_utilities_recreate_aggregated_data'] = array( - 'title' => __('Truncate and Re-create Aggregated Port Results Table', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_utilities.php:mactrack_proc_status'] = array( - 'title' => __('View Mactrack Process Status', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_utilities.php:mactrack_refresh_oui_database'] = array( - 'title' => __('Refresh/Update Vendor MAC Database from IEEE', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2' - ); - - $nav['mactrack_view_graphs.php:'] = array( - 'title' => __('Mactrack Graph Viewer', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_graphs.php', - 'level' => '0' - ); - - $nav['mactrack_view_graphs.php:preview'] = array( - 'title' => __('Mactrack Graph Viewer', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_graphs.php', - 'level' => '0' - ); - - return $nav; +function mactrack_draw_navigation_text($nav) +{ + $nav['mactrack_devices.php:'] = [ + 'title' => __('Mactrack Devices', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_devices.php', + 'level' => '1', + ]; + + $nav['mactrack_devices.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_devices.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_devices.php:import'] = [ + 'title' => __('(Import)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_devices.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_devices.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_devices.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_snmp.php:'] = [ + 'title' => __('Mactrack SNMP Options', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_snmp.php', + 'level' => '1', + ]; + + $nav['mactrack_snmp.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_snmp.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_snmp.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_snmp.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_snmp.php:item_edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_snmp.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_device_types.php:'] = [ + 'title' => __('Mactrack Device Types', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_device_types.php', + 'level' => '1', + ]; + + $nav['mactrack_device_types.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_device_types.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_device_types.php:import'] = [ + 'title' => __('(Import)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_device_types.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_device_types.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_device_types.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_sites.php:'] = [ + 'title' => __('Mactrack Sites', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_sites.php', + 'level' => '1', + ]; + + $nav['mactrack_sites.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_sites.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_sites.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_sites.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macwatch.php:'] = [ + 'title' => __('Mac Address Tracking Utility', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_macwatch.php', + 'level' => '1', + ]; + + $nav['mactrack_macwatch.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macwatch.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macwatch.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macwatch.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macauth.php:'] = [ + 'title' => __('Mac Address Authorization Utility', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_macauth.php', + 'level' => '1', + ]; + + $nav['mactrack_macauth.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macauth.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macauth.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macauth.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_vendormacs.php:'] = [ + 'title' => __('Mactrack Vendor Macs', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_vendormacs.php', + 'level' => '1', + ]; + + $nav['mactrack_view_macs.php:'] = [ + 'title' => __('Mactrack View Macs', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_macs.php', + 'level' => '0', + ]; + + $nav['mactrack_view_macs.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'mactrack_view_macs.php:', + 'url' => '', + 'level' => '1', + ]; + + $nav['mactrack_view_dot1x.php:'] = [ + 'title' => __('Mactrack Dot1x View', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_dot1x.php', + 'level' => '0', + ]; + + $nav['mactrack_view_arp.php:'] = [ + 'title' => __('Mactrack IP Address Viewer', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_arp.php', + 'level' => '0', + ]; + + $nav['mactrack_view_interfaces.php:'] = [ + 'title' => __('Mactrack View Interfaces', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_interfaces.php', + 'level' => '0', + ]; + + $nav['mactrack_view_sites.php:'] = [ + 'title' => __('Mactrack View Sites', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_sites.php', + 'level' => '0', + ]; + + $nav['mactrack_view_ips.php:'] = [ + 'title' => __('Mactrack View IP Ranges', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_ips.php', + 'level' => '0', + ]; + + $nav['mactrack_view_devices.php:'] = [ + 'title' => __('Mactrack View Devices', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_devices.php', + 'level' => '0', + ]; + + $nav['mactrack_utilities.php:'] = [ + 'title' => __('Mactrack Utilities', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '1', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_perform_db_maint'] = [ + 'title' => __('Perform Database Maintenance', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_purge_scanning_funcs'] = [ + 'title' => __('Refresh Scanning Functions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_truncate_ports_table'] = [ + 'title' => __('Truncate Port Results Table', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_purge_aggregated_data'] = [ + 'title' => __('Truncate Aggregated Port Results Table', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_recreate_aggregated_data'] = [ + 'title' => __('Truncate and Re-create Aggregated Port Results Table', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_proc_status'] = [ + 'title' => __('View Mactrack Process Status', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_refresh_oui_database'] = [ + 'title' => __('Refresh/Update Vendor MAC Database from IEEE', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_view_graphs.php:'] = [ + 'title' => __('Mactrack Graph Viewer', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_graphs.php', + 'level' => '0', + ]; + + $nav['mactrack_view_graphs.php:preview'] = [ + 'title' => __('Mactrack Graph Viewer', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_graphs.php', + 'level' => '0', + ]; + + return $nav; } -function mactrack_show_tab() { - global $config, $user_auth_realm_filenames; +function mactrack_show_tab() +{ + global $config, $user_auth_realm_filenames; - include_once($config['base_path'] . '/plugins/mactrack/lib/mactrack_functions.php'); + include_once $config['base_path'].'/plugins/mactrack/lib/mactrack_functions.php'; - if (!isset_request_var('report')) { - set_request_var('report', 'sites'); - } + if (!isset_request_var('report')) { + set_request_var('report', 'sites'); + } - if (api_user_realm_auth('mactrack_view_macs.php')) { - if (substr_count($_SERVER['REQUEST_URI'], 'mactrack_view_')) { - print '' . __('MacTrack', 'mactrack') . ''; - } else { - print '' . __('MacTrack', 'mactrack') . ''; - } - } + if (api_user_realm_auth('mactrack_view_macs.php')) { + if (substr_count($_SERVER['REQUEST_URI'], 'mactrack_view_')) { + echo ''.__('MacTrack', 'mactrack').''; + } else { + echo ''.__('MacTrack', 'mactrack').''; + } + } } -function mactrack_config_arrays() { - global $mactrack_device_types, $mactrack_search_types, $messages; - global $menu, $menu_glyphs, $config, $rows_selector; - global $mactrack_poller_frequencies, $mactrack_data_retention, $refresh_interval; - global $mactrack_macauth_frequencies, $mactrack_duplexes, $mactrack_update_policies; - - if (isset($_SESSION['mactrack_message']) && $_SESSION['mactrack_message'] != '') { - $messages['mactrack_message'] = array('message' => $_SESSION['mactrack_message'], 'type' => 'info'); - kill_session_var('mactrack_message'); - } - - $refresh_interval = array( - 5 => __('%d Seconds', 5, 'mactrack'), - 10 => __('%d Seconds', 10, 'mactrack'), - 20 => __('%d Seconds', 20, 'mactrack'), - 30 => __('%d Seconds', 30, 'mactrack'), - 60 => __('%d Minute', 1, 'mactrack'), - 300 => __('%d Minutes', 5, 'mactrack') - ); - - $mactrack_device_types = array( - 1 => __('Switch/Hub', 'mactrack'), - 2 => __('Switch/Router', 'mactrack'), - 3 => __('Router', 'mactrack') - ); - - $mactrack_search_types = array( - 1 => '', - 2 => __('Matches', 'mactrack'), - 3 => __('Contains', 'mactrack'), - 4 => __('Begins With', 'mactrack'), - 5 => __('Does Not Contain', 'mactrack'), - 6 => __('Does Not Begin With', 'mactrack'), - 7 => __('Is Null', 'mactrack'), - 8 => __('Is Not Null', 'mactrack') - ); - - $mactrack_duplexes = array( - 1 => __('Unknown', 'mactrack'), - 2 => __('Half', 'mactrack'), - 3 => __('Full', 'mactrack') - ); - - $mactrack_update_policies = array( - 1 => __('None', 'mactrack'), - 2 => __('Sync Cacti Device to Mactrack Device', 'mactrack'), - 3 => __('Sync Mactrack Device to Cacti Device', 'mactrack') - ); - - $rows_selector = array( - -1 => __('Default', 'mactrack'), - 10 => '10', - 15 => '15', - 20 => '20', - 30 => '30', - 50 => '50', - 100 => '100', - 500 => '500', - 1000 => '1000', - -2 => __('All', 'mactrack') - ); - - $mactrack_poller_frequencies = array( - 'disabled' => __('Disabled', 'mactrack'), - '5' => __('Every %d Minutes', 5, 'mactrack'), - '10' => __('Every %d Minutes', 10, 'mactrack'), - '15' => __('Every %d Minutes', 15, 'mactrack'), - '20' => __('Every %d Minutes', 20, 'mactrack'), - '30' => __('Every %d Minutes', 30, 'mactrack'), - '60' => __('Every %d Hour', 1, 'mactrack'), - '120' => __('Every %d Hours', 2, 'mactrack'), - '240' => __('Every %d Hours', 4, 'mactrack'), - '480' => __('Every %d Hours', 8, 'mactrack'), - '720' => __('Every %d Hours', 12, 'mactrack'), - '1440' => __('Every Day', 'mactrack') - ); - - $mactrack_data_retention = array( - '3' => __('%d Days', 3, 'mactrack'), - '7' => __('%d Days', 7, 'mactrack'), - '10' => __('%d Days', 10, 'mactrack'), - '14' => __('%d Days', 14, 'mactrack'), - '20' => __('%d Days', 20, 'mactrack'), - '30' => __('%d Month', 1, 'mactrack'), - '60' => __('%d Months', 2, 'mactrack'), - '120' => __('%d Months', 4, 'mactrack'), - '240' => __('%d Months', 8, 'mactrack'), - '365' => __('%d Year', 1, 'mactrack') - ); - - $mactrack_macauth_frequencies = array( - 'disabled' => __('Disabled', 'mactrack'), - '0' => __('On Scan Completion', 'mactrack'), - '720' => __('Every %d Hours', 12), - '1440' => __('Every Day', 'mactrack'), - '2880' => __('Every %d Days', 2), - '10080' => __('Every Week', 'mactrack') - ); - - $menu2 = array (); - foreach ($menu as $temp => $temp2 ) { - $menu2[$temp] = $temp2; - if ($temp == __('Management')) { - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_sites.php'] = __('Sites', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_devices.php'] = __('Devices', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_snmp.php'] = __('SNMP Options', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_device_types.php'] = __('Device Types', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_vendormacs.php'] = __('Vendor Macs', 'mactrack'); - $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macwatch.php'] = __('Mac Watch', 'mactrack'); - $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macauth.php'] = __('Mac Authorizations', 'mactrack'); - $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_utilities.php'] = __('Tracking Utilities', 'mactrack'); - } - } - $menu = $menu2; - - if (cacti_version_compare(CACTI_VERSION, '1.2', '<')) { - $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield'; - } else { - $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield-alt'; - } - $menu_glyphs[__('Mactrack Tools', 'mactrack')] = 'fa fa-bullhorn'; +function mactrack_config_arrays() +{ + global $mactrack_device_types, $mactrack_search_types, $messages; + global $menu, $menu_glyphs, $config, $rows_selector; + global $mactrack_poller_frequencies, $mactrack_data_retention, $refresh_interval; + global $mactrack_macauth_frequencies, $mactrack_duplexes, $mactrack_update_policies; + + if (isset($_SESSION['mactrack_message']) && '' != $_SESSION['mactrack_message']) { + $messages['mactrack_message'] = ['message' => $_SESSION['mactrack_message'], 'type' => 'info']; + kill_session_var('mactrack_message'); + } + + $refresh_interval = [ + 5 => __('%d Seconds', 5, 'mactrack'), + 10 => __('%d Seconds', 10, 'mactrack'), + 20 => __('%d Seconds', 20, 'mactrack'), + 30 => __('%d Seconds', 30, 'mactrack'), + 60 => __('%d Minute', 1, 'mactrack'), + 300 => __('%d Minutes', 5, 'mactrack'), + ]; + + $mactrack_device_types = [ + 1 => __('Switch/Hub', 'mactrack'), + 2 => __('Switch/Router', 'mactrack'), + 3 => __('Router', 'mactrack'), + ]; + + $mactrack_search_types = [ + 1 => '', + 2 => __('Matches', 'mactrack'), + 3 => __('Contains', 'mactrack'), + 4 => __('Begins With', 'mactrack'), + 5 => __('Does Not Contain', 'mactrack'), + 6 => __('Does Not Begin With', 'mactrack'), + 7 => __('Is Null', 'mactrack'), + 8 => __('Is Not Null', 'mactrack'), + ]; + + $mactrack_duplexes = [ + 1 => __('Unknown', 'mactrack'), + 2 => __('Half', 'mactrack'), + 3 => __('Full', 'mactrack'), + ]; + + $mactrack_update_policies = [ + 1 => __('None', 'mactrack'), + 2 => __('Sync Cacti Device to Mactrack Device', 'mactrack'), + 3 => __('Sync Mactrack Device to Cacti Device', 'mactrack'), + ]; + + $rows_selector = [ + -1 => __('Default', 'mactrack'), + 10 => '10', + 15 => '15', + 20 => '20', + 30 => '30', + 50 => '50', + 100 => '100', + 500 => '500', + 1000 => '1000', + -2 => __('All', 'mactrack'), + ]; + + $mactrack_poller_frequencies = [ + 'disabled' => __('Disabled', 'mactrack'), + '5' => __('Every %d Minutes', 5, 'mactrack'), + '10' => __('Every %d Minutes', 10, 'mactrack'), + '15' => __('Every %d Minutes', 15, 'mactrack'), + '20' => __('Every %d Minutes', 20, 'mactrack'), + '30' => __('Every %d Minutes', 30, 'mactrack'), + '60' => __('Every %d Hour', 1, 'mactrack'), + '120' => __('Every %d Hours', 2, 'mactrack'), + '240' => __('Every %d Hours', 4, 'mactrack'), + '480' => __('Every %d Hours', 8, 'mactrack'), + '720' => __('Every %d Hours', 12, 'mactrack'), + '1440' => __('Every Day', 'mactrack'), + ]; + + $mactrack_data_retention = [ + '3' => __('%d Days', 3, 'mactrack'), + '7' => __('%d Days', 7, 'mactrack'), + '10' => __('%d Days', 10, 'mactrack'), + '14' => __('%d Days', 14, 'mactrack'), + '20' => __('%d Days', 20, 'mactrack'), + '30' => __('%d Month', 1, 'mactrack'), + '60' => __('%d Months', 2, 'mactrack'), + '120' => __('%d Months', 4, 'mactrack'), + '240' => __('%d Months', 8, 'mactrack'), + '365' => __('%d Year', 1, 'mactrack'), + ]; + + $mactrack_macauth_frequencies = [ + 'disabled' => __('Disabled', 'mactrack'), + '0' => __('On Scan Completion', 'mactrack'), + '720' => __('Every %d Hours', 12), + '1440' => __('Every Day', 'mactrack'), + '2880' => __('Every %d Days', 2), + '10080' => __('Every Week', 'mactrack'), + ]; + + $menu2 = []; + foreach ($menu as $temp => $temp2) { + $menu2[$temp] = $temp2; + if ($temp == __('Management')) { + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_sites.php'] = __('Sites', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_devices.php'] = __('Devices', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_snmp.php'] = __('SNMP Options', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_device_types.php'] = __('Device Types', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_vendormacs.php'] = __('Vendor Macs', 'mactrack'); + $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macwatch.php'] = __('Mac Watch', 'mactrack'); + $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macauth.php'] = __('Mac Authorizations', 'mactrack'); + $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_utilities.php'] = __('Tracking Utilities', 'mactrack'); + } + } + $menu = $menu2; + + if (cacti_version_compare(CACTI_VERSION, '1.2', '<')) { + $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield'; + } else { + $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield-alt'; + } + $menu_glyphs[__('Mactrack Tools', 'mactrack')] = 'fa fa-bullhorn'; } -function mactrack_config_form () { - global $fields_mactrack_device_type_edit, $fields_mactrack_device_edit, $fields_mactrack_site_edit; - global $fields_mactrack_snmp_edit, $fields_mactrack_snmp_item, $fields_mactrack_snmp_item_edit; - global $mactrack_device_types, $snmp_versions, $fields_mactrack_macw_edit, $fields_mactrack_maca_edit; - global $snmp_priv_protocols, $snmp_auth_protocols; - - /* file: mactrack_device_types.php, action: edit */ - $fields_mactrack_device_type_edit = array( - 'spacer0' => array( - 'method' => 'spacer', - 'friendly_name' => __('Device Scanning Function Options', 'mactrack') - ), - 'description' => array( - 'method' => 'textbox', - 'friendly_name' => __('Description', 'mactrack'), - 'description' => __('Give this device type a meaningful description.', 'mactrack'), - 'value' => '|arg1:description|', - 'max_length' => '250' - ), - 'vendor' => array( - 'method' => 'textbox', - 'friendly_name' => __('Vendor', 'mactrack'), - 'description' => __('Fill in the name for the vendor of this device type.', 'mactrack'), - 'value' => '|arg1:vendor|', - 'max_length' => '250' - ), - 'device_type' => array( - 'method' => 'drop_array', - 'friendly_name' => __('Device Type', 'mactrack'), - 'description' => __('Choose the type of device.', 'mactrack'), - 'value' => '|arg1:device_type|', - 'default' => 1, - 'array' => $mactrack_device_types - ), - 'sysDescr_match' => array( - 'method' => 'textbox', - 'friendly_name' => __('System Description Match', 'mactrack'), - 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), - 'value' => '|arg1:sysDescr_match|', - 'max_length' => '250' - ), - 'sysObjectID_match' => array( - 'method' => 'textbox', - 'friendly_name' => __('Vendor SNMP Object ID Match', 'mactrack'), - 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), - 'value' => '|arg1:sysObjectID_match|', - 'max_length' => '250' - ), - 'scanning_function' => array( - 'method' => 'drop_sql', - 'friendly_name' => __('MAC Address Scanning Function', 'mactrack'), - 'description' => __('Mactrack scanning function to call in order to obtain and store port details. The function name is all that is required. The following four parameters are assumed and will always be appended: \'my_function($site, &$device, $lowport, $highport)\'. There is no function required for a pure router.', 'mactrack'), - 'value' => '|arg1:scanning_function|', - 'default' => 0, - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select scanning_function as id, scanning_function as name from mac_track_scanning_functions where type="1" order by scanning_function' - ), - 'ip_scanning_function' => array( - 'method' => 'drop_sql', - 'friendly_name' => __('IP Address Scanning Function', 'mactrack'), - 'description' => __('Mactrack scanning function specific to Layer3 devices that track IP Addresses.', 'mactrack'), - 'value' => '|arg1:ip_scanning_function|', - 'default' => 0, - 'none_value' => __('None', 'mactrack'), - 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="2" ORDER BY scanning_function' - ), - 'dot1x_scanning_function' => array( - 'method' => 'drop_sql', - 'friendly_name' => __('802.1x Scanning Function', 'mactrack'), - 'description' => __('Mactrack scanning function specific to Switches with dot1x enabled.', 'mactrack'), - 'value' => '|arg1:dot1x_scanning_function|', - 'default' => '', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="3" ORDER BY scanning_function' - ), - 'serial_number_oid' => array( - 'method' => 'textbox', - 'friendly_name' => __('Serial Number Base OID', 'mactrack'), - 'description' => __('The SNMP OID used to obtain this device types serial number to be stored in the Mactrack Asset Information table.', 'mactrack'), - 'value' => '|arg1:serial_number_oid|', - 'max_length' => '100', - 'default' => '' - ), - 'serial_number_oid_type' => array( - 'method' => 'drop_array', - 'friendly_name' => __('Serial Number Collection Method', 'mactrack'), - 'description' => __('How is the serial number collected for this OID. If \'SNMP Walk\', we assume multiple serial numbers. If \'Get\', it will be only one..', 'mactrack'), - 'value' => '|arg1:serial_number_oid_method|', - 'default' => 'get', - 'array' => array('get' => __('SNMP Get', 'mactrack'), 'walk' => __('SNMP Walk', 'mactrack')) - ), - 'lowPort' => array( - 'method' => 'textbox', - 'friendly_name' => __('Low User Port Number', 'mactrack'), - 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), - 'value' => '|arg1:lowPort|', - 'default' => read_config_option('mt_port_lowPort'), - 'max_length' => '100', - 'size' => '10' - ), - 'highPort' => array( - 'method' => 'textbox', - 'friendly_name' => __('High User Port Number', 'mactrack'), - 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), - 'value' => '|arg1:highPort|', - 'default' => read_config_option('mt_port_highPort'), - 'max_length' => '100', - 'size' => '10' - ), - 'disabled' => array( - 'method' => 'checkbox', - 'friendly_name' => __('Disabled', 'mactrack'), - 'description' => __('Disabled device type is not used.', 'mactrack'), - 'value' => '|arg1:disabled|', - 'default' => '' - ), - 'device_type_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:device_type_id|' - ), - '_device_type_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:device_type_id|' - ), - 'save_component_device_type' => array( - 'method' => 'hidden', - 'value' => '1' - ) - ); - - /* file: mactrack_snmp.php, action: edit */ - $fields_mactrack_snmp_edit = array( - 'name' => array( - 'method' => 'textbox', - 'friendly_name' => __('Name', 'mactrack'), - 'description' => __('Fill in the name of this SNMP option set.', 'mactrack'), - 'value' => '|arg1:name|', - 'default' => '', - 'max_length' => '100', - 'size' => '40' - ), - ); - - /* file: mactrack_snmp.php, action: item_edit */ - $fields_mactrack_snmp_item = array( - 'snmp_version' => array( - 'method' => 'drop_array', - 'friendly_name' => __('SNMP Version', 'mactrack'), - 'description' => __('Choose the SNMP version for this host.', 'mactrack'), - 'value' => '|arg1:snmp_version|', - 'default' => read_config_option('mt_snmp_ver'), - 'array' => $snmp_versions - ), - 'snmp_readstring' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Community String', 'mactrack'), - 'description' => __('Fill in the SNMP read community for this device.', 'mactrack'), - 'value' => '|arg1:snmp_readstring|', - 'default' => read_config_option('mt_snmp_community'), - 'max_length' => '100', - 'size' => '20' - ), - 'snmp_port' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Port', 'mactrack'), - 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), - 'value' => '|arg1:snmp_port|', - 'max_length' => '8', - 'default' => read_config_option('mt_snmp_port'), - 'size' => '10' - ), - 'snmp_timeout' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Timeout', 'mactrack'), - 'description' => __('The maximum number of milliseconds Cacti will wait for an SNMP response (does not work with php-snmp support).', 'mactrack'), - 'value' => '|arg1:snmp_timeout|', - 'max_length' => '8', - 'default' => read_config_option('mt_snmp_timeout'), - 'size' => '10' - ), - 'snmp_retries' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Retries', 'mactrack'), - 'description' => __('The maximum number of attempts to reach a device via an SNMP readstring prior to giving up.', 'mactrack'), - 'value' => '|arg1:snmp_retries|', - 'max_length' => '8', - 'default' => read_config_option('mt_snmp_retries'), - 'size' => '10' - ), - 'max_oids' => array( - 'method' => 'textbox', - 'friendly_name' => __('Maximum OID\'s Per Get Request', 'mactrack'), - 'description' => __('Specified the number of OID\'s that can be obtained in a single SNMP Get request.', 'mactrack'), - 'value' => '|arg1:max_oids|', - 'max_length' => '8', - 'default' => read_config_option('max_get_size'), - 'size' => '15' - ), - 'snmp_username' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Username (v3)', 'mactrack'), - 'description' => __('SNMP v3 username for this device.', 'mactrack'), - 'value' => '|arg1:snmp_username|', - 'default' => read_config_option('snmp_username'), - 'max_length' => '50', - 'size' => '15' - ), - 'snmp_password' => array( - 'method' => 'textbox_password', - 'friendly_name' => __('SNMP Password (v3)', 'mactrack'), - 'description' => __('SNMP v3 password for this device.', 'mactrack'), - 'value' => '|arg1:snmp_password|', - 'default' => read_config_option('snmp_password'), - 'max_length' => '50', - 'size' => '15' - ), - 'snmp_auth_protocol' => array( - 'method' => 'drop_array', - 'friendly_name' => __('SNMP Auth Protocol (v3)', 'mactrack'), - 'description' => __('Choose the SNMPv3 Authorization Protocol.', 'mactrack'), - 'value' => '|arg1:snmp_auth_protocol|', - 'default' => read_config_option('snmp_auth_protocol'), - 'array' => $snmp_auth_protocols, - ), - 'snmp_priv_passphrase' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Privacy Passphrase (v3)', 'mactrack'), - 'description' => __('Choose the SNMPv3 Privacy Passphrase.', 'mactrack'), - 'value' => '|arg1:snmp_priv_passphrase|', - 'default' => read_config_option('snmp_priv_passphrase'), - 'max_length' => '200', - 'size' => '40' - ), - 'snmp_priv_protocol' => array( - 'method' => 'drop_array', - 'friendly_name' => __('SNMP Privacy Protocol (v3)', 'mactrack'), - 'description' => __('Choose the SNMPv3 Privacy Protocol.', 'mactrack'), - 'value' => '|arg1:snmp_priv_protocol|', - 'default' => read_config_option('snmp_priv_protocol'), - 'array' => $snmp_priv_protocols, - ), - 'snmp_context' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Context (v3)', 'mactrack'), - 'description' => __('Enter the SNMP v3 Context to use for this device.', 'mactrack'), - 'value' => '|arg1:snmp_context|', - 'default' => '', - 'max_length' => '64', - 'size' => '40' - ), - 'snmp_engine_id' => array( - 'method' => 'textbox', - 'friendly_name' => __('SNMP Engine ID (v3)', 'mactrack'), - 'description' => __('Enter the SNMP v3 Engine ID to use for this device.', 'mactrack'), - 'value' => '|arg1:snmp_engine_id|', - 'default' => '', - 'max_length' => '64', - 'size' => '40' - ), - ); - - /* file: mactrack_devices.php, action: edit */ - $fields_mactrack_device_edit = array( - 'spacer0' => array( - 'method' => 'spacer', - 'friendly_name' => __('General Device Settings', 'mactrack') - ), - 'device_name' => array( - 'method' => 'textbox', - 'friendly_name' => __('Device Name', 'mactrack'), - 'description' => __('Give this device a meaningful name.', 'mactrack'), - 'value' => '|arg1:device_name|', - 'max_length' => '250' - ), - 'hostname' => array( - 'method' => 'textbox', - 'friendly_name' => __('Hostname', 'mactrack'), - 'description' => __('Fill in the fully qualified hostname for this device.', 'mactrack'), - 'value' => '|arg1:hostname|', - 'max_length' => '250' - ), - 'host_id' => array( - 'friendly_name' => __('Related Cacti Host', 'mactrack'), - 'description' => __('Given Mactrack Host is connected to this Cacti Host.', 'mactrack'), - #'method' => 'view', - 'method' => 'drop_sql', - 'value' => '|arg1:host_id|', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select id,CONCAT_WS("",description," (",hostname,")") as name from host order by description,hostname' - ), - 'device_type_id' => array( - 'method' => 'drop_sql', - 'friendly_name' => 'Device Type', - 'description' => 'Choose the type of device.', - 'value' => '|arg1:device_type_id|', - 'default' => 0, - 'none_value' => 'Not Detected', - 'sql' => 'select device_type_id as id,description as name from mac_track_device_types order by description' - ), - 'scan_type' => array( - 'method' => 'drop_array', - 'friendly_name' => __('Scan Type', 'mactrack'), - 'description' => __('Choose the scan type you wish to perform on this device.', 'mactrack'), - 'value' => '|arg1:scan_type|', - 'default' => 1, - 'array' => $mactrack_device_types - ), - 'site_id' => array( - 'method' => 'drop_sql', - 'friendly_name' => __('Site Name', 'mactrack'), - 'description' => __('Choose the site to associate with this device.', 'mactrack'), - 'value' => '|arg1:site_id|', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select site_id as id,site_name as name from mac_track_sites order by name' - ), - 'notes' => array( - 'method' => 'textarea', - 'friendly_name' => __('Device Notes', 'mactrack'), - 'description' => __('This field value is useful to save general information about a specific device.', 'mactrack'), - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'value' => '|arg1:notes|', - 'max_length' => '255' - ), - 'disabled' => array( - 'method' => 'checkbox', - 'friendly_name' => __('Disable Device', 'mactrack'), - 'description' => __('Check this box to disable all checks for this host.', 'mactrack'), - 'value' => '|arg1:disabled|', - 'default' => '', - 'form_id' => false - ), - 'spacer1' => array( - 'method' => 'spacer', - 'friendly_name' => __('Switch/Hub, Switch/Router Settings', 'mactrack') - ), - 'ignorePorts' => array( - 'method' => 'textarea', - 'friendly_name' => __('Ports to Ignore', 'mactrack'), - 'description' => __('Provide a list of ports on a specific switch/hub whose MAC results should be ignored. Ports such as link/trunk ports that can not be distinguished from other user ports are examples. Each port number must be separated by a colon, pipe, or a space \':\', \'|\', \' \'. For example, \'Fa0/1: Fa1/23\' or \'Fa0/1 Fa1/23\' would be acceptable for some manufacturers switch types.', 'mactrack'), - 'value' => '|arg1:ignorePorts|', - 'default' => '', - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'max_length' => '255' - ), - 'scan_trunk_port' => array( - 'method' => 'textarea', - 'friendly_name' => 'Trunk Ports to Scan', - 'description' => 'A comma delimited list of Port Number to be scanned. Some VMware network port will be configured with 802.1Q', - 'value' => '|arg1:scan_trunk_port|', - 'default' => '', - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'max_length' => '255' - ), - 'spacer2' => array( - 'method' => 'spacer', - 'friendly_name' => __('SNMP Options', 'mactrack') - ), - 'snmp_options' => array( - 'method' => 'drop_sql', - 'friendly_name' => __('SNMP Options', 'mactrack'), - 'description' => __('You can use specific SNMP settings or select SNMP set. In the second case, mactrack tries to find correct settings from SNMP set', 'mactrack'), - 'value' => '|arg1:snmp_options|', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select * from mac_track_snmp order by name' - ), - 'snmp_readstrings' => array( - 'method' => 'view', - 'friendly_name' => __('Read Strings', 'mactrack'), - 'description' => __('DEPRECATED: SNMP community strings', 'mactrack'), - 'value' => '|arg1:snmp_readstrings|', - ), - 'spacer3' => array( - 'method' => 'spacer', - 'friendly_name' => __('Specific SNMP Settings', 'mactrack') - ), - ); - - $fields_mactrack_device_edit += $fields_mactrack_snmp_item; - - $fields_mactrack_device_edit += array( - 'spacer4' => array( - 'method' => 'spacer', - 'friendly_name' => __('Connectivity Options', 'mactrack') - ), - 'term_type' => array( - 'method' => 'drop_array', - 'friendly_name' => __('Terminal Type', 'mactrack'), - 'description' => __('Choose the terminal type that you use to connect to this device.', 'mactrack'), - 'value' => '|arg1:term_type|', - 'default' => 1, - 'array' => array( - 0 => __('None', 'mactrack'), - 1 => __('Telnet', 'mactrack'), - 2 => __('SSH', 'mactrack'), - 3 => __('HTTP', 'mactrack'), - 4 => __('HTTPS', 'mactrack')) - ), - 'user_name' => array( - 'method' => 'textbox', - 'friendly_name' => __('User Name', 'mactrack'), - 'description' => __('The user name to be used for your custom authentication method. Examples include SSH, RSH, HTML, etc.', 'mactrack'), - 'value' => '|arg1:user_name|', - 'default' => '', - 'max_length' => '40', - 'size' => '20' - ), - 'user_password' => array( - 'method' => 'textbox_password', - 'friendly_name' => __('Password', 'mactrack'), - 'description' => __('The password to be used for your custom authentication.', 'mactrack'), - 'value' => '|arg1:user_password|', - 'default' => '', - 'max_length' => '40', - 'size' => '20' - ), - 'private_key_path' => array( - 'method' => 'filepath', - 'friendly_name' => __('Private Key Path', 'mactrack'), - 'description' => __('The path to the private key used for SSH authentication.', 'mactrack'), - 'value' => '|arg1:private_key_path|', - 'default' => '', - 'max_length' => '128', - 'size' => '40' - ), - 'device_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:device_id|' - ), - '_device_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:device_id|' - ), - 'save_component_device' => array( - 'method' => 'hidden', - 'value' => '1' - ) - ); - - /* file: mactrack_snmp.php, action: item_edit */ - $fields_mactrack_snmp_item_edit = $fields_mactrack_snmp_item + array( - 'sequence' => array( - 'method' => 'view', - 'friendly_name' => __('Sequence', 'mactrack'), - 'description' => __('Sequence of Item.', 'mactrack'), - 'value' => '|arg1:sequence|'), - ); - - /* file: mactrack_sites.php, action: edit */ - $fields_mactrack_site_edit = array( - 'spacer0' => array( - 'method' => 'spacer', - 'friendly_name' => __('General Site Settings', 'mactrack') - ), - 'site_name' => array( - 'method' => 'textbox', - 'friendly_name' => __('Site Name', 'mactrack'), - 'description' => __('Please enter a reasonable name for this site.', 'mactrack'), - 'value' => '|arg1:site_name|', - 'size' => '70', - 'max_length' => '250' - ), - 'customer_contact' => array( - 'method' => 'textbox', - 'friendly_name' => __('Primary Customer Contact', 'mactrack'), - 'description' => __('The principal customer contact name and number for this site.', 'mactrack'), - 'value' => '|arg1:customer_contact|', - 'size' => '70', - 'max_length' => '150' - ), - 'netops_contact' => array( - 'method' => 'textbox', - 'friendly_name' => __('NetOps Contact', 'mactrack'), - 'description' => __('Please principal network support contact name and number for this site.', 'mactrack'), - 'value' => '|arg1:netops_contact|', - 'size' => '70', - 'max_length' => '150' - ), - 'facilities_contact' => array( - 'method' => 'textbox', - 'friendly_name' => __('Facilities Contact', 'mactrack'), - 'description' => __('Please principal facilities/security contact name and number for this site.', 'mactrack'), - 'value' => '|arg1:facilities_contact|', - 'size' => '70', - 'max_length' => '150' - ), - 'site_info' => array( - 'method' => 'textarea', - 'friendly_name' => __('Site Information', 'mactrack'), - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'description' => __('Provide any site-specific information, in free form, that allows you to better manage this location.', 'mactrack'), - 'value' => '|arg1:site_info|', - 'max_length' => '255' - ), - 'skip_vlans' => array( - 'method' => 'textarea', - 'friendly_name' => 'VLAN ID to Skipped Scan', - 'class' => 'textAreaNotes', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - 'description' => 'A comma delimited list of VLAN ID always forced to be skipped scanning.', - 'value' => '|arg1:skip_vlans|', - 'max_length' => '1024' - ), - 'scan_vlans' => array( - 'method' => 'textarea', - 'friendly_name' => 'VLAN ID to Scan', - 'class' => 'textAreaNotes', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - 'description' => 'A comma delimited list of VLAN ID to be scanned', - 'value' => '|arg1:scan_vlans|', - 'max_length' => '1024' - ), - 'site_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:site_id|' - ), - '_site_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:site_id|' - ), - 'save_component_site' => array( - 'method' => 'hidden', - 'value' => '1' - ) - ); - - /* file: mactrack_macwatch.php, action: edit */ - $fields_mactrack_macw_edit = array( - 'spacer0' => array( - 'method' => 'spacer', - 'friendly_name' => __('General Mac Address Tracking Settings', 'mactrack') - ), - 'mac_address' => array( - 'method' => 'textbox', - 'friendly_name' => __('MAC Address', 'mactrack'), - 'description' => __('Please enter the MAC Address to be watched for.', 'mactrack'), - 'value' => '|arg1:mac_address|', - 'default' => '', - 'max_length' => '40' - ), - 'name' => array( - 'method' => 'textbox', - 'friendly_name' => __('MAC Tracking Name/Email Subject', 'mactrack'), - 'description' => __('Please enter a reasonable name for this MAC Tracking entry. This information will be in the subject line of your Email', 'mactrack'), - 'value' => '|arg1:name|', - 'size' => '70', - 'max_length' => '250' - ), - 'description' => array( - 'friendly_name' => __('MacWatch Default Body', 'mactrack'), - 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain any valid html tags. It also supports replacement tags that will be processed when sending an Email. Valid tags include , , , , , , , .', 'mactrack')), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:description|', - 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), - 'max_length' => '512', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - ), - 'ticket_number' => array( - 'method' => 'textbox', - 'friendly_name' => __('Ticket Number', 'mactrack'), - 'description' => __('Ticket number for cross referencing with your corporate help desk system(s).', 'mactrack'), - 'value' => '|arg1:ticket_number|', - 'size' => '70', - 'max_length' => '150' - ), - 'notify_schedule' => array( - 'method' => 'drop_array', - 'friendly_name' => __('Notification Schedule', 'mactrack'), - 'description' => __('Choose how often an Email should be generated for this Mac Watch item.', 'mactrack'), - 'value' => '|arg1:notify_schedule|', - 'default' => '1', - 'array' => array( - 1 => __('First Occurrence Only', 'mactrack'), - 2 => __('All Occurrences', 'mactrack'), - 60 => __('Every Hour', 'mactrack'), - 240 => __('Every %d Hours', 4, 'mactrack'), - 1800 => __('Every %d Hours', 12, 'mactrack'), - 3600 => __('Every Day', 'mactrack')) - ), - 'email_addresses' => array( - 'method' => 'textbox', - 'friendly_name' => __('Email Addresses', 'mactrack'), - 'description' => __('Enter a semicolon separated of Email addresses that will be notified where this MAC address is.', 'mactrack'), - 'value' => '|arg1:email_addresses|', - 'size' => '90', - 'max_length' => '255' - ), - 'mac_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|' - ), - '_mac_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|' - ), - 'save_component_macw' => array( - 'method' => 'hidden', - 'value' => '1' - ) - ); - - /* file: mactrack_macwatch.php, action: edit */ - $fields_mactrack_maca_edit = array( - 'spacer0' => array( - 'method' => 'spacer', - 'friendly_name' => __('General Mac Address Authorization Settings', 'mactrack') - ), - 'mac_address' => array( - 'method' => 'textbox', - 'friendly_name' => __('MAC Address Match', 'mactrack'), - 'description' => __('Please enter the MAC Address or Mac Address Match string to be automatically authorized. If you wish to authorize a group of MAC Addresses, you can use the wildcard character of \'%\' anywhere in the MAC Address.', 'mactrack'), - 'value' => '|arg1:mac_address|', - 'default' => '', - 'max_length' => '40' - ), - 'description' => array( - 'method' => 'textarea', - 'friendly_name' => __('Reason', 'mactrack'), - 'class' => 'textAreaNotes', - 'description' => __('Please add a reason for this entry.', 'mactrack'), - 'value' => '|arg1:description|', - 'textarea_rows' => '4', - 'textarea_cols' => '80' - ), - 'mac_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|' - ), - '_mac_id' => array( - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|' - ), - 'save_component_maca' => array( - 'method' => 'hidden', - 'value' => '1' - ) - ); +function mactrack_config_form() +{ + global $fields_mactrack_device_type_edit, $fields_mactrack_device_edit, $fields_mactrack_site_edit; + global $fields_mactrack_snmp_edit, $fields_mactrack_snmp_item, $fields_mactrack_snmp_item_edit; + global $mactrack_device_types, $snmp_versions, $fields_mactrack_macw_edit, $fields_mactrack_maca_edit; + global $snmp_priv_protocols, $snmp_auth_protocols; + + // file: mactrack_device_types.php, action: edit + $fields_mactrack_device_type_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('Device Scanning Function Options', 'mactrack'), + ], + 'description' => [ + 'method' => 'textbox', + 'friendly_name' => __('Description', 'mactrack'), + 'description' => __('Give this device type a meaningful description.', 'mactrack'), + 'value' => '|arg1:description|', + 'max_length' => '250', + ], + 'vendor' => [ + 'method' => 'textbox', + 'friendly_name' => __('Vendor', 'mactrack'), + 'description' => __('Fill in the name for the vendor of this device type.', 'mactrack'), + 'value' => '|arg1:vendor|', + 'max_length' => '250', + ], + 'device_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Device Type', 'mactrack'), + 'description' => __('Choose the type of device.', 'mactrack'), + 'value' => '|arg1:device_type|', + 'default' => 1, + 'array' => $mactrack_device_types, + ], + 'sysDescr_match' => [ + 'method' => 'textbox', + 'friendly_name' => __('System Description Match', 'mactrack'), + 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), + 'value' => '|arg1:sysDescr_match|', + 'max_length' => '250', + ], + 'sysObjectID_match' => [ + 'method' => 'textbox', + 'friendly_name' => __('Vendor SNMP Object ID Match', 'mactrack'), + 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), + 'value' => '|arg1:sysObjectID_match|', + 'max_length' => '250', + ], + 'scanning_function' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('MAC Address Scanning Function', 'mactrack'), + 'description' => __('Mactrack scanning function to call in order to obtain and store port details. The function name is all that is required. The following four parameters are assumed and will always be appended: \'my_function($site, &$device, $lowport, $highport)\'. There is no function required for a pure router.', 'mactrack'), + 'value' => '|arg1:scanning_function|', + 'default' => 0, + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select scanning_function as id, scanning_function as name from mac_track_scanning_functions where type="1" order by scanning_function', + ], + 'ip_scanning_function' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('IP Address Scanning Function', 'mactrack'), + 'description' => __('Mactrack scanning function specific to Layer3 devices that track IP Addresses.', 'mactrack'), + 'value' => '|arg1:ip_scanning_function|', + 'default' => 0, + 'none_value' => __('None', 'mactrack'), + 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="2" ORDER BY scanning_function', + ], + 'dot1x_scanning_function' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('802.1x Scanning Function', 'mactrack'), + 'description' => __('Mactrack scanning function specific to Switches with dot1x enabled.', 'mactrack'), + 'value' => '|arg1:dot1x_scanning_function|', + 'default' => '', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="3" ORDER BY scanning_function', + ], + 'serial_number_oid' => [ + 'method' => 'textbox', + 'friendly_name' => __('Serial Number Base OID', 'mactrack'), + 'description' => __('The SNMP OID used to obtain this device types serial number to be stored in the Mactrack Asset Information table.', 'mactrack'), + 'value' => '|arg1:serial_number_oid|', + 'max_length' => '100', + 'default' => '', + ], + 'serial_number_oid_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Serial Number Collection Method', 'mactrack'), + 'description' => __('How is the serial number collected for this OID. If \'SNMP Walk\', we assume multiple serial numbers. If \'Get\', it will be only one..', 'mactrack'), + 'value' => '|arg1:serial_number_oid_method|', + 'default' => 'get', + 'array' => ['get' => __('SNMP Get', 'mactrack'), 'walk' => __('SNMP Walk', 'mactrack')], + ], + 'lowPort' => [ + 'method' => 'textbox', + 'friendly_name' => __('Low User Port Number', 'mactrack'), + 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), + 'value' => '|arg1:lowPort|', + 'default' => read_config_option('mt_port_lowPort'), + 'max_length' => '100', + 'size' => '10', + ], + 'highPort' => [ + 'method' => 'textbox', + 'friendly_name' => __('High User Port Number', 'mactrack'), + 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), + 'value' => '|arg1:highPort|', + 'default' => read_config_option('mt_port_highPort'), + 'max_length' => '100', + 'size' => '10', + ], + 'disabled' => [ + 'method' => 'checkbox', + 'friendly_name' => __('Disabled', 'mactrack'), + 'description' => __('Disabled device type is not used.', 'mactrack'), + 'value' => '|arg1:disabled|', + 'default' => '', + ], + 'device_type_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_type_id|', + ], + '_device_type_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_type_id|', + ], + 'save_component_device_type' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_snmp.php, action: edit + $fields_mactrack_snmp_edit = [ + 'name' => [ + 'method' => 'textbox', + 'friendly_name' => __('Name', 'mactrack'), + 'description' => __('Fill in the name of this SNMP option set.', 'mactrack'), + 'value' => '|arg1:name|', + 'default' => '', + 'max_length' => '100', + 'size' => '40', + ], + ]; + + // file: mactrack_snmp.php, action: item_edit + $fields_mactrack_snmp_item = [ + 'snmp_version' => [ + 'method' => 'drop_array', + 'friendly_name' => __('SNMP Version', 'mactrack'), + 'description' => __('Choose the SNMP version for this host.', 'mactrack'), + 'value' => '|arg1:snmp_version|', + 'default' => read_config_option('mt_snmp_ver'), + 'array' => $snmp_versions, + ], + 'snmp_readstring' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Community String', 'mactrack'), + 'description' => __('Fill in the SNMP read community for this device.', 'mactrack'), + 'value' => '|arg1:snmp_readstring|', + 'default' => read_config_option('mt_snmp_community'), + 'max_length' => '100', + 'size' => '20', + ], + 'snmp_port' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Port', 'mactrack'), + 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), + 'value' => '|arg1:snmp_port|', + 'max_length' => '8', + 'default' => read_config_option('mt_snmp_port'), + 'size' => '10', + ], + 'snmp_timeout' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Timeout', 'mactrack'), + 'description' => __('The maximum number of milliseconds Cacti will wait for an SNMP response (does not work with php-snmp support).', 'mactrack'), + 'value' => '|arg1:snmp_timeout|', + 'max_length' => '8', + 'default' => read_config_option('mt_snmp_timeout'), + 'size' => '10', + ], + 'snmp_retries' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Retries', 'mactrack'), + 'description' => __('The maximum number of attempts to reach a device via an SNMP readstring prior to giving up.', 'mactrack'), + 'value' => '|arg1:snmp_retries|', + 'max_length' => '8', + 'default' => read_config_option('mt_snmp_retries'), + 'size' => '10', + ], + 'max_oids' => [ + 'method' => 'textbox', + 'friendly_name' => __('Maximum OID\'s Per Get Request', 'mactrack'), + 'description' => __('Specified the number of OID\'s that can be obtained in a single SNMP Get request.', 'mactrack'), + 'value' => '|arg1:max_oids|', + 'max_length' => '8', + 'default' => read_config_option('max_get_size'), + 'size' => '15', + ], + 'snmp_username' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Username (v3)', 'mactrack'), + 'description' => __('SNMP v3 username for this device.', 'mactrack'), + 'value' => '|arg1:snmp_username|', + 'default' => read_config_option('snmp_username'), + 'max_length' => '50', + 'size' => '15', + ], + 'snmp_password' => [ + 'method' => 'textbox_password', + 'friendly_name' => __('SNMP Password (v3)', 'mactrack'), + 'description' => __('SNMP v3 password for this device.', 'mactrack'), + 'value' => '|arg1:snmp_password|', + 'default' => read_config_option('snmp_password'), + 'max_length' => '50', + 'size' => '15', + ], + 'snmp_auth_protocol' => [ + 'method' => 'drop_array', + 'friendly_name' => __('SNMP Auth Protocol (v3)', 'mactrack'), + 'description' => __('Choose the SNMPv3 Authorization Protocol.', 'mactrack'), + 'value' => '|arg1:snmp_auth_protocol|', + 'default' => read_config_option('snmp_auth_protocol'), + 'array' => $snmp_auth_protocols, + ], + 'snmp_priv_passphrase' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Privacy Passphrase (v3)', 'mactrack'), + 'description' => __('Choose the SNMPv3 Privacy Passphrase.', 'mactrack'), + 'value' => '|arg1:snmp_priv_passphrase|', + 'default' => read_config_option('snmp_priv_passphrase'), + 'max_length' => '200', + 'size' => '40', + ], + 'snmp_priv_protocol' => [ + 'method' => 'drop_array', + 'friendly_name' => __('SNMP Privacy Protocol (v3)', 'mactrack'), + 'description' => __('Choose the SNMPv3 Privacy Protocol.', 'mactrack'), + 'value' => '|arg1:snmp_priv_protocol|', + 'default' => read_config_option('snmp_priv_protocol'), + 'array' => $snmp_priv_protocols, + ], + 'snmp_context' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Context (v3)', 'mactrack'), + 'description' => __('Enter the SNMP v3 Context to use for this device.', 'mactrack'), + 'value' => '|arg1:snmp_context|', + 'default' => '', + 'max_length' => '64', + 'size' => '40', + ], + 'snmp_engine_id' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Engine ID (v3)', 'mactrack'), + 'description' => __('Enter the SNMP v3 Engine ID to use for this device.', 'mactrack'), + 'value' => '|arg1:snmp_engine_id|', + 'default' => '', + 'max_length' => '64', + 'size' => '40', + ], + ]; + + // file: mactrack_devices.php, action: edit + $fields_mactrack_device_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Device Settings', 'mactrack'), + ], + 'device_name' => [ + 'method' => 'textbox', + 'friendly_name' => __('Device Name', 'mactrack'), + 'description' => __('Give this device a meaningful name.', 'mactrack'), + 'value' => '|arg1:device_name|', + 'max_length' => '250', + ], + 'hostname' => [ + 'method' => 'textbox', + 'friendly_name' => __('Hostname', 'mactrack'), + 'description' => __('Fill in the fully qualified hostname for this device.', 'mactrack'), + 'value' => '|arg1:hostname|', + 'max_length' => '250', + ], + 'host_id' => [ + 'friendly_name' => __('Related Cacti Host', 'mactrack'), + 'description' => __('Given Mactrack Host is connected to this Cacti Host.', 'mactrack'), + // 'method' => 'view', + 'method' => 'drop_sql', + 'value' => '|arg1:host_id|', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select id,CONCAT_WS("",description," (",hostname,")") as name from host order by description,hostname', + ], + 'device_type_id' => [ + 'method' => 'drop_sql', + 'friendly_name' => 'Device Type', + 'description' => 'Choose the type of device.', + 'value' => '|arg1:device_type_id|', + 'default' => 0, + 'none_value' => 'Not Detected', + 'sql' => 'select device_type_id as id,description as name from mac_track_device_types order by description', + ], + 'scan_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Scan Type', 'mactrack'), + 'description' => __('Choose the scan type you wish to perform on this device.', 'mactrack'), + 'value' => '|arg1:scan_type|', + 'default' => 1, + 'array' => $mactrack_device_types, + ], + 'site_id' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('Site Name', 'mactrack'), + 'description' => __('Choose the site to associate with this device.', 'mactrack'), + 'value' => '|arg1:site_id|', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select site_id as id,site_name as name from mac_track_sites order by name', + ], + 'notes' => [ + 'method' => 'textarea', + 'friendly_name' => __('Device Notes', 'mactrack'), + 'description' => __('This field value is useful to save general information about a specific device.', 'mactrack'), + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'value' => '|arg1:notes|', + 'max_length' => '255', + ], + 'disabled' => [ + 'method' => 'checkbox', + 'friendly_name' => __('Disable Device', 'mactrack'), + 'description' => __('Check this box to disable all checks for this host.', 'mactrack'), + 'value' => '|arg1:disabled|', + 'default' => '', + 'form_id' => false, + ], + 'spacer1' => [ + 'method' => 'spacer', + 'friendly_name' => __('Switch/Hub, Switch/Router Settings', 'mactrack'), + ], + 'ignorePorts' => [ + 'method' => 'textarea', + 'friendly_name' => __('Ports to Ignore', 'mactrack'), + 'description' => __('Provide a list of ports on a specific switch/hub whose MAC results should be ignored. Ports such as link/trunk ports that can not be distinguished from other user ports are examples. Each port number must be separated by a colon, pipe, or a space \':\', \'|\', \' \'. For example, \'Fa0/1: Fa1/23\' or \'Fa0/1 Fa1/23\' would be acceptable for some manufacturers switch types.', 'mactrack'), + 'value' => '|arg1:ignorePorts|', + 'default' => '', + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'max_length' => '255', + ], + 'scan_trunk_port' => [ + 'method' => 'textarea', + 'friendly_name' => 'Trunk Ports to Scan', + 'description' => 'A comma delimited list of Port Number to be scanned. Some VMware network port will be configured with 802.1Q', + 'value' => '|arg1:scan_trunk_port|', + 'default' => '', + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'max_length' => '255', + ], + 'spacer2' => [ + 'method' => 'spacer', + 'friendly_name' => __('SNMP Options', 'mactrack'), + ], + 'snmp_options' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('SNMP Options', 'mactrack'), + 'description' => __('You can use specific SNMP settings or select SNMP set. In the second case, mactrack tries to find correct settings from SNMP set', 'mactrack'), + 'value' => '|arg1:snmp_options|', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select * from mac_track_snmp order by name', + ], + 'snmp_readstrings' => [ + 'method' => 'view', + 'friendly_name' => __('Read Strings', 'mactrack'), + 'description' => __('DEPRECATED: SNMP community strings', 'mactrack'), + 'value' => '|arg1:snmp_readstrings|', + ], + 'spacer3' => [ + 'method' => 'spacer', + 'friendly_name' => __('Specific SNMP Settings', 'mactrack'), + ], + ]; + + $fields_mactrack_device_edit += $fields_mactrack_snmp_item; + + $fields_mactrack_device_edit += [ + 'spacer4' => [ + 'method' => 'spacer', + 'friendly_name' => __('Connectivity Options', 'mactrack'), + ], + 'term_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Terminal Type', 'mactrack'), + 'description' => __('Choose the terminal type that you use to connect to this device.', 'mactrack'), + 'value' => '|arg1:term_type|', + 'default' => 1, + 'array' => [ + 0 => __('None', 'mactrack'), + 1 => __('Telnet', 'mactrack'), + 2 => __('SSH', 'mactrack'), + 3 => __('HTTP', 'mactrack'), + 4 => __('HTTPS', 'mactrack')], + ], + 'user_name' => [ + 'method' => 'textbox', + 'friendly_name' => __('User Name', 'mactrack'), + 'description' => __('The user name to be used for your custom authentication method. Examples include SSH, RSH, HTML, etc.', 'mactrack'), + 'value' => '|arg1:user_name|', + 'default' => '', + 'max_length' => '40', + 'size' => '20', + ], + 'user_password' => [ + 'method' => 'textbox_password', + 'friendly_name' => __('Password', 'mactrack'), + 'description' => __('The password to be used for your custom authentication.', 'mactrack'), + 'value' => '|arg1:user_password|', + 'default' => '', + 'max_length' => '40', + 'size' => '20', + ], + 'private_key_path' => [ + 'method' => 'filepath', + 'friendly_name' => __('Private Key Path', 'mactrack'), + 'description' => __('The path to the private key used for SSH authentication.', 'mactrack'), + 'value' => '|arg1:private_key_path|', + 'default' => '', + 'max_length' => '128', + 'size' => '40', + ], + 'device_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_id|', + ], + '_device_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_id|', + ], + 'save_component_device' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_snmp.php, action: item_edit + $fields_mactrack_snmp_item_edit = $fields_mactrack_snmp_item + [ + 'sequence' => [ + 'method' => 'view', + 'friendly_name' => __('Sequence', 'mactrack'), + 'description' => __('Sequence of Item.', 'mactrack'), + 'value' => '|arg1:sequence|'], + ]; + + // file: mactrack_sites.php, action: edit + $fields_mactrack_site_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Site Settings', 'mactrack'), + ], + 'site_name' => [ + 'method' => 'textbox', + 'friendly_name' => __('Site Name', 'mactrack'), + 'description' => __('Please enter a reasonable name for this site.', 'mactrack'), + 'value' => '|arg1:site_name|', + 'size' => '70', + 'max_length' => '250', + ], + 'customer_contact' => [ + 'method' => 'textbox', + 'friendly_name' => __('Primary Customer Contact', 'mactrack'), + 'description' => __('The principal customer contact name and number for this site.', 'mactrack'), + 'value' => '|arg1:customer_contact|', + 'size' => '70', + 'max_length' => '150', + ], + 'netops_contact' => [ + 'method' => 'textbox', + 'friendly_name' => __('NetOps Contact', 'mactrack'), + 'description' => __('Please principal network support contact name and number for this site.', 'mactrack'), + 'value' => '|arg1:netops_contact|', + 'size' => '70', + 'max_length' => '150', + ], + 'facilities_contact' => [ + 'method' => 'textbox', + 'friendly_name' => __('Facilities Contact', 'mactrack'), + 'description' => __('Please principal facilities/security contact name and number for this site.', 'mactrack'), + 'value' => '|arg1:facilities_contact|', + 'size' => '70', + 'max_length' => '150', + ], + 'site_info' => [ + 'method' => 'textarea', + 'friendly_name' => __('Site Information', 'mactrack'), + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'description' => __('Provide any site-specific information, in free form, that allows you to better manage this location.', 'mactrack'), + 'value' => '|arg1:site_info|', + 'max_length' => '255', + ], + 'skip_vlans' => [ + 'method' => 'textarea', + 'friendly_name' => 'VLAN ID to Skipped Scan', + 'class' => 'textAreaNotes', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + 'description' => 'A comma delimited list of VLAN ID always forced to be skipped scanning.', + 'value' => '|arg1:skip_vlans|', + 'max_length' => '1024', + ], + 'scan_vlans' => [ + 'method' => 'textarea', + 'friendly_name' => 'VLAN ID to Scan', + 'class' => 'textAreaNotes', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + 'description' => 'A comma delimited list of VLAN ID to be scanned', + 'value' => '|arg1:scan_vlans|', + 'max_length' => '1024', + ], + 'site_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:site_id|', + ], + '_site_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:site_id|', + ], + 'save_component_site' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_macwatch.php, action: edit + $fields_mactrack_macw_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Mac Address Tracking Settings', 'mactrack'), + ], + 'mac_address' => [ + 'method' => 'textbox', + 'friendly_name' => __('MAC Address', 'mactrack'), + 'description' => __('Please enter the MAC Address to be watched for.', 'mactrack'), + 'value' => '|arg1:mac_address|', + 'default' => '', + 'max_length' => '40', + ], + 'name' => [ + 'method' => 'textbox', + 'friendly_name' => __('MAC Tracking Name/Email Subject', 'mactrack'), + 'description' => __('Please enter a reasonable name for this MAC Tracking entry. This information will be in the subject line of your Email', 'mactrack'), + 'value' => '|arg1:name|', + 'size' => '70', + 'max_length' => '250', + ], + 'description' => [ + 'friendly_name' => __('MacWatch Default Body', 'mactrack'), + 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain any valid html tags. It also supports replacement tags that will be processed when sending an Email. Valid tags include , , , , , , , .', 'mactrack')), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:description|', + 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), + 'max_length' => '512', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + ], + 'ticket_number' => [ + 'method' => 'textbox', + 'friendly_name' => __('Ticket Number', 'mactrack'), + 'description' => __('Ticket number for cross referencing with your corporate help desk system(s).', 'mactrack'), + 'value' => '|arg1:ticket_number|', + 'size' => '70', + 'max_length' => '150', + ], + 'notify_schedule' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Notification Schedule', 'mactrack'), + 'description' => __('Choose how often an Email should be generated for this Mac Watch item.', 'mactrack'), + 'value' => '|arg1:notify_schedule|', + 'default' => '1', + 'array' => [ + 1 => __('First Occurrence Only', 'mactrack'), + 2 => __('All Occurrences', 'mactrack'), + 60 => __('Every Hour', 'mactrack'), + 240 => __('Every %d Hours', 4, 'mactrack'), + 1800 => __('Every %d Hours', 12, 'mactrack'), + 3600 => __('Every Day', 'mactrack')], + ], + 'email_addresses' => [ + 'method' => 'textbox', + 'friendly_name' => __('Email Addresses', 'mactrack'), + 'description' => __('Enter a semicolon separated of Email addresses that will be notified where this MAC address is.', 'mactrack'), + 'value' => '|arg1:email_addresses|', + 'size' => '90', + 'max_length' => '255', + ], + 'mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + '_mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + 'save_component_macw' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_macwatch.php, action: edit + $fields_mactrack_maca_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Mac Address Authorization Settings', 'mactrack'), + ], + 'mac_address' => [ + 'method' => 'textbox', + 'friendly_name' => __('MAC Address Match', 'mactrack'), + 'description' => __('Please enter the MAC Address or Mac Address Match string to be automatically authorized. If you wish to authorize a group of MAC Addresses, you can use the wildcard character of \'%\' anywhere in the MAC Address.', 'mactrack'), + 'value' => '|arg1:mac_address|', + 'default' => '', + 'max_length' => '40', + ], + 'description' => [ + 'method' => 'textarea', + 'friendly_name' => __('Reason', 'mactrack'), + 'class' => 'textAreaNotes', + 'description' => __('Please add a reason for this entry.', 'mactrack'), + 'value' => '|arg1:description|', + 'textarea_rows' => '4', + 'textarea_cols' => '80', + ], + 'mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + '_mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + 'save_component_maca' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; } -function convert_readstrings() { - global $config; - - $sql = 'SELECT DISTINCT ' . - 'snmp_readstrings, ' . - 'snmp_version, ' . - 'snmp_port, ' . - 'snmp_timeout, ' . - 'snmp_retries ' . - 'FROM mac_track_devices'; - - $devices = db_fetch_assoc($sql); - - if (cacti_sizeof($devices)) { - $i = 0; - foreach($devices as $device) { - # create new SNMP Option Set - unset($save); - $save['id'] = 0; - $save['name'] = 'Custom_' . $i++; - $snmp_id = sql_save($save, 'mac_track_snmp'); - - # add each single option derived from readstrings - $read_strings = explode(':',$device['snmp_readstrings']); - if (cacti_sizeof($read_strings)) { - foreach($read_strings as $snmp_readstring) { - unset($save); - $save['id'] = 0; - $save['snmp_id'] = $snmp_id; - $save['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id=' . $snmp_id); - - $save['snmp_readstring'] = $snmp_readstring; - $save['snmp_version'] = $device['snmp_version']; - $save['snmp_port'] = $device['snmp_port']; - $save['snmp_timeout'] = $device['snmp_timeout']; - $save['snmp_retries'] = $device['snmp_retries']; - $save['snmp_username'] = ''; - $save['snmp_password'] = ''; - $save['snmp_auth_protocol'] = ''; - $save['snmp_priv_passphrase'] = ''; - $save['snmp_priv_protocol'] = ''; - $save['snmp_context'] = ''; - $save['snmp_engine_id'] = ''; - $save['max_oids'] = ''; - - $item_id = sql_save($save, 'mac_track_snmp_items'); - } - } # each readstring added as SNMP Option item - - # now, let's find all devices, that used this snmp_readstrings - $sql = 'UPDATE mac_track_devices SET snmp_options=' . $snmp_id . - " WHERE snmp_readstrings='" . $device['snmp_readstrings'] . - "' AND snmp_version=" . $device['snmp_version'] . - ' AND snmp_port=' . $device['snmp_port'] . - ' AND snmp_timeout=' . $device['snmp_timeout'] . - ' AND snmp_retries=' . $device['snmp_retries']; - - $ok = db_execute($sql); - } - } - db_execute("REPLACE INTO settings (name,value) VALUES ('mt_convert_readstrings', 'on')"); - # we keep the field:snmp_readstrings in mac_track_devices, it should be deprecated first - # next mactrack release may delete that field, then +function convert_readstrings() +{ + global $config; + + $sql = 'SELECT DISTINCT ' + .'snmp_readstrings, ' + .'snmp_version, ' + .'snmp_port, ' + .'snmp_timeout, ' + .'snmp_retries ' + .'FROM mac_track_devices'; + + $devices = db_fetch_assoc($sql); + + if (cacti_sizeof($devices)) { + $i = 0; + foreach ($devices as $device) { + // create new SNMP Option Set + unset($save); + $save['id'] = 0; + $save['name'] = 'Custom_'.$i++; + $snmp_id = sql_save($save, 'mac_track_snmp'); + + // add each single option derived from readstrings + $read_strings = explode(':', $device['snmp_readstrings']); + if (cacti_sizeof($read_strings)) { + foreach ($read_strings as $snmp_readstring) { + unset($save); + $save['id'] = 0; + $save['snmp_id'] = $snmp_id; + $save['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id='.$snmp_id); + + $save['snmp_readstring'] = $snmp_readstring; + $save['snmp_version'] = $device['snmp_version']; + $save['snmp_port'] = $device['snmp_port']; + $save['snmp_timeout'] = $device['snmp_timeout']; + $save['snmp_retries'] = $device['snmp_retries']; + $save['snmp_username'] = ''; + $save['snmp_password'] = ''; + $save['snmp_auth_protocol'] = ''; + $save['snmp_priv_passphrase'] = ''; + $save['snmp_priv_protocol'] = ''; + $save['snmp_context'] = ''; + $save['snmp_engine_id'] = ''; + $save['max_oids'] = ''; + + $item_id = sql_save($save, 'mac_track_snmp_items'); + } + } // each readstring added as SNMP Option item + + // now, let's find all devices, that used this snmp_readstrings + $sql = 'UPDATE mac_track_devices SET snmp_options='.$snmp_id + ." WHERE snmp_readstrings='".$device['snmp_readstrings'] + ."' AND snmp_version=".$device['snmp_version'] + .' AND snmp_port='.$device['snmp_port'] + .' AND snmp_timeout='.$device['snmp_timeout'] + .' AND snmp_retries='.$device['snmp_retries']; + + $ok = db_execute($sql); + } + } + db_execute("REPLACE INTO settings (name,value) VALUES ('mt_convert_readstrings', 'on')"); + // we keep the field:snmp_readstrings in mac_track_devices, it should be deprecated first + // next mactrack release may delete that field, then } From 318c54019f071bcb74bdafc76d809ab596aac9f8 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:20:21 -0500 Subject: [PATCH 10/18] Update plugin-ci-workflow.yml --- .github/workflows/plugin-ci-workflow.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 728eee21..302b1531 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -66,7 +66,7 @@ jobs: repository: Cacti/cacti path: cacti - - name: Checkout mactrack Plugin + - name: Checkout MacTrack Plugin uses: actions/checkout@v4 with: path: cacti/plugins/mactrack @@ -128,7 +128,7 @@ jobs: run: | cd ${{ github.workspace }}/cacti if [ -f composer.json ]; then - sudo composer install --dev --no-progress + sudo composer install --prefer-dist --no-progress fi - name: Create Cacti config.php @@ -165,7 +165,7 @@ jobs: cd ${{ github.workspace }}/cacti sudo php cli/install_cacti.php --accept-eula --install --force - - name: Install mactrack Plugin + - name: Install MacTrack Plugin run: | cd ${{ github.workspace }}/cacti sudo php cli/plugin_manage.php --plugin=mactrack --install --enable @@ -206,7 +206,7 @@ jobs: cat log/cacti.log exit 1 fi - + - name: View Cacti Logs if: always() run: | From 1bda81f06bf9f5deb2ec785ca149b4a9ab98a038 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:21:29 -0500 Subject: [PATCH 11/18] Update plugin-ci-workflow.yml --- .github/workflows/plugin-ci-workflow.yml | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 2258bc54..302b1531 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -106,14 +106,16 @@ jobs: cat ~/.my.cnf - name: Initialize Cacti Database + env: + MYSQL_AUTH_USR: '--defaults-file=~/.my.cnf' run: | - mysql --defaults-file="$HOME/.my.cnf" -e 'CREATE DATABASE IF NOT EXISTS cacti;' - mysql --defaults-file="$HOME/.my.cnf" -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" - mysql --defaults-file="$HOME/.my.cnf" -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" - mysql --defaults-file="$HOME/.my.cnf" -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" - mysql --defaults-file="$HOME/.my.cnf" -e "FLUSH PRIVILEGES;" - mysql --defaults-file="$HOME/.my.cnf" cacti < ${{ github.workspace }}/cacti/cacti.sql - mysql --defaults-file="$HOME/.my.cnf" -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti + mysql $MYSQL_AUTH_USR -e 'CREATE DATABASE IF NOT EXISTS cacti;' + mysql $MYSQL_AUTH_USR -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" + mysql $MYSQL_AUTH_USR -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "FLUSH PRIVILEGES;" + mysql $MYSQL_AUTH_USR cacti < ${{ github.workspace }}/cacti/cacti.sql + mysql $MYSQL_AUTH_USR -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti - name: Validate composer files run: | @@ -180,6 +182,9 @@ jobs: run: sed '/plugins/d' -i .phpstan.neon working-directory: ${{ github.workspace }}/cacti + - name: Mark composer scripts executable + run: sudo chmod +x ${{ github.workspace }}/cacti/include/vendor/bin/* + - name: Run Linter on base code run: composer run-script lint ${{ github.workspace }}/cacti/plugins/mactrack working-directory: ${{ github.workspace }}/cacti From c4649379a031aba79e5a7a8c35a0d031ead622d3 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:26:54 -0500 Subject: [PATCH 12/18] update gitignoe --- .gitignore | 4 +- composer.json | 14 - composer.lock | 2686 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 2687 insertions(+), 17 deletions(-) delete mode 100644 composer.json create mode 100644 composer.lock diff --git a/.gitignore b/.gitignore index c1dee42d..43677ddf 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,4 @@ # +-------------------------------------------------------------------------+ locales/po/*.mo -vendor/ -composer.lock -composer.phar \ No newline at end of file +vendor/ \ No newline at end of file diff --git a/composer.json b/composer.json deleted file mode 100644 index 5b559865..00000000 --- a/composer.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "cacti/plugin-mactrack", - "description": "MacTrack plugin for Cacti - helper composer file for tooling", - "type": "library", - "require": {}, - "require-dev": { - "friendsofphp/php-cs-fixer": "^3.0" - }, - "scripts": { - "phpcsfixer": "vendor/bin/php-cs-fixer fix" - }, - "minimum-stability": "stable", - "prefer-stable": true -} diff --git a/composer.lock b/composer.lock new file mode 100644 index 00000000..d9a43ed4 --- /dev/null +++ b/composer.lock @@ -0,0 +1,2686 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "9555d003bb68593947d0fedbd916fa18", + "packages": [], + "packages-dev": [ + { + "name": "clue/ndjson-react", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/clue/reactphp-ndjson.git", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/reactphp-ndjson/zipball/392dc165fce93b5bb5c637b67e59619223c931b0", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react/stream": "^1.2" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react/event-loop": "^1.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Clue\\React\\NDJson\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.", + "homepage": "https://github.com/clue/reactphp-ndjson", + "keywords": [ + "NDJSON", + "json", + "jsonlines", + "newline", + "reactphp", + "streaming" + ], + "support": { + "issues": "https://github.com/clue/reactphp-ndjson/issues", + "source": "https://github.com/clue/reactphp-ndjson/tree/v1.3.0" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "time": "2022-12-23T10:58:28+00:00" + }, + { + "name": "composer/pcre", + "version": "3.3.2", + "source": { + "type": "git", + "url": "https://github.com/composer/pcre.git", + "reference": "b2bed4734f0cc156ee1fe9c0da2550420d99a21e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/pcre/zipball/b2bed4734f0cc156ee1fe9c0da2550420d99a21e", + "reference": "b2bed4734f0cc156ee1fe9c0da2550420d99a21e", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<1.11.10" + }, + "require-dev": { + "phpstan/phpstan": "^1.12 || ^2", + "phpstan/phpstan-strict-rules": "^1 || ^2", + "phpunit/phpunit": "^8 || ^9" + }, + "type": "library", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + }, + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https://github.com/composer/pcre/issues", + "source": "https://github.com/composer/pcre/tree/3.3.2" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2024-11-12T16:29:46+00:00" + }, + { + "name": "composer/semver", + "version": "3.4.4", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.4" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "time": "2025-08-20T19:15:30+00:00" + }, + { + "name": "composer/xdebug-handler", + "version": "3.0.5", + "source": { + "type": "git", + "url": "https://github.com/composer/xdebug-handler.git", + "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/6c1925561632e83d60a44492e0b344cf48ab85ef", + "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef", + "shasum": "" + }, + "require": { + "composer/pcre": "^1 || ^2 || ^3", + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "phpunit/phpunit": "^8.5 || ^9.6 || ^10.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "description": "Restarts a process without Xdebug.", + "keywords": [ + "Xdebug", + "performance" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/xdebug-handler/issues", + "source": "https://github.com/composer/xdebug-handler/tree/3.0.5" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2024-05-06T16:37:16+00:00" + }, + { + "name": "evenement/evenement", + "version": "v3.0.2", + "source": { + "type": "git", + "url": "https://github.com/igorw/evenement.git", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/igorw/evenement/zipball/0a16b0d71ab13284339abb99d9d2bd813640efbc", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc", + "shasum": "" + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^9 || ^6" + }, + "type": "library", + "autoload": { + "psr-4": { + "Evenement\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "support": { + "issues": "https://github.com/igorw/evenement/issues", + "source": "https://github.com/igorw/evenement/tree/v3.0.2" + }, + "time": "2023-08-08T05:53:35+00:00" + }, + { + "name": "fidry/cpu-core-counter", + "version": "1.3.0", + "source": { + "type": "git", + "url": "https://github.com/theofidry/cpu-core-counter.git", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/db9508f7b1474469d9d3c53b86f817e344732678", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry/makefile": "^0.2.0", + "fidry/php-cs-fixer-config": "^1.1.2", + "phpstan/extension-installer": "^1.2.0", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-deprecation-rules": "^2.0.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^8.5.31 || ^9.5.26", + "webmozarts/strict-phpunit": "^7.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Fidry\\CpuCoreCounter\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "description": "Tiny utility to get the number of CPU cores.", + "keywords": [ + "CPU", + "core" + ], + "support": { + "issues": "https://github.com/theofidry/cpu-core-counter/issues", + "source": "https://github.com/theofidry/cpu-core-counter/tree/1.3.0" + }, + "funding": [ + { + "url": "https://github.com/theofidry", + "type": "github" + } + ], + "time": "2025-08-14T07:29:31+00:00" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v3.94.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", + "reference": "883b20fb38c7866de9844ab6d0a205c423bde2d4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/883b20fb38c7866de9844ab6d0a205c423bde2d4", + "reference": "883b20fb38c7866de9844ab6d0a205c423bde2d4", + "shasum": "" + }, + "require": { + "clue/ndjson-react": "^1.3", + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.5", + "ext-filter": "*", + "ext-hash": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "fidry/cpu-core-counter": "^1.3", + "php": "^7.4 || ^8.0", + "react/child-process": "^0.6.6", + "react/event-loop": "^1.5", + "react/socket": "^1.16", + "react/stream": "^1.4", + "sebastian/diff": "^4.0.6 || ^5.1.1 || ^6.0.2 || ^7.0 || ^8.0", + "symfony/console": "^5.4.47 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/event-dispatcher": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/filesystem": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/finder": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/options-resolver": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/polyfill-mbstring": "^1.33", + "symfony/polyfill-php80": "^1.33", + "symfony/polyfill-php81": "^1.33", + "symfony/polyfill-php84": "^1.33", + "symfony/process": "^5.4.47 || ^6.4.24 || ^7.2 || ^8.0", + "symfony/stopwatch": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3.1 || ^2.7.1", + "infection/infection": "^0.32.3", + "justinrainbow/json-schema": "^6.6.4", + "keradus/cli-executor": "^2.3", + "mikey179/vfsstream": "^1.6.12", + "php-coveralls/php-coveralls": "^2.9.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.7", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.7", + "phpunit/phpunit": "^9.6.34 || ^10.5.63 || ^11.5.51", + "symfony/polyfill-php85": "^1.33", + "symfony/var-dumper": "^5.4.48 || ^6.4.32 || ^7.4.4 || ^8.0.4", + "symfony/yaml": "^5.4.45 || ^6.4.30 || ^7.4.1 || ^8.0.1" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + }, + "exclude-from-classmap": [ + "src/**/Internal/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "keywords": [ + "Static code analysis", + "fixer", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.94.0" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "time": "2026-02-11T16:44:33+00:00" + }, + { + "name": "psr/container", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "time": "2021-11-05T16:47:00+00:00" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "time": "2019-01-08T18:20:26+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "react/cache", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/cache.git", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/cache/zipball/d47c472b64aa5608225f47965a484b75c7817d5b", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/cache/issues", + "source": "https://github.com/reactphp/cache/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2022-11-30T15:59:55+00:00" + }, + { + "name": "react/child-process", + "version": "v0.6.7", + "source": { + "type": "git", + "url": "https://github.com/reactphp/child-process.git", + "reference": "970f0e71945556422ee4570ccbabaedc3cf04ad3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/child-process/zipball/970f0e71945556422ee4570ccbabaedc3cf04ad3", + "reference": "970f0e71945556422ee4570ccbabaedc3cf04ad3", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/event-loop": "^1.2", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/socket": "^1.16", + "sebastian/environment": "^5.0 || ^3.0 || ^2.0 || ^1.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\ChildProcess\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven library for executing child processes with ReactPHP.", + "keywords": [ + "event-driven", + "process", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/child-process/issues", + "source": "https://github.com/reactphp/child-process/tree/v0.6.7" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-12-23T15:25:20+00:00" + }, + { + "name": "react/dns", + "version": "v1.14.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/dns.git", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/dns/zipball/7562c05391f42701c1fccf189c8225fece1cd7c3", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3 || ^2", + "react/promise-timer": "^1.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Dns\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "async", + "dns", + "dns-resolver", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/dns/issues", + "source": "https://github.com/reactphp/dns/tree/v1.14.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-18T19:34:28+00:00" + }, + { + "name": "react/event-loop", + "version": "v1.6.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/event-loop.git", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/event-loop/zipball/ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": [ + "asynchronous", + "event-loop" + ], + "support": { + "issues": "https://github.com/reactphp/event-loop/issues", + "source": "https://github.com/reactphp/event-loop/tree/v1.6.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-17T20:46:25+00:00" + }, + { + "name": "react/promise", + "version": "v3.3.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise.git", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise/zipball/23444f53a813a3296c1368bb104793ce8d88f04a", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a", + "shasum": "" + }, + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan/phpstan": "1.12.28 || 1.4.10", + "phpunit/phpunit": "^9.6 || ^7.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "React\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "keywords": [ + "promise", + "promises" + ], + "support": { + "issues": "https://github.com/reactphp/promise/issues", + "source": "https://github.com/reactphp/promise/tree/v3.3.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-08-19T18:57:03+00:00" + }, + { + "name": "react/socket", + "version": "v1.17.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/socket.git", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/socket/zipball/ef5b17b81f6f60504c539313f94f2d826c5faa08", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/dns": "^1.13", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.6 || ^1.2.1", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3.3 || ^2", + "react/promise-stream": "^1.4", + "react/promise-timer": "^1.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Socket\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "Connection", + "Socket", + "async", + "reactphp", + "stream" + ], + "support": { + "issues": "https://github.com/reactphp/socket/issues", + "source": "https://github.com/reactphp/socket/tree/v1.17.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-19T20:47:34+00:00" + }, + { + "name": "react/stream", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/stream.git", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/stream/zipball/1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.8", + "react/event-loop": "^1.2" + }, + "require-dev": { + "clue/stream-filter": "~1.2", + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Stream\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": [ + "event-driven", + "io", + "non-blocking", + "pipe", + "reactphp", + "readable", + "stream", + "writable" + ], + "support": { + "issues": "https://github.com/reactphp/stream/issues", + "source": "https://github.com/reactphp/stream/tree/v1.4.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2024-06-11T12:45:25+00:00" + }, + { + "name": "sebastian/diff", + "version": "7.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "7ab1ea946c012266ca32390913653d844ecd085f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/7ab1ea946c012266ca32390913653d844ecd085f", + "reference": "7ab1ea946c012266ca32390913653d844ecd085f", + "shasum": "" + }, + "require": { + "php": ">=8.3" + }, + "require-dev": { + "phpunit/phpunit": "^12.0", + "symfony/process": "^7.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/7.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-02-07T04:55:46+00:00" + }, + { + "name": "symfony/console", + "version": "v7.4.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "41e38717ac1dd7a46b6bda7d6a82af2d98a78894" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/41e38717ac1dd7a46b6bda7d6a82af2d98a78894", + "reference": "41e38717ac1dd7a46b6bda7d6a82af2d98a78894", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^7.2|^8.0" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/dotenv": "<6.4", + "symfony/event-dispatcher": "<6.4", + "symfony/lock": "<6.4", + "symfony/process": "<6.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0|^8.0", + "symfony/dependency-injection": "^6.4|^7.0|^8.0", + "symfony/event-dispatcher": "^6.4|^7.0|^8.0", + "symfony/http-foundation": "^6.4|^7.0|^8.0", + "symfony/http-kernel": "^6.4|^7.0|^8.0", + "symfony/lock": "^6.4|^7.0|^8.0", + "symfony/messenger": "^6.4|^7.0|^8.0", + "symfony/process": "^6.4|^7.0|^8.0", + "symfony/stopwatch": "^6.4|^7.0|^8.0", + "symfony/var-dumper": "^6.4|^7.0|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v7.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-01-13T11:36:38+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.6.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/63afe740e99a13ba87ec199bb07bbdee937a5b62", + "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.6-dev" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.6.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:21:43+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v7.4.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "dc2c0eba1af673e736bb851d747d266108aea746" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/dc2c0eba1af673e736bb851d747d266108aea746", + "reference": "dc2c0eba1af673e736bb851d747d266108aea746", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0|^8.0", + "symfony/dependency-injection": "^6.4|^7.0|^8.0", + "symfony/error-handler": "^6.4|^7.0|^8.0", + "symfony/expression-language": "^6.4|^7.0|^8.0", + "symfony/framework-bundle": "^6.4|^7.0|^8.0", + "symfony/http-foundation": "^6.4|^7.0|^8.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^6.4|^7.0|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v7.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-01-05T11:45:34+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.6.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "59eb412e93815df44f05f342958efa9f46b1e586" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/59eb412e93815df44f05f342958efa9f46b1e586", + "reference": "59eb412e93815df44f05f342958efa9f46b1e586", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.6-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.6.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:21:43+00:00" + }, + { + "name": "symfony/filesystem", + "version": "v7.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "d551b38811096d0be9c4691d406991b47c0c630a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/d551b38811096d0be9c4691d406991b47c0c630a", + "reference": "d551b38811096d0be9c4691d406991b47c0c630a", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "require-dev": { + "symfony/process": "^6.4|^7.0|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v7.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-11-27T13:27:24+00:00" + }, + { + "name": "symfony/finder", + "version": "v7.4.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "ad4daa7c38668dcb031e63bc99ea9bd42196a2cb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/ad4daa7c38668dcb031e63bc99ea9bd42196a2cb", + "reference": "ad4daa7c38668dcb031e63bc99ea9bd42196a2cb", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "symfony/filesystem": "^6.4|^7.0|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v7.4.5" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-01-26T15:07:59+00:00" + }, + { + "name": "symfony/options-resolver", + "version": "v7.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "b38026df55197f9e39a44f3215788edf83187b80" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/b38026df55197f9e39a44f3215788edf83187b80", + "reference": "b38026df55197f9e39a44f3215788edf83187b80", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v7.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-11-12T15:39:26+00:00" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638", + "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "380872130d3a5dd3ace2f4010d95125fde5d5c70" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/380872130d3a5dd3ace2f4010d95125fde5d5c70", + "reference": "380872130d3a5dd3ace2f4010d95125fde5d5c70", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-06-27T09:58:17+00:00" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "3833d7255cc303546435cb650316bff708a1c75c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/3833d7255cc303546435cb650316bff708a1c75c", + "reference": "3833d7255cc303546435cb650316bff708a1c75c", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6d857f4d76bd4b343eac26d6b539585d2bc56493", + "reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "php": ">=7.2" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-12-23T08:48:59+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/0cc9dd0f17f61d8131e7df6b84bd344899fe2608", + "reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-01-02T08:10:11+00:00" + }, + { + "name": "symfony/polyfill-php81", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "4a4cfc2d253c21a5ad0e53071df248ed48c6ce5c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/4a4cfc2d253c21a5ad0e53071df248ed48c6ce5c", + "reference": "4a4cfc2d253c21a5ad0e53071df248ed48c6ce5c", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-php84", + "version": "v1.33.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php84.git", + "reference": "d8ced4d875142b6a7426000426b8abc631d6b191" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/d8ced4d875142b6a7426000426b8abc631d6b191", + "reference": "d8ced4d875142b6a7426000426b8abc631d6b191", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php84\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.4+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php84/tree/v1.33.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-06-24T13:30:11+00:00" + }, + { + "name": "symfony/process", + "version": "v7.4.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "608476f4604102976d687c483ac63a79ba18cc97" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/608476f4604102976d687c483ac63a79ba18cc97", + "reference": "608476f4604102976d687c483ac63a79ba18cc97", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v7.4.5" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-01-26T15:07:59+00:00" + }, + { + "name": "symfony/service-contracts", + "version": "v3.6.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "45112560a3ba2d715666a509a0bc9521d10b6c43" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/45112560a3ba2d715666a509a0bc9521d10b6c43", + "reference": "45112560a3ba2d715666a509a0bc9521d10b6c43", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.6-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.6.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-07-15T11:30:57+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v7.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "8a24af0a2e8a872fb745047180649b8418303084" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/8a24af0a2e8a872fb745047180649b8418303084", + "reference": "8a24af0a2e8a872fb745047180649b8418303084", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/service-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a way to profile code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v7.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2025-08-04T07:05:15+00:00" + }, + { + "name": "symfony/string", + "version": "v7.4.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "1c4b10461bf2ec27537b5f36105337262f5f5d6f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/1c4b10461bf2ec27537b5f36105337262f5f5d6f", + "reference": "1c4b10461bf2ec27537b5f36105337262f5f5d6f", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3.0", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.33", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/emoji": "^7.1|^8.0", + "symfony/http-client": "^6.4|^7.0|^8.0", + "symfony/intl": "^6.4|^7.0|^8.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^6.4|^7.0|^8.0" + }, + "type": "library", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v7.4.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-01-12T10:54:30+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": true, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "2.6.0" +} From 35a0f54188fb53331d77d9fbb9052b78c4cbed9a Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:38:09 -0500 Subject: [PATCH 13/18] better appplication of csfixer Use the proper config file this time --- Net/DNS2.php | 2409 ++++++------ Net/DNS2/BitMap.php | 325 +- Net/DNS2/Cache.php | 400 +- Net/DNS2/Cache/File.php | 317 +- Net/DNS2/Cache/Shm.php | 457 +-- Net/DNS2/Exception.php | 119 +- Net/DNS2/Header.php | 336 +- Net/DNS2/Lookups.php | 955 +++-- Net/DNS2/Notifier.php | 356 +- Net/DNS2/Packet.php | 641 ++-- Net/DNS2/Packet/Request.php | 262 +- Net/DNS2/Packet/Response.php | 206 +- Net/DNS2/PrivateKey.php | 605 ++-- Net/DNS2/Question.php | 286 +- Net/DNS2/RR.php | 982 +++-- Net/DNS2/RR/A.php | 116 +- Net/DNS2/RR/AAAA.php | 151 +- Net/DNS2/RR/AFSDB.php | 131 +- Net/DNS2/RR/AMTRELAY.php | 409 +-- Net/DNS2/RR/ANY.php | 87 +- Net/DNS2/RR/APL.php | 502 ++- Net/DNS2/RR/ATMA.php | 203 +- Net/DNS2/RR/AVC.php | 3 +- Net/DNS2/RR/CAA.php | 175 +- Net/DNS2/RR/CDNSKEY.php | 3 +- Net/DNS2/RR/CDS.php | 3 +- Net/DNS2/RR/CERT.php | 356 +- Net/DNS2/RR/CNAME.php | 109 +- Net/DNS2/RR/CSYNC.php | 207 +- Net/DNS2/RR/DHCID.php | 210 +- Net/DNS2/RR/DLV.php | 3 +- Net/DNS2/RR/DNAME.php | 109 +- Net/DNS2/RR/DNSKEY.php | 193 +- Net/DNS2/RR/DS.php | 171 +- Net/DNS2/RR/EID.php | 87 +- Net/DNS2/RR/EUI48.php | 188 +- Net/DNS2/RR/EUI64.php | 194 +- Net/DNS2/RR/HINFO.php | 156 +- Net/DNS2/RR/HIP.php | 329 +- Net/DNS2/RR/IPSECKEY.php | 587 ++- Net/DNS2/RR/ISDN.php | 184 +- Net/DNS2/RR/KEY.php | 3 +- Net/DNS2/RR/KX.php | 137 +- Net/DNS2/RR/L32.php | 145 +- Net/DNS2/RR/L64.php | 163 +- Net/DNS2/RR/LOC.php | 603 ++-- Net/DNS2/RR/LP.php | 137 +- Net/DNS2/RR/MX.php | 137 +- Net/DNS2/RR/NAPTR.php | 244 +- Net/DNS2/RR/NID.php | 163 +- Net/DNS2/RR/NIMLOC.php | 87 +- Net/DNS2/RR/NS.php | 109 +- Net/DNS2/RR/NSAP.php | 331 +- Net/DNS2/RR/NSEC.php | 175 +- Net/DNS2/RR/NSEC3.php | 392 +- Net/DNS2/RR/NSEC3PARAM.php | 240 +- Net/DNS2/RR/OPENPGPKEY.php | 111 +- Net/DNS2/RR/OPT.php | 347 +- Net/DNS2/RR/PTR.php | 109 +- Net/DNS2/RR/PX.php | 171 +- Net/DNS2/RR/RP.php | 119 +- Net/DNS2/RR/RRSIG.php | 368 +- Net/DNS2/RR/RT.php | 133 +- Net/DNS2/RR/SIG.php | 612 ++-- Net/DNS2/RR/SMIMEA.php | 3 +- Net/DNS2/RR/SOA.php | 247 +- Net/DNS2/RR/SPF.php | 3 +- Net/DNS2/RR/SRV.php | 181 +- Net/DNS2/RR/SSHFP.php | 301 +- Net/DNS2/RR/TA.php | 3 +- Net/DNS2/RR/TALINK.php | 125 +- Net/DNS2/RR/TKEY.php | 391 +- Net/DNS2/RR/TLSA.php | 191 +- Net/DNS2/RR/TSIG.php | 764 ++-- Net/DNS2/RR/TXT.php | 168 +- Net/DNS2/RR/TYPE65534.php | 111 +- Net/DNS2/RR/URI.php | 141 +- Net/DNS2/RR/WKS.php | 266 +- Net/DNS2/RR/X25.php | 120 +- Net/DNS2/Resolver.php | 437 ++- Net/DNS2/Socket.php | 766 ++-- Net/DNS2/Socket/Sockets.php | 555 +-- Net/DNS2/Socket/Streams.php | 607 ++-- Net/DNS2/Updater.php | 1094 +++--- composer.json | 16 + includes/database.php | 2421 ++++++------- lib/mactrack_3com.php | 447 +-- lib/mactrack_aruba_oscx.php | 871 ++--- lib/mactrack_cabletron.php | 665 ++-- lib/mactrack_cisco.php | 1676 ++++----- lib/mactrack_dell.php | 462 +-- lib/mactrack_dlink.php | 620 ++-- lib/mactrack_enterasys.php | 258 +- lib/mactrack_enterasys_N7.php | 899 ++--- lib/mactrack_extreme.php | 533 +-- lib/mactrack_foundry.php | 367 +- lib/mactrack_functions.php | 6431 ++++++++++++++++----------------- lib/mactrack_h3c_3com.php | 831 ++--- lib/mactrack_hp.php | 216 +- lib/mactrack_hp_ng.php | 203 +- lib/mactrack_hp_ngi.php | 365 +- lib/mactrack_juniper.php | 290 +- lib/mactrack_linux.php | 427 +-- lib/mactrack_norbay.php | 476 +-- lib/mactrack_norbay_ng.php | 201 +- lib/mactrack_tplink.php | 325 +- lib/mactrack_trendnet.php | 451 +-- lib/mactrack_vendors.php | 40 +- mactrack_actions.php | 673 ++-- mactrack_ajax.php | 6 +- mactrack_ajax_admin.php | 27 +- mactrack_convert.php | 281 +- mactrack_device_types.php | 1885 +++++----- mactrack_devices.php | 2086 ++++++----- mactrack_import_ouidb.php | 119 +- mactrack_macauth.php | 561 ++- mactrack_macwatch.php | 623 ++-- mactrack_resolver.php | 356 +- mactrack_scanner.php | 346 +- mactrack_sites.php | 917 +++-- mactrack_snmp.php | 929 +++-- mactrack_utilities.php | 773 ++-- mactrack_vendormacs.php | 276 +- mactrack_view_arp.php | 886 +++-- mactrack_view_devices.php | 830 +++-- mactrack_view_dot1x.php | 1058 +++--- mactrack_view_graphs.php | 246 +- mactrack_view_interfaces.php | 970 ++--- mactrack_view_ips.php | 488 +-- mactrack_view_macs.php | 2096 ++++++----- mactrack_view_sites.php | 704 ++-- poller_mactrack.php | 1809 +++++----- setup.php | 3338 +++++++++-------- 133 files changed, 33172 insertions(+), 33634 deletions(-) create mode 100644 composer.json diff --git a/Net/DNS2.php b/Net/DNS2.php index f1b549fa..3e44677a 100644 --- a/Net/DNS2.php +++ b/Net/DNS2.php @@ -23,1220 +23,1197 @@ /** * This is the base class for the Net_DNS2_Resolver and Net_DNS2_Updater classes. */ -class Net_DNS2 -{ - // the current version of this library - public const VERSION = '1.5.0'; - - // the default path to a resolv.conf file - public const RESOLV_CONF = '/etc/resolv.conf'; - - /* - * override options from the resolv.conf file - * - * if this is set, then certain values from the resolv.conf file will override - * local settings. This is disabled by default to remain backwards compatible. - * - */ - public $use_resolv_options = false; - - // use TCP only (true/false) - public $use_tcp = false; - - // DNS Port to use (53) - public $dns_port = 53; - - // the ip/port for use as a local socket - public $local_host = ''; - public $local_port = 0; - - // timeout value for socket connections - public $timeout = 5; - - // randomize the name servers list - public $ns_random = false; - - // default domains - public $domain = ''; - - // domain search list - not actually used right now - public $search_list = []; - - // enable cache; either "shared", "file" or "none" - public $cache_type = 'none'; - - // file name to use for shared memory segment or file cache - public $cache_file = '/tmp/net_dns2.cache'; - - // the max size of the cache file (in bytes) - public $cache_size = 50000; - - /* - * the method to use for storing cache data; either "serialize" or "json" - * - * json is faster, but can't remember the class names (everything comes back - * as a "stdClass Object"; all the data is the same though. serialize is - * slower, but will have all the class info. - * - * defaults to 'serialize' - */ - public $cache_serializer = 'serialize'; - - /* - * by default, according to RFC 1034 - * - * CNAME RRs cause special action in DNS software. When a name server - * fails to find a desired RR in the resource set associated with the - * domain name, it checks to see if the resource set consists of a CNAME - * record with a matching class. If so, the name server includes the CNAME - * record in the response and restarts the query at the domain name - * specified in the data field of the CNAME record. - * - * this can cause "unexpected" behaviours, since i'm sure *most* people - * don't know DNS does this; there may be cases where Net_DNS2 returns a - * positive response, even though the hostname the user looked up did not - * actually exist. - * - * strict_query_mode means that if the hostname that was looked up isn't - * actually in the answer section of the response, Net_DNS2 will return an - * empty answer section, instead of an answer section that could contain - * CNAME records. - * - */ - public $strict_query_mode = false; - - /* - * if we should set the recursion desired bit to 1 or 0. - * - * by default this is set to true, we want the DNS server to perform a recursive - * request. If set to false, the RD bit will be set to 0, and the server will - * not perform recursion on the request. - */ - public $recurse = true; - - /* - * request DNSSEC values, by setting the DO flag to 1; this actually makes - * the resolver add a OPT RR to the additional section, and sets the DO flag - * in this RR to 1 - * - */ - public $dnssec = false; - - /* - * set the DNSSEC AD (Authentic Data) bit on/off; the AD bit on the request - * side was previously undefined, and resolvers we instructed to always clear - * the AD bit when sending a request. - * - * RFC6840 section 5.7 defines setting the AD bit in the query as a signal to - * the server that it wants the value of the AD bit, without needed to request - * all the DNSSEC data via the DO bit. - * - */ - public $dnssec_ad_flag = false; - - /* - * set the DNSSEC CD (Checking Disabled) bit on/off; turning this off, means - * that the DNS resolver will perform it's own signature validation- so the DNS - * servers simply pass through all the details. - * - */ - public $dnssec_cd_flag = false; - - /* - * the EDNS(0) UDP payload size to use when making DNSSEC requests - * see RFC 4035 section 4.1 - EDNS Support. - * - * there is some different ideas on the suggest size to support; but it seems to - * be "at least 1220 bytes, but SHOULD support 4000 bytes. - * - * we'll just support 4000 - * - */ - public $dnssec_payload_size = 4000; - - // the last exception that was generated - public $last_exception; - - // the list of exceptions by name server - public $last_exception_list = []; - - // name server list - public $nameservers = []; - - // local sockets - protected $sock = [Net_DNS2_Socket::SOCK_DGRAM => [], Net_DNS2_Socket::SOCK_STREAM => []]; - - // the TSIG or SIG RR object for authentication - protected $auth_signature; - - // the shared memory segment id for the local cache - protected $cache; - - // internal setting for enabling cache - protected $use_cache = false; - - /** - * Constructor - base constructor for the Resolver and Updater. - * - * @param mixed $options array of options or null for none - * - * @throws Net_DNS2_Exception - */ - public function __construct(?array $options = null) - { - // - // load any options that were provided - // - if (!empty($options)) { - foreach ($options as $key => $value) { - if ('nameservers' == $key) { - $this->setServers($value); - } else { - $this->{$key} = $value; - } - } - } - - // - // if we're set to use the local shared memory cache, then - // make sure it's been initialized - // - switch ($this->cache_type) { - case 'shared': - if (extension_loaded('shmop')) { - $this->cache = new Net_DNS2_Cache_Shm(); - $this->use_cache = true; - } else { - throw new Net_DNS2_Exception( - 'shmop library is not available for cache', - Net_DNS2_Lookups::E_CACHE_SHM_UNAVAIL - ); - } - - break; - - case 'file': - $this->cache = new Net_DNS2_Cache_File(); - $this->use_cache = true; - - break; - - case 'none': - $this->use_cache = false; - - break; - - default: - throw new Net_DNS2_Exception( - 'un-supported cache type: '.$this->cache_type, - Net_DNS2_Lookups::E_CACHE_UNSUPPORTED - ); - } - } - - /** - * autoload call-back function; used to auto-load classes. - * - * @param string $name the name of the class - */ - public static function autoload($name) - { - // - // only auto-load our classes - // - if (0 == strncmp($name, 'Net_DNS2', 8)) { - include str_replace('_', '/', $name).'.php'; - } - } - - /** - * sets the name servers to be used. - * - * @param mixed $nameservers either an array of name servers, or a file name - * to parse, assuming it's in the resolv.conf format - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function setServers($nameservers) - { - // - // if it's an array, then use it directly - // - // otherwise, see if it's a path to a resolv.conf file and if so, load it - // - if (is_array($nameservers)) { - $this->nameservers = $nameservers; - } else { - // - // temporary list of name servers; do it this way rather than just - // resetting the local nameservers value, just incase an exception - // is thrown here; this way we might avoid ending up with an empty - // namservers list. - // - $ns = []; - - // - // check to see if the file is readable - // - if (true === is_readable($nameservers)) { - $data = file_get_contents($nameservers); - if (false === $data) { - throw new Net_DNS2_Exception( - 'failed to read contents of file: '.$nameservers, - Net_DNS2_Lookups::E_NS_INVALID_FILE - ); - } - - $lines = explode("\n", $data); - - foreach ($lines as $line) { - $line = trim($line); - - // - // ignore empty lines, and lines that are commented out - // - if ((0 == strlen($line)) - || ('#' == $line[0]) - || (';' == $line[0]) - ) { - continue; - } - - // - // ignore lines with no spaces in them. - // - if (false === strpos($line, ' ')) { - continue; - } - - list($key, $value) = preg_split('/\s+/', $line, 2); - - $key = trim(strtolower($key)); - $value = trim(strtolower($value)); - - switch ($key) { - case 'nameserver': - // - // nameserver can be a IPv4 or IPv6 address - // - if ((true == self::isIPv4($value)) - || (true == self::isIPv6($value)) - ) { - $ns[] = $value; - } else { - throw new Net_DNS2_Exception( - 'invalid nameserver entry: '.$value, - Net_DNS2_Lookups::E_NS_INVALID_ENTRY - ); - } - - break; - - case 'domain': - $this->domain = $value; - - break; - - case 'search': - $this->search_list = preg_split('/\s+/', $value); - - break; - - case 'options': - $this->parseOptions($value); - - break; - - default:; - } - } - - // - // if we don't have a domain, but we have a search list, then - // take the first entry on the search list as the domain - // - if ((0 == strlen($this->domain)) - && (cacti_sizeof($this->search_list) > 0) - ) { - $this->domain = $this->search_list[0]; - } - } else { - throw new Net_DNS2_Exception( - 'resolver file file provided is not readable: '.$nameservers, - Net_DNS2_Lookups::E_NS_INVALID_FILE - ); - } - - // - // store the name servers locally - // - if (cacti_sizeof($ns) > 0) { - $this->nameservers = $ns; - } - } - - // - // remove any duplicates; not sure if we should bother with this- if people - // put duplicate name servers, who I am to stop them? - // - $this->nameservers = array_unique($this->nameservers); - - // - // check the name servers - // - $this->checkServers(); - - return true; - } - - /** - * return the internal $sock array. - * - * @return array - */ - public function getSockets() - { - return $this->sock; - } - - /** - * give users access to close all open sockets on the resolver object; resetting each - * array, calls the destructor on the Net_DNS2_Socket object, which calls the close() - * method on each object. - * - * @return bool - */ - public function closeSockets() - { - $this->sock[Net_DNS2_Socket::SOCK_DGRAM] = []; - $this->sock[Net_DNS2_Socket::SOCK_STREAM] = []; - - return true; - } - - /** - * adds a TSIG RR object for authentication. - * - * @param string $keyname the key name to use for the TSIG RR - * @param string $signature the key to sign the request - * @param string $algorithm the algorithm to use - * - * @return bool - * - * @since function available since release 1.1.0 - */ - public function signTSIG( - $keyname, - $signature = '', - $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5 - ) { - // - // if the TSIG was pre-created and passed in, then we can just used - // it as provided. - // - if ($keyname instanceof Net_DNS2_RR_TSIG) { - $this->auth_signature = $keyname; - } else { - // - // otherwise create the TSIG RR, but don't add it just yet; TSIG needs - // to be added as the last additional entry- so we'll add it just - // before we send. - // - $this->auth_signature = Net_DNS2_RR::fromString( - strtolower(trim($keyname)) - .' TSIG '.$signature - ); - - // - // set the algorithm to use - // - $this->auth_signature->algorithm = $algorithm; - } - - return true; - } - - /** - * adds a SIG RR object for authentication. - * - * @param string $filename the name of a file to load the signature from - * - * @return bool - * - * @throws Net_DNS2_Exception - * - * @since function available since release 1.1.0 - */ - public function signSIG0($filename) - { - // - // check for OpenSSL - // - if (false === extension_loaded('openssl')) { - throw new Net_DNS2_Exception( - 'the OpenSSL extension is required to use SIG(0).', - Net_DNS2_Lookups::E_OPENSSL_UNAVAIL - ); - } - - // - // if the SIG was pre-created, then use it as-is - // - if ($filename instanceof Net_DNS2_RR_SIG) { - $this->auth_signature = $filename; - } else { - // - // otherwise, it's filename which needs to be parsed and processed. - // - $private = new Net_DNS2_PrivateKey($filename); - - // - // create a new Net_DNS2_RR_SIG object - // - $this->auth_signature = new Net_DNS2_RR_SIG(); - - // - // reset some values - // - $this->auth_signature->name = $private->signname; - $this->auth_signature->ttl = 0; - $this->auth_signature->class = 'ANY'; - - // - // these values are pulled from the private key - // - $this->auth_signature->algorithm = $private->algorithm; - $this->auth_signature->keytag = $private->keytag; - $this->auth_signature->signname = $private->signname; - - // - // these values are hard-coded for SIG0 - // - $this->auth_signature->typecovered = 'SIG0'; - $this->auth_signature->labels = 0; - $this->auth_signature->origttl = 0; - - // - // generate the dates - // - $t = time(); - - $this->auth_signature->sigincep = gmdate('YmdHis', $t); - $this->auth_signature->sigexp = gmdate('YmdHis', $t + 500); - - // - // store the private key in the SIG object for later. - // - $this->auth_signature->private_key = $private; - } - - // - // only RSA algorithms are supported for SIG(0) - // - switch ($this->auth_signature->algorithm) { - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: - break; - - default: - throw new Net_DNS2_Exception( - 'only asymmetric algorithms work with SIG(0)!', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - return true; - } - - /** - * a simple function to determine if the RR type is cacheable. - * - * @param string $_type the RR type string - * - * @return bool returns true/false if the RR type if cacheable - */ - public function cacheable($_type) - { - switch ($_type) { - case 'AXFR': - case 'OPT': - return false; - } - - return true; - } - - /** - * PHP doesn't support unsigned integers, but many of the RR's return - * unsigned values (like SOA), so there is the possibility that the - * value will overrun on 32bit systems, and you'll end up with a - * negative value. - * - * 64bit systems are not affected, as their PHP_IN_MAX value should - * be 64bit (ie 9223372036854775807) - * - * This function returns a negative integer value, as a string, with - * the correct unsigned value. - * - * @param string $_int the unsigned integer value to check - * - * @return string returns the unsigned value as a string - */ - public static function expandUint32($_int) - { - if (($_int < 0) && (PHP_INT_MAX == 2147483647)) { - return sprintf('%u', $_int); - } - - return $_int; - } - - /** - * returns true/false if the given address is a valid IPv4 address. - * - * @param string $_address the IPv4 address to check - * - * @return bool returns true/false if the address is IPv4 address - */ - public static function isIPv4($_address) - { - // - // use filter_var() if it's available; it's faster than preg - // - if (true == extension_loaded('filter')) { - if (false == filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - return false; - } - } else { - // - // do the main check here; - // - if (false === inet_pton($_address)) { - return false; - } - - // - // then make sure we're not a IPv6 address - // - if (0 == preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address)) { - return false; - } - } - - return true; - } - - /** - * returns true/false if the given address is a valid IPv6 address. - * - * @param string $_address the IPv6 address to check - * - * @return bool returns true/false if the address is IPv6 address - */ - public static function isIPv6($_address) - { - // - // use filter_var() if it's available; it's faster than preg - // - if (true == extension_loaded('filter')) { - if (false == filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { - return false; - } - } else { - // - // do the main check here - // - if (false === inet_pton($_address)) { - return false; - } - - // - // then make sure it doesn't match a IPv4 address - // - if (1 == preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address)) { - return false; - } - } - - return true; - } - - /** - * formats the given IPv6 address as a fully expanded IPv6 address. - * - * @param string $_address the IPv6 address to expand - * - * @return string the fully expanded IPv6 address - */ - public static function expandIPv6($_address) - { - $hex = unpack('H*hex', inet_pton($_address)); - - return substr(preg_replace('/([A-f0-9]{4})/', '$1:', $hex['hex']), 0, -1); - } - - /** - * checks the list of name servers to make sure they're set. - * - * @param mixed $default a path to a resolv.conf file or an array of servers. - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - protected function checkServers($default = null) - { - if (empty($this->nameservers)) { - if (isset($default)) { - $this->setServers($default); - } else { - throw new Net_DNS2_Exception( - 'empty name servers list; you must provide a list of name ' - .'servers, or the path to a resolv.conf file.', - Net_DNS2_Lookups::E_NS_INVALID_ENTRY - ); - } - } - - return true; - } - - /** - * sends a standard Net_DNS2_Packet_Request packet. - * - * @param Net_DNS2_Packet $request a Net_DNS2_Packet_Request object - * @param bool $use_tcp true/false if the function should - * use TCP for the request - * - * @return Net_DNS2_Packet_Response - * - * @throws Net_DNS2_Exception - */ - protected function sendPacket(Net_DNS2_Packet $request, $use_tcp) - { - // - // get the data from the packet - // - $data = $request->get(); - if (strlen($data) < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - throw new Net_DNS2_Exception( - 'invalid or empty packet for sending!', - Net_DNS2_Lookups::E_PACKET_INVALID, - null, - $request - ); - } - - reset($this->nameservers); - - // - // randomize the name server list if it's asked for - // - if (true == $this->ns_random) { - shuffle($this->nameservers); - } - - // - // loop so we can handle server errors - // - $response = null; - $ns = ''; - - while (1) { - // - // grab the next DNS server - // - $ns = current($this->nameservers); - next($this->nameservers); - - if (false === $ns) { - if (false == is_null($this->last_exception)) { - throw $this->last_exception; - } - - throw new Net_DNS2_Exception( - 'every name server provided has failed', - Net_DNS2_Lookups::E_NS_FAILED - ); - } - - // - // if the use TCP flag (force TCP) is set, or the packet is bigger than our - // max allowed UDP size- which is either 512, or if this is DNSSEC request, - // then whatever the configured dnssec_payload_size is. - // - $max_udp_size = Net_DNS2_Lookups::DNS_MAX_UDP_SIZE; - if (true == $this->dnssec) { - $max_udp_size = $this->dnssec_payload_size; - } - - if ((true == $use_tcp) || (strlen($data) > $max_udp_size)) { - try { - $response = $this->sendTCPRequest($ns, $data, ('AXFR' == $request->question[0]->qtype) ? true : false); - } catch (Net_DNS2_Exception $e) { - $this->last_exception = $e; - $this->last_exception_list[$ns] = $e; - - continue; - } - - // - // otherwise, send it using UDP - // - } else { - try { - $response = $this->sendUDPRequest($ns, $data); - - // - // check the packet header for a truncated bit; if it was truncated, - // then re-send the request as TCP. - // - if (1 == $response->header->tc) { - $response = $this->sendTCPRequest($ns, $data); - } - } catch (Net_DNS2_Exception $e) { - $this->last_exception = $e; - $this->last_exception_list[$ns] = $e; - - continue; - } - } - - // - // make sure header id's match between the request and response - // - if ($request->header->id != $response->header->id) { - $this->last_exception = new Net_DNS2_Exception( - 'invalid header: the request and response id do not match.', - Net_DNS2_Lookups::E_HEADER_INVALID, - null, - $request, - $response - ); - - $this->last_exception_list[$ns] = $this->last_exception; - - continue; - } - - // - // make sure the response is actually a response - // - // 0 = query, 1 = response - // - if (Net_DNS2_Lookups::QR_RESPONSE != $response->header->qr) { - $this->last_exception = new Net_DNS2_Exception( - 'invalid header: the response provided is not a response packet.', - Net_DNS2_Lookups::E_HEADER_INVALID, - null, - $request, - $response - ); - - $this->last_exception_list[$ns] = $this->last_exception; - - continue; - } - - // - // make sure the response code in the header is ok - // - if (Net_DNS2_Lookups::RCODE_NOERROR != $response->header->rcode) { - $this->last_exception = new Net_DNS2_Exception( - 'DNS request failed: ' - .Net_DNS2_Lookups::$result_code_messages[$response->header->rcode], - $response->header->rcode, - null, - $request, - $response - ); - - $this->last_exception_list[$ns] = $this->last_exception; - - continue; - } - - break; - } - - return $response; - } - - /** - * parses the options line from a resolv.conf file; we don't support all the options - * yet, and using them is optional. - * - * @param string $value is the options string from the resolv.conf file. - * - * @return bool - */ - private function parseOptions($value) - { - // - // if overrides are disabled (the default), or the options list is empty for some - // reason, then we don't need to do any of this work. - // - if ((false == $this->use_resolv_options) || (0 == strlen($value))) { - return true; - } - - $options = preg_split('/\s+/', strtolower($value)); - - foreach ($options as $option) { - // - // override the timeout value from the resolv.conf file. - // - if ((0 == strncmp($option, 'timeout', 7)) && (false !== strpos($option, ':'))) { - list($key, $val) = explode(':', $option); - - if (($val > 0) && ($val <= 30)) { - $this->timeout = $val; - } - - // - // the rotate option just enabled the ns_random option - // - } elseif (0 == strncmp($option, 'rotate', 6)) { - $this->ns_random = true; - } - } - - return true; - } - - /** - * cleans up a failed socket and throws the given exception. - * - * @param string $_proto the protocol of the socket - * @param string $_ns the name server to use for the request - * @param string $_error the error message to throw at the end of the function - * - * @throws Net_DNS2_Exception - */ - private function generateError($_proto, $_ns, $_error) - { - if (false == isset($this->sock[$_proto][$_ns])) { - throw new Net_DNS2_Exception('invalid socket referenced', Net_DNS2_Lookups::E_NS_INVALID_SOCKET); - } - - // - // grab the last error message off the socket - // - $last_error = $this->sock[$_proto][$_ns]->last_error; - - // - // remove it from the socket cache; this will call the destructor, which calls close() on the socket - // - unset($this->sock[$_proto][$_ns]); - - // - // throw the error provided - // - throw new Net_DNS2_Exception($last_error, $_error); - } - - /** - * sends a DNS request using TCP. - * - * @param string $_ns the name server to use for the request - * @param string $_data the raw DNS packet data - * @param bool $_axfr if this is a zone transfer request - * - * @return Net_DNS2_Packet_Response the response object - * - * @throws Net_DNS2_Exception - */ - private function sendTCPRequest($_ns, $_data, $_axfr = false) - { - // - // grab the start time - // - $start_time = microtime(true); - - // - // see if we already have an open socket from a previous request; if so, try to use - // that instead of opening a new one. - // - if ((!isset($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns])) - || (!$this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] instanceof Net_DNS2_Socket) - ) { - // - // create the socket object - // - $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] = new Net_DNS2_Socket( - Net_DNS2_Socket::SOCK_STREAM, - $_ns, - $this->dns_port, - $this->timeout - ); - - // - // if a local IP address / port is set, then add it - // - if (strlen($this->local_host) > 0) { - $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->bindAddress( - $this->local_host, - $this->local_port - ); - } - - // - // open the socket - // - if (false === $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->open()) { - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - } - - // - // write the data to the socket; if it fails, continue on - // the while loop - // - if (false === $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->write($_data)) { - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // read the content, using select to wait for a response - // - $size = 0; - $result = null; - $response = null; - - // - // handle zone transfer requests differently than other requests. - // - if (true == $_axfr) { - $soa_count = 0; - - while (1) { - // - // read the data off the socket - // - $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read( - $size, - (true == $this->dnssec) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE - ); - - if ((false === $result) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { - // - // if we get an error, then keeping this socket around for a future request, could cause - // an error- for example, https://github.com/mikepultz/netdns2/issues/61 - // - // in this case, the connection was timing out, which once it did finally respond, left - // data on the socket, which could be captured on a subsequent request. - // - // since there's no way to "reset" a socket, the only thing we can do it close it. - // - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // parse the first chunk as a packet - // - $chunk = new Net_DNS2_Packet_Response($result, $size); - - // - // if this is the first packet, then clone it directly, then - // go through it to see if there are two SOA records - // (indicating that it's the only packet) - // - if (true == is_null($response)) { - $response = clone $chunk; - - // - // look for a failed response; if the zone transfer - // failed, then we don't need to do anything else at this - // point, and we should just break out. - // - if (Net_DNS2_Lookups::RCODE_NOERROR != $response->header->rcode) { - break; - } - - // - // go through each answer - // - foreach ($response->answer as $index => $rr) { - // - // count the SOA records - // - if ('SOA' == $rr->type) { - ++$soa_count; - } - } - - // - // if we have 2 or more SOA records, then we're done; - // otherwise continue out so we read the rest of the - // packets off the socket - // - if ($soa_count >= 2) { - break; - } - - continue; - } - - // - // go through all these answers, and look for SOA records - // - foreach ($chunk->answer as $index => $rr) { - // - // count the number of SOA records we find - // - if ('SOA' == $rr->type) { - ++$soa_count; - } - - // - // add the records to a single response object - // - $response->answer[] = $rr; - } - - // - // if we've found the second SOA record, we're done - // - if ($soa_count >= 2) { - break; - } - } - - // - // everything other than a AXFR - // - } else { - $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read( - $size, - (true == $this->dnssec) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE - ); - - if ((false === $result) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { - $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // create the packet object - // - $response = new Net_DNS2_Packet_Response($result, $size); - } - - // - // store the query time - // - $response->response_time = microtime(true) - $start_time; - - // - // add the name server that the response came from to the response object, - // and the socket type that was used. - // - $response->answer_from = $_ns; - $response->answer_socket_type = Net_DNS2_Socket::SOCK_STREAM; - - // - // return the Net_DNS2_Packet_Response object - // - return $response; - } - - /** - * sends a DNS request using UDP. - * - * @param string $_ns the name server to use for the request - * @param string $_data the raw DNS packet data - * - * @return Net_DNS2_Packet_Response the response object - * - * @throws Net_DNS2_Exception - */ - private function sendUDPRequest($_ns, $_data) - { - // - // grab the start time - // - $start_time = microtime(true); - - // - // see if we already have an open socket from a previous request; if so, try to use - // that instead of opening a new one. - // - if ((!isset($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns])) - || (!$this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] instanceof Net_DNS2_Socket) - ) { - // - // create the socket object - // - $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] = new Net_DNS2_Socket( - Net_DNS2_Socket::SOCK_DGRAM, - $_ns, - $this->dns_port, - $this->timeout - ); - - // - // if a local IP address / port is set, then add it - // - if (strlen($this->local_host) > 0) { - $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->bindAddress( - $this->local_host, - $this->local_port - ); - } - - // - // open the socket - // - if (false === $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->open()) { - $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - } - - // - // write the data to the socket - // - if (false === $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->write($_data)) { - $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // read the content, using select to wait for a response - // - $size = 0; - - $result = $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->read( - $size, - (true == $this->dnssec) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE - ); - - if ((false === $result) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { - $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); - } - - // - // create the packet object - // - $response = new Net_DNS2_Packet_Response($result, $size); - - // - // store the query time - // - $response->response_time = microtime(true) - $start_time; - - // - // add the name server that the response came from to the response object, - // and the socket type that was used. - // - $response->answer_from = $_ns; - $response->answer_socket_type = Net_DNS2_Socket::SOCK_DGRAM; - - // - // return the Net_DNS2_Packet_Response object - // - return $response; - } +class Net_DNS2 { + // the current version of this library + public const VERSION = '1.5.0'; + + // the default path to a resolv.conf file + public const RESOLV_CONF = '/etc/resolv.conf'; + + /* + * override options from the resolv.conf file + * + * if this is set, then certain values from the resolv.conf file will override + * local settings. This is disabled by default to remain backwards compatible. + * + */ + public $use_resolv_options = false; + + // use TCP only (true/false) + public $use_tcp = false; + + // DNS Port to use (53) + public $dns_port = 53; + + // the ip/port for use as a local socket + public $local_host = ''; + public $local_port = 0; + + // timeout value for socket connections + public $timeout = 5; + + // randomize the name servers list + public $ns_random = false; + + // default domains + public $domain = ''; + + // domain search list - not actually used right now + public $search_list = []; + + // enable cache; either "shared", "file" or "none" + public $cache_type = 'none'; + + // file name to use for shared memory segment or file cache + public $cache_file = '/tmp/net_dns2.cache'; + + // the max size of the cache file (in bytes) + public $cache_size = 50000; + + /* + * the method to use for storing cache data; either "serialize" or "json" + * + * json is faster, but can't remember the class names (everything comes back + * as a "stdClass Object"; all the data is the same though. serialize is + * slower, but will have all the class info. + * + * defaults to 'serialize' + */ + public $cache_serializer = 'serialize'; + + /* + * by default, according to RFC 1034 + * + * CNAME RRs cause special action in DNS software. When a name server + * fails to find a desired RR in the resource set associated with the + * domain name, it checks to see if the resource set consists of a CNAME + * record with a matching class. If so, the name server includes the CNAME + * record in the response and restarts the query at the domain name + * specified in the data field of the CNAME record. + * + * this can cause "unexpected" behaviours, since i'm sure *most* people + * don't know DNS does this; there may be cases where Net_DNS2 returns a + * positive response, even though the hostname the user looked up did not + * actually exist. + * + * strict_query_mode means that if the hostname that was looked up isn't + * actually in the answer section of the response, Net_DNS2 will return an + * empty answer section, instead of an answer section that could contain + * CNAME records. + * + */ + public $strict_query_mode = false; + + /* + * if we should set the recursion desired bit to 1 or 0. + * + * by default this is set to true, we want the DNS server to perform a recursive + * request. If set to false, the RD bit will be set to 0, and the server will + * not perform recursion on the request. + */ + public $recurse = true; + + /* + * request DNSSEC values, by setting the DO flag to 1; this actually makes + * the resolver add a OPT RR to the additional section, and sets the DO flag + * in this RR to 1 + * + */ + public $dnssec = false; + + /* + * set the DNSSEC AD (Authentic Data) bit on/off; the AD bit on the request + * side was previously undefined, and resolvers we instructed to always clear + * the AD bit when sending a request. + * + * RFC6840 section 5.7 defines setting the AD bit in the query as a signal to + * the server that it wants the value of the AD bit, without needed to request + * all the DNSSEC data via the DO bit. + * + */ + public $dnssec_ad_flag = false; + + /* + * set the DNSSEC CD (Checking Disabled) bit on/off; turning this off, means + * that the DNS resolver will perform it's own signature validation- so the DNS + * servers simply pass through all the details. + * + */ + public $dnssec_cd_flag = false; + + /* + * the EDNS(0) UDP payload size to use when making DNSSEC requests + * see RFC 4035 section 4.1 - EDNS Support. + * + * there is some different ideas on the suggest size to support; but it seems to + * be "at least 1220 bytes, but SHOULD support 4000 bytes. + * + * we'll just support 4000 + * + */ + public $dnssec_payload_size = 4000; + + // the last exception that was generated + public $last_exception; + + // the list of exceptions by name server + public $last_exception_list = []; + + // name server list + public $nameservers = []; + + // local sockets + protected $sock = [Net_DNS2_Socket::SOCK_DGRAM => [], Net_DNS2_Socket::SOCK_STREAM => []]; + + // the TSIG or SIG RR object for authentication + protected $auth_signature; + + // the shared memory segment id for the local cache + protected $cache; + + // internal setting for enabling cache + protected $use_cache = false; + + /** + * Constructor - base constructor for the Resolver and Updater. + * + * @param mixed $options array of options or null for none + * + * @throws Net_DNS2_Exception + */ + public function __construct(?array $options = null) { + // + // load any options that were provided + // + if (!empty($options)) { + foreach ($options as $key => $value) { + if ($key == 'nameservers') { + $this->setServers($value); + } else { + $this->{$key} = $value; + } + } + } + + // + // if we're set to use the local shared memory cache, then + // make sure it's been initialized + // + switch ($this->cache_type) { + case 'shared': + if (extension_loaded('shmop')) { + $this->cache = new Net_DNS2_Cache_Shm(); + $this->use_cache = true; + } else { + throw new Net_DNS2_Exception( + 'shmop library is not available for cache', + Net_DNS2_Lookups::E_CACHE_SHM_UNAVAIL + ); + } + + break; + case 'file': + $this->cache = new Net_DNS2_Cache_File(); + $this->use_cache = true; + + break; + case 'none': + $this->use_cache = false; + + break; + default: + throw new Net_DNS2_Exception( + 'un-supported cache type: ' . $this->cache_type, + Net_DNS2_Lookups::E_CACHE_UNSUPPORTED + ); + } + } + + /** + * autoload call-back function; used to auto-load classes. + * + * @param string $name the name of the class + */ + public static function autoload($name) { + // + // only auto-load our classes + // + if (strncmp($name, 'Net_DNS2', 8) == 0) { + include str_replace('_', '/', $name) . '.php'; + } + } + + /** + * sets the name servers to be used. + * + * @param mixed $nameservers either an array of name servers, or a file name + * to parse, assuming it's in the resolv.conf format + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function setServers($nameservers) { + // + // if it's an array, then use it directly + // + // otherwise, see if it's a path to a resolv.conf file and if so, load it + // + if (is_array($nameservers)) { + $this->nameservers = $nameservers; + } else { + // + // temporary list of name servers; do it this way rather than just + // resetting the local nameservers value, just incase an exception + // is thrown here; this way we might avoid ending up with an empty + // namservers list. + // + $ns = []; + + // + // check to see if the file is readable + // + if (is_readable($nameservers) === true) { + $data = file_get_contents($nameservers); + + if ($data === false) { + throw new Net_DNS2_Exception( + 'failed to read contents of file: ' . $nameservers, + Net_DNS2_Lookups::E_NS_INVALID_FILE + ); + } + + $lines = explode("\n", $data); + + foreach ($lines as $line) { + $line = trim($line); + + // + // ignore empty lines, and lines that are commented out + // + if ((strlen($line) == 0) + || ($line[0] == '#') + || ($line[0] == ';') + ) { + continue; + } + + // + // ignore lines with no spaces in them. + // + if (strpos($line, ' ') === false) { + continue; + } + + [$key, $value] = preg_split('/\s+/', $line, 2); + + $key = trim(strtolower($key)); + $value = trim(strtolower($value)); + + switch ($key) { + case 'nameserver': + // + // nameserver can be a IPv4 or IPv6 address + // + if ((self::isIPv4($value) == true) + || (self::isIPv6($value) == true) + ) { + $ns[] = $value; + } else { + throw new Net_DNS2_Exception( + 'invalid nameserver entry: ' . $value, + Net_DNS2_Lookups::E_NS_INVALID_ENTRY + ); + } + + break; + case 'domain': + $this->domain = $value; + + break; + case 'search': + $this->search_list = preg_split('/\s+/', $value); + + break; + case 'options': + $this->parseOptions($value); + + break; + default:; + } + } + + // + // if we don't have a domain, but we have a search list, then + // take the first entry on the search list as the domain + // + if ((strlen($this->domain) == 0) + && (cacti_sizeof($this->search_list) > 0) + ) { + $this->domain = $this->search_list[0]; + } + } else { + throw new Net_DNS2_Exception( + 'resolver file file provided is not readable: ' . $nameservers, + Net_DNS2_Lookups::E_NS_INVALID_FILE + ); + } + + // + // store the name servers locally + // + if (cacti_sizeof($ns) > 0) { + $this->nameservers = $ns; + } + } + + // + // remove any duplicates; not sure if we should bother with this- if people + // put duplicate name servers, who I am to stop them? + // + $this->nameservers = array_unique($this->nameservers); + + // + // check the name servers + // + $this->checkServers(); + + return true; + } + + /** + * return the internal $sock array. + * + * @return array + */ + public function getSockets() { + return $this->sock; + } + + /** + * give users access to close all open sockets on the resolver object; resetting each + * array, calls the destructor on the Net_DNS2_Socket object, which calls the close() + * method on each object. + * + * @return bool + */ + public function closeSockets() { + $this->sock[Net_DNS2_Socket::SOCK_DGRAM] = []; + $this->sock[Net_DNS2_Socket::SOCK_STREAM] = []; + + return true; + } + + /** + * adds a TSIG RR object for authentication. + * + * @param string $keyname the key name to use for the TSIG RR + * @param string $signature the key to sign the request + * @param string $algorithm the algorithm to use + * + * @return bool + * + * @since function available since release 1.1.0 + */ + public function signTSIG( + $keyname, + $signature = '', + $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5 + ) { + // + // if the TSIG was pre-created and passed in, then we can just used + // it as provided. + // + if ($keyname instanceof Net_DNS2_RR_TSIG) { + $this->auth_signature = $keyname; + } else { + // + // otherwise create the TSIG RR, but don't add it just yet; TSIG needs + // to be added as the last additional entry- so we'll add it just + // before we send. + // + $this->auth_signature = Net_DNS2_RR::fromString( + strtolower(trim($keyname)) + . ' TSIG ' . $signature + ); + + // + // set the algorithm to use + // + $this->auth_signature->algorithm = $algorithm; + } + + return true; + } + + /** + * adds a SIG RR object for authentication. + * + * @param string $filename the name of a file to load the signature from + * + * @return bool + * + * @throws Net_DNS2_Exception + * + * @since function available since release 1.1.0 + */ + public function signSIG0($filename) { + // + // check for OpenSSL + // + if (extension_loaded('openssl') === false) { + throw new Net_DNS2_Exception( + 'the OpenSSL extension is required to use SIG(0).', + Net_DNS2_Lookups::E_OPENSSL_UNAVAIL + ); + } + + // + // if the SIG was pre-created, then use it as-is + // + if ($filename instanceof Net_DNS2_RR_SIG) { + $this->auth_signature = $filename; + } else { + // + // otherwise, it's filename which needs to be parsed and processed. + // + $private = new Net_DNS2_PrivateKey($filename); + + // + // create a new Net_DNS2_RR_SIG object + // + $this->auth_signature = new Net_DNS2_RR_SIG(); + + // + // reset some values + // + $this->auth_signature->name = $private->signname; + $this->auth_signature->ttl = 0; + $this->auth_signature->class = 'ANY'; + + // + // these values are pulled from the private key + // + $this->auth_signature->algorithm = $private->algorithm; + $this->auth_signature->keytag = $private->keytag; + $this->auth_signature->signname = $private->signname; + + // + // these values are hard-coded for SIG0 + // + $this->auth_signature->typecovered = 'SIG0'; + $this->auth_signature->labels = 0; + $this->auth_signature->origttl = 0; + + // + // generate the dates + // + $t = time(); + + $this->auth_signature->sigincep = gmdate('YmdHis', $t); + $this->auth_signature->sigexp = gmdate('YmdHis', $t + 500); + + // + // store the private key in the SIG object for later. + // + $this->auth_signature->private_key = $private; + } + + // + // only RSA algorithms are supported for SIG(0) + // + switch ($this->auth_signature->algorithm) { + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: + break; + default: + throw new Net_DNS2_Exception( + 'only asymmetric algorithms work with SIG(0)!', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + return true; + } + + /** + * a simple function to determine if the RR type is cacheable. + * + * @param string $_type the RR type string + * + * @return bool returns true/false if the RR type if cacheable + */ + public function cacheable($_type) { + switch ($_type) { + case 'AXFR': + case 'OPT': + return false; + } + + return true; + } + + /** + * PHP doesn't support unsigned integers, but many of the RR's return + * unsigned values (like SOA), so there is the possibility that the + * value will overrun on 32bit systems, and you'll end up with a + * negative value. + * + * 64bit systems are not affected, as their PHP_IN_MAX value should + * be 64bit (ie 9223372036854775807) + * + * This function returns a negative integer value, as a string, with + * the correct unsigned value. + * + * @param string $_int the unsigned integer value to check + * + * @return string returns the unsigned value as a string + */ + public static function expandUint32($_int) { + if (($_int < 0) && (PHP_INT_MAX == 2147483647)) { + return sprintf('%u', $_int); + } + + return $_int; + } + + /** + * returns true/false if the given address is a valid IPv4 address. + * + * @param string $_address the IPv4 address to check + * + * @return bool returns true/false if the address is IPv4 address + */ + public static function isIPv4($_address) { + // + // use filter_var() if it's available; it's faster than preg + // + if (extension_loaded('filter') == true) { + if (filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == false) { + return false; + } + } else { + // + // do the main check here; + // + if (inet_pton($_address) === false) { + return false; + } + + // + // then make sure we're not a IPv6 address + // + if (preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address) == 0) { + return false; + } + } + + return true; + } + + /** + * returns true/false if the given address is a valid IPv6 address. + * + * @param string $_address the IPv6 address to check + * + * @return bool returns true/false if the address is IPv6 address + */ + public static function isIPv6($_address) { + // + // use filter_var() if it's available; it's faster than preg + // + if (extension_loaded('filter') == true) { + if (filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) == false) { + return false; + } + } else { + // + // do the main check here + // + if (inet_pton($_address) === false) { + return false; + } + + // + // then make sure it doesn't match a IPv4 address + // + if (preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address) == 1) { + return false; + } + } + + return true; + } + + /** + * formats the given IPv6 address as a fully expanded IPv6 address. + * + * @param string $_address the IPv6 address to expand + * + * @return string the fully expanded IPv6 address + */ + public static function expandIPv6($_address) { + $hex = unpack('H*hex', inet_pton($_address)); + + return substr(preg_replace('/([A-f0-9]{4})/', '$1:', $hex['hex']), 0, -1); + } + + /** + * checks the list of name servers to make sure they're set. + * + * @param mixed $default a path to a resolv.conf file or an array of servers. + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + protected function checkServers($default = null) { + if (empty($this->nameservers)) { + if (isset($default)) { + $this->setServers($default); + } else { + throw new Net_DNS2_Exception( + 'empty name servers list; you must provide a list of name ' + . 'servers, or the path to a resolv.conf file.', + Net_DNS2_Lookups::E_NS_INVALID_ENTRY + ); + } + } + + return true; + } + + /** + * sends a standard Net_DNS2_Packet_Request packet. + * + * @param Net_DNS2_Packet $request a Net_DNS2_Packet_Request object + * @param bool $use_tcp true/false if the function should + * use TCP for the request + * + * @return Net_DNS2_Packet_Response + * + * @throws Net_DNS2_Exception + */ + protected function sendPacket(Net_DNS2_Packet $request, $use_tcp) { + // + // get the data from the packet + // + $data = $request->get(); + + if (strlen($data) < Net_DNS2_Lookups::DNS_HEADER_SIZE) { + throw new Net_DNS2_Exception( + 'invalid or empty packet for sending!', + Net_DNS2_Lookups::E_PACKET_INVALID, + null, + $request + ); + } + + reset($this->nameservers); + + // + // randomize the name server list if it's asked for + // + if ($this->ns_random == true) { + shuffle($this->nameservers); + } + + // + // loop so we can handle server errors + // + $response = null; + $ns = ''; + + while (1) { + // + // grab the next DNS server + // + $ns = current($this->nameservers); + next($this->nameservers); + + if ($ns === false) { + if (is_null($this->last_exception) == false) { + throw $this->last_exception; + } + + throw new Net_DNS2_Exception( + 'every name server provided has failed', + Net_DNS2_Lookups::E_NS_FAILED + ); + } + + // + // if the use TCP flag (force TCP) is set, or the packet is bigger than our + // max allowed UDP size- which is either 512, or if this is DNSSEC request, + // then whatever the configured dnssec_payload_size is. + // + $max_udp_size = Net_DNS2_Lookups::DNS_MAX_UDP_SIZE; + + if ($this->dnssec == true) { + $max_udp_size = $this->dnssec_payload_size; + } + + if (($use_tcp == true) || (strlen($data) > $max_udp_size)) { + try { + $response = $this->sendTCPRequest($ns, $data, ($request->question[0]->qtype == 'AXFR') ? true : false); + } catch (Net_DNS2_Exception $e) { + $this->last_exception = $e; + $this->last_exception_list[$ns] = $e; + + continue; + } + + // + // otherwise, send it using UDP + // + } else { + try { + $response = $this->sendUDPRequest($ns, $data); + + // + // check the packet header for a truncated bit; if it was truncated, + // then re-send the request as TCP. + // + if ($response->header->tc == 1) { + $response = $this->sendTCPRequest($ns, $data); + } + } catch (Net_DNS2_Exception $e) { + $this->last_exception = $e; + $this->last_exception_list[$ns] = $e; + + continue; + } + } + + // + // make sure header id's match between the request and response + // + if ($request->header->id != $response->header->id) { + $this->last_exception = new Net_DNS2_Exception( + 'invalid header: the request and response id do not match.', + Net_DNS2_Lookups::E_HEADER_INVALID, + null, + $request, + $response + ); + + $this->last_exception_list[$ns] = $this->last_exception; + + continue; + } + + // + // make sure the response is actually a response + // + // 0 = query, 1 = response + // + if ($response->header->qr != Net_DNS2_Lookups::QR_RESPONSE) { + $this->last_exception = new Net_DNS2_Exception( + 'invalid header: the response provided is not a response packet.', + Net_DNS2_Lookups::E_HEADER_INVALID, + null, + $request, + $response + ); + + $this->last_exception_list[$ns] = $this->last_exception; + + continue; + } + + // + // make sure the response code in the header is ok + // + if ($response->header->rcode != Net_DNS2_Lookups::RCODE_NOERROR) { + $this->last_exception = new Net_DNS2_Exception( + 'DNS request failed: ' + . Net_DNS2_Lookups::$result_code_messages[$response->header->rcode], + $response->header->rcode, + null, + $request, + $response + ); + + $this->last_exception_list[$ns] = $this->last_exception; + + continue; + } + + break; + } + + return $response; + } + + /** + * parses the options line from a resolv.conf file; we don't support all the options + * yet, and using them is optional. + * + * @param string $value is the options string from the resolv.conf file. + * + * @return bool + */ + private function parseOptions($value) { + // + // if overrides are disabled (the default), or the options list is empty for some + // reason, then we don't need to do any of this work. + // + if (($this->use_resolv_options == false) || (strlen($value) == 0)) { + return true; + } + + $options = preg_split('/\s+/', strtolower($value)); + + foreach ($options as $option) { + // + // override the timeout value from the resolv.conf file. + // + if ((strncmp($option, 'timeout', 7) == 0) && (strpos($option, ':') !== false)) { + [$key, $val] = explode(':', $option); + + if (($val > 0) && ($val <= 30)) { + $this->timeout = $val; + } + + // + // the rotate option just enabled the ns_random option + // + } elseif (strncmp($option, 'rotate', 6) == 0) { + $this->ns_random = true; + } + } + + return true; + } + + /** + * cleans up a failed socket and throws the given exception. + * + * @param string $_proto the protocol of the socket + * @param string $_ns the name server to use for the request + * @param string $_error the error message to throw at the end of the function + * + * @throws Net_DNS2_Exception + */ + private function generateError($_proto, $_ns, $_error) { + if (isset($this->sock[$_proto][$_ns]) == false) { + throw new Net_DNS2_Exception('invalid socket referenced', Net_DNS2_Lookups::E_NS_INVALID_SOCKET); + } + + // + // grab the last error message off the socket + // + $last_error = $this->sock[$_proto][$_ns]->last_error; + + // + // remove it from the socket cache; this will call the destructor, which calls close() on the socket + // + unset($this->sock[$_proto][$_ns]); + + // + // throw the error provided + // + throw new Net_DNS2_Exception($last_error, $_error); + } + + /** + * sends a DNS request using TCP. + * + * @param string $_ns the name server to use for the request + * @param string $_data the raw DNS packet data + * @param bool $_axfr if this is a zone transfer request + * + * @return Net_DNS2_Packet_Response the response object + * + * @throws Net_DNS2_Exception + */ + private function sendTCPRequest($_ns, $_data, $_axfr = false) { + // + // grab the start time + // + $start_time = microtime(true); + + // + // see if we already have an open socket from a previous request; if so, try to use + // that instead of opening a new one. + // + if ((!isset($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns])) + || (!$this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] instanceof Net_DNS2_Socket) + ) { + // + // create the socket object + // + $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] = new Net_DNS2_Socket( + Net_DNS2_Socket::SOCK_STREAM, + $_ns, + $this->dns_port, + $this->timeout + ); + + // + // if a local IP address / port is set, then add it + // + if (strlen($this->local_host) > 0) { + $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->bindAddress( + $this->local_host, + $this->local_port + ); + } + + // + // open the socket + // + if ($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->open() === false) { + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + } + + // + // write the data to the socket; if it fails, continue on + // the while loop + // + if ($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->write($_data) === false) { + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // read the content, using select to wait for a response + // + $size = 0; + $result = null; + $response = null; + + // + // handle zone transfer requests differently than other requests. + // + if ($_axfr == true) { + $soa_count = 0; + + while (1) { + // + // read the data off the socket + // + $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read( + $size, + ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE + ); + + if (($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { + // + // if we get an error, then keeping this socket around for a future request, could cause + // an error- for example, https://github.com/mikepultz/netdns2/issues/61 + // + // in this case, the connection was timing out, which once it did finally respond, left + // data on the socket, which could be captured on a subsequent request. + // + // since there's no way to "reset" a socket, the only thing we can do it close it. + // + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // parse the first chunk as a packet + // + $chunk = new Net_DNS2_Packet_Response($result, $size); + + // + // if this is the first packet, then clone it directly, then + // go through it to see if there are two SOA records + // (indicating that it's the only packet) + // + if (is_null($response) == true) { + $response = clone $chunk; + + // + // look for a failed response; if the zone transfer + // failed, then we don't need to do anything else at this + // point, and we should just break out. + // + if ($response->header->rcode != Net_DNS2_Lookups::RCODE_NOERROR) { + break; + } + + // + // go through each answer + // + foreach ($response->answer as $index => $rr) { + // + // count the SOA records + // + if ($rr->type == 'SOA') { + ++$soa_count; + } + } + + // + // if we have 2 or more SOA records, then we're done; + // otherwise continue out so we read the rest of the + // packets off the socket + // + if ($soa_count >= 2) { + break; + } + + continue; + } + + // + // go through all these answers, and look for SOA records + // + foreach ($chunk->answer as $index => $rr) { + // + // count the number of SOA records we find + // + if ($rr->type == 'SOA') { + ++$soa_count; + } + + // + // add the records to a single response object + // + $response->answer[] = $rr; + } + + // + // if we've found the second SOA record, we're done + // + if ($soa_count >= 2) { + break; + } + } + + // + // everything other than a AXFR + // + } else { + $result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read( + $size, + ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE + ); + + if (($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { + $this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // create the packet object + // + $response = new Net_DNS2_Packet_Response($result, $size); + } + + // + // store the query time + // + $response->response_time = microtime(true) - $start_time; + + // + // add the name server that the response came from to the response object, + // and the socket type that was used. + // + $response->answer_from = $_ns; + $response->answer_socket_type = Net_DNS2_Socket::SOCK_STREAM; + + // + // return the Net_DNS2_Packet_Response object + // + return $response; + } + + /** + * sends a DNS request using UDP. + * + * @param string $_ns the name server to use for the request + * @param string $_data the raw DNS packet data + * + * @return Net_DNS2_Packet_Response the response object + * + * @throws Net_DNS2_Exception + */ + private function sendUDPRequest($_ns, $_data) { + // + // grab the start time + // + $start_time = microtime(true); + + // + // see if we already have an open socket from a previous request; if so, try to use + // that instead of opening a new one. + // + if ((!isset($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns])) + || (!$this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] instanceof Net_DNS2_Socket) + ) { + // + // create the socket object + // + $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] = new Net_DNS2_Socket( + Net_DNS2_Socket::SOCK_DGRAM, + $_ns, + $this->dns_port, + $this->timeout + ); + + // + // if a local IP address / port is set, then add it + // + if (strlen($this->local_host) > 0) { + $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->bindAddress( + $this->local_host, + $this->local_port + ); + } + + // + // open the socket + // + if ($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->open() === false) { + $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + } + + // + // write the data to the socket + // + if ($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->write($_data) === false) { + $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // read the content, using select to wait for a response + // + $size = 0; + + $result = $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->read( + $size, + ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE + ); + + if (($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) { + $this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED); + } + + // + // create the packet object + // + $response = new Net_DNS2_Packet_Response($result, $size); + + // + // store the query time + // + $response->response_time = microtime(true) - $start_time; + + // + // add the name server that the response came from to the response object, + // and the socket type that was used. + // + $response->answer_from = $_ns; + $response->answer_socket_type = Net_DNS2_Socket::SOCK_DGRAM; + + // + // return the Net_DNS2_Packet_Response object + // + return $response; + } } diff --git a/Net/DNS2/BitMap.php b/Net/DNS2/BitMap.php index 9172b1c9..e07d8ac2 100644 --- a/Net/DNS2/BitMap.php +++ b/Net/DNS2/BitMap.php @@ -21,166 +21,167 @@ * a class to handle converting RR bitmaps to arrays and back; used on NSEC * and NSEC3 RR's. */ -class Net_DNS2_BitMap -{ - /** - * parses a RR bitmap field defined in RFC3845, into an array of RR names. - * - * Type Bit Map(s) Field = ( Window Block # | Bitmap Length | Bitmap ) + - * - * @param string $data a bitmap stringto parse - * - * @return array - */ - public static function bitMapToArray($data) - { - if (0 == strlen($data)) { - return []; - } - - $output = []; - $offset = 0; - $length = strlen($data); - - while ($offset < $length) { - // - // unpack the window and length values - // - $x = unpack('@'.$offset.'/Cwindow/Clength', $data); - $offset += 2; - - // - // copy out the bitmap value - // - $bitmap = unpack('C*', substr($data, $offset, $x['length'])); - $offset += $x['length']; - - // - // I'm not sure if there's a better way of doing this, but PHP doesn't - // have a 'B' flag for unpack() - // - $bitstr = ''; - foreach ($bitmap as $r) { - $bitstr .= sprintf('%08b', $r); - } - - $blen = strlen($bitstr); - for ($i = 0; $i < $blen; ++$i) { - if ('1' == $bitstr[$i]) { - $type = $x['window'] * 256 + $i; - - if (isset(Net_DNS2_Lookups::$rr_types_by_id[$type])) { - $output[] = Net_DNS2_Lookups::$rr_types_by_id[$type]; - } else { - $output[] = 'TYPE'.$type; - } - } - } - } - - return $output; - } - - /** - * builds a RR Bit map from an array of RR type names. - * - * @param array $data a list of RR names - * - * @return string - */ - public static function arrayToBitMap(array $data) - { - if (0 == cacti_sizeof($data)) { - return ''; - } - - $current_window = 0; - - // - // go through each RR - // - $max = 0; - $bm = []; - - foreach ($data as $rr) { - $rr = strtoupper($rr); - - // - // get the type id for the RR - // - $type = @Net_DNS2_Lookups::$rr_types_by_name[$rr]; - if (isset($type)) { - // - // skip meta types or qtypes - // - if ((isset(Net_DNS2_Lookups::$rr_qtypes_by_id[$type])) - || (isset(Net_DNS2_Lookups::$rr_metatypes_by_id[$type])) - ) { - continue; - } - } else { - // - // if it's not found, then it must be defined as TYPE, per - // RFC3845 section 2.2, if it's not, we ignore it. - // - list($name, $type) = explode('TYPE', $rr); - if (!isset($type)) { - continue; - } - } - - // - // build the current window - // - $current_window = (int) ($type / 256); - - $val = $type - $current_window * 256.0; - if ($val > $max) { - $max = $val; - } - - $bm[$current_window][$val] = 1; - $bm[$current_window]['length'] = ceil(($max + 1) / 8); - } - - $output = ''; - - foreach ($bm as $window => $bitdata) { - $bitstr = ''; - - for ($i = 0; $i < $bm[$window]['length'] * 8; ++$i) { - if (isset($bm[$window][$i])) { - $bitstr .= '1'; - } else { - $bitstr .= '0'; - } - } - - $output .= pack('CC', $window, $bm[$window]['length']); - $output .= pack('H*', self::bigBaseConvert($bitstr)); - } - - return $output; - } - - /** - * a base_convert that handles large numbers; forced to 2/16. - * - * @param string $number a bit string - * - * @return string - */ - public static function bigBaseConvert($number) - { - $result = ''; - - $bin = substr(chunk_split(strrev($number), 4, '-'), 0, -1); - $temp = preg_split('[-]', $bin, -1, PREG_SPLIT_DELIM_CAPTURE); - - for ($i = cacti_sizeof($temp) - 1; $i >= 0; --$i) { - $result = $result.base_convert(strrev($temp[$i]), 2, 16); - } - - return strtoupper($result); - } +class Net_DNS2_BitMap { + /** + * parses a RR bitmap field defined in RFC3845, into an array of RR names. + * + * Type Bit Map(s) Field = ( Window Block # | Bitmap Length | Bitmap ) + + * + * @param string $data a bitmap stringto parse + * + * @return array + */ + public static function bitMapToArray($data) { + if (strlen($data) == 0) { + return []; + } + + $output = []; + $offset = 0; + $length = strlen($data); + + while ($offset < $length) { + // + // unpack the window and length values + // + $x = unpack('@' . $offset . '/Cwindow/Clength', $data); + $offset += 2; + + // + // copy out the bitmap value + // + $bitmap = unpack('C*', substr($data, $offset, $x['length'])); + $offset += $x['length']; + + // + // I'm not sure if there's a better way of doing this, but PHP doesn't + // have a 'B' flag for unpack() + // + $bitstr = ''; + + foreach ($bitmap as $r) { + $bitstr .= sprintf('%08b', $r); + } + + $blen = strlen($bitstr); + + for ($i = 0; $i < $blen; ++$i) { + if ($bitstr[$i] == '1') { + $type = $x['window'] * 256 + $i; + + if (isset(Net_DNS2_Lookups::$rr_types_by_id[$type])) { + $output[] = Net_DNS2_Lookups::$rr_types_by_id[$type]; + } else { + $output[] = 'TYPE' . $type; + } + } + } + } + + return $output; + } + + /** + * builds a RR Bit map from an array of RR type names. + * + * @param array $data a list of RR names + * + * @return string + */ + public static function arrayToBitMap(array $data) { + if (cacti_sizeof($data) == 0) { + return ''; + } + + $current_window = 0; + + // + // go through each RR + // + $max = 0; + $bm = []; + + foreach ($data as $rr) { + $rr = strtoupper($rr); + + // + // get the type id for the RR + // + $type = @Net_DNS2_Lookups::$rr_types_by_name[$rr]; + + if (isset($type)) { + // + // skip meta types or qtypes + // + if ((isset(Net_DNS2_Lookups::$rr_qtypes_by_id[$type])) + || (isset(Net_DNS2_Lookups::$rr_metatypes_by_id[$type])) + ) { + continue; + } + } else { + // + // if it's not found, then it must be defined as TYPE, per + // RFC3845 section 2.2, if it's not, we ignore it. + // + [$name, $type] = explode('TYPE', $rr); + + if (!isset($type)) { + continue; + } + } + + // + // build the current window + // + $current_window = (int) ($type / 256); + + $val = $type - $current_window * 256.0; + + if ($val > $max) { + $max = $val; + } + + $bm[$current_window][$val] = 1; + $bm[$current_window]['length'] = ceil(($max + 1) / 8); + } + + $output = ''; + + foreach ($bm as $window => $bitdata) { + $bitstr = ''; + + for ($i = 0; $i < $bm[$window]['length'] * 8; ++$i) { + if (isset($bm[$window][$i])) { + $bitstr .= '1'; + } else { + $bitstr .= '0'; + } + } + + $output .= pack('CC', $window, $bm[$window]['length']); + $output .= pack('H*', self::bigBaseConvert($bitstr)); + } + + return $output; + } + + /** + * a base_convert that handles large numbers; forced to 2/16. + * + * @param string $number a bit string + * + * @return string + */ + public static function bigBaseConvert($number) { + $result = ''; + + $bin = substr(chunk_split(strrev($number), 4, '-'), 0, -1); + $temp = preg_split('[-]', $bin, -1, PREG_SPLIT_DELIM_CAPTURE); + + for ($i = cacti_sizeof($temp) - 1; $i >= 0; --$i) { + $result = $result . base_convert(strrev($temp[$i]), 2, 16); + } + + return strtoupper($result); + } } diff --git a/Net/DNS2/Cache.php b/Net/DNS2/Cache.php index 97a2769a..4d08bc2d 100644 --- a/Net/DNS2/Cache.php +++ b/Net/DNS2/Cache.php @@ -20,206 +20,202 @@ /** * A class to provide simple dns lookup caching. */ -class Net_DNS2_Cache -{ - // the filename of the cache file - protected $cache_file = ''; - - // the local data store for the cache - protected $cache_data = []; - - // the size of the cache to use - protected $cache_size = 0; - - // the cache serializer - protected $cache_serializer; - - /* - * an internal flag to make sure we don't load the cache content more - * than once per instance. - */ - protected $cache_opened = false; - - /** - * returns true/false if the provided key is defined in the cache. - * - * @param string $key the key to lookup in the local cache - * - * @return bool - */ - public function has($key) - { - return isset($this->cache_data[$key]); - } - - /** - * returns the value for the given key. - * - * @param string $key the key to lookup in the local cache - * - * @return mixed returns the cache data on success, false on error - */ - public function get($key) - { - if (isset($this->cache_data[$key])) { - if ('json' == $this->cache_serializer) { - return json_decode($this->cache_data[$key]['object']); - } - - return unserialize($this->cache_data[$key]['object']); - } - - return false; - } - - /** - * adds a new key/value pair to the cache. - * - * @param string $key the key for the new cache entry - * @param mixed $data the data to store in cache - */ - public function put($key, $data) - { - $ttl = 86400 * 365; - - // - // clear the rdata values - // - $data->rdata = ''; - $data->rdlength = 0; - - // - // find the lowest TTL, and use that as the TTL for the whole cached - // object. The downside to using one TTL for the whole object, is that - // we'll invalidate entries before they actually expire, causing a - // real lookup to happen. - // - // The upside is that we don't need to require() each RR type in the - // cache, so we can look at their individual TTL's on each run- we only - // unserialize the actual RR object when it's get() from the cache. - // - foreach ($data->answer as $index => $rr) { - if ($rr->ttl < $ttl) { - $ttl = $rr->ttl; - } - - $rr->rdata = ''; - $rr->rdlength = 0; - } - foreach ($data->authority as $index => $rr) { - if ($rr->ttl < $ttl) { - $ttl = $rr->ttl; - } - - $rr->rdata = ''; - $rr->rdlength = 0; - } - foreach ($data->additional as $index => $rr) { - if ($rr->ttl < $ttl) { - $ttl = $rr->ttl; - } - - $rr->rdata = ''; - $rr->rdlength = 0; - } - - $this->cache_data[$key] = [ - 'cache_date' => time(), - 'ttl' => $ttl, - ]; - - if ('json' == $this->cache_serializer) { - $this->cache_data[$key]['object'] = json_encode($data); - } else { - $this->cache_data[$key]['object'] = serialize($data); - } - } - - /** - * runs a clean up process on the cache data. - */ - protected function clean() - { - if (cacti_sizeof($this->cache_data) > 0) { - // - // go through each entry and adjust their TTL, and remove entries that - // have expired - // - $now = time(); - - foreach ($this->cache_data as $key => $data) { - $diff = $now - $data['cache_date']; - - if ($data['ttl'] <= $diff) { - unset($this->cache_data[$key]); - } else { - $this->cache_data[$key]['ttl'] -= $diff; - $this->cache_data[$key]['cache_date'] = $now; - } - } - } - } - - /** - * runs a clean up process on the cache data. - * - * @return mixed - */ - protected function resize() - { - if (cacti_sizeof($this->cache_data) > 0) { - // - // serialize the cache data - // - if ('json' == $this->cache_serializer) { - $cache = json_encode($this->cache_data); - } else { - $cache = serialize($this->cache_data); - } - - // - // only do this part if the size allocated to the cache storage - // is smaller than the actual cache data - // - if (strlen($cache) > $this->cache_size) { - while (strlen($cache) > $this->cache_size) { - // - // go through the data, and remove the entries closed to - // their expiration date. - // - $smallest_ttl = time(); - $smallest_key = null; - - foreach ($this->cache_data as $key => $data) { - if ($data['ttl'] < $smallest_ttl) { - $smallest_ttl = $data['ttl']; - $smallest_key = $key; - } - } - - // - // unset the key with the smallest TTL - // - unset($this->cache_data[$smallest_key]); - - // - // re-serialize - // - if ('json' == $this->cache_serializer) { - $cache = json_encode($this->cache_data); - } else { - $cache = serialize($this->cache_data); - } - } - } - - if (('a:0:{}' == $cache) || ('{}' == $cache)) { - return null; - } - - return $cache; - } - - return null; - } +class Net_DNS2_Cache { + // the filename of the cache file + protected $cache_file = ''; + + // the local data store for the cache + protected $cache_data = []; + + // the size of the cache to use + protected $cache_size = 0; + + // the cache serializer + protected $cache_serializer; + + /* + * an internal flag to make sure we don't load the cache content more + * than once per instance. + */ + protected $cache_opened = false; + + /** + * returns true/false if the provided key is defined in the cache. + * + * @param string $key the key to lookup in the local cache + * + * @return bool + */ + public function has($key) { + return isset($this->cache_data[$key]); + } + + /** + * returns the value for the given key. + * + * @param string $key the key to lookup in the local cache + * + * @return mixed returns the cache data on success, false on error + */ + public function get($key) { + if (isset($this->cache_data[$key])) { + if ($this->cache_serializer == 'json') { + return json_decode($this->cache_data[$key]['object']); + } + + return unserialize($this->cache_data[$key]['object']); + } + + return false; + } + + /** + * adds a new key/value pair to the cache. + * + * @param string $key the key for the new cache entry + * @param mixed $data the data to store in cache + */ + public function put($key, $data) { + $ttl = 86400 * 365; + + // + // clear the rdata values + // + $data->rdata = ''; + $data->rdlength = 0; + + // + // find the lowest TTL, and use that as the TTL for the whole cached + // object. The downside to using one TTL for the whole object, is that + // we'll invalidate entries before they actually expire, causing a + // real lookup to happen. + // + // The upside is that we don't need to require() each RR type in the + // cache, so we can look at their individual TTL's on each run- we only + // unserialize the actual RR object when it's get() from the cache. + // + foreach ($data->answer as $index => $rr) { + if ($rr->ttl < $ttl) { + $ttl = $rr->ttl; + } + + $rr->rdata = ''; + $rr->rdlength = 0; + } + + foreach ($data->authority as $index => $rr) { + if ($rr->ttl < $ttl) { + $ttl = $rr->ttl; + } + + $rr->rdata = ''; + $rr->rdlength = 0; + } + + foreach ($data->additional as $index => $rr) { + if ($rr->ttl < $ttl) { + $ttl = $rr->ttl; + } + + $rr->rdata = ''; + $rr->rdlength = 0; + } + + $this->cache_data[$key] = [ + 'cache_date' => time(), + 'ttl' => $ttl, + ]; + + if ($this->cache_serializer == 'json') { + $this->cache_data[$key]['object'] = json_encode($data); + } else { + $this->cache_data[$key]['object'] = serialize($data); + } + } + + /** + * runs a clean up process on the cache data. + */ + protected function clean() { + if (cacti_sizeof($this->cache_data) > 0) { + // + // go through each entry and adjust their TTL, and remove entries that + // have expired + // + $now = time(); + + foreach ($this->cache_data as $key => $data) { + $diff = $now - $data['cache_date']; + + if ($data['ttl'] <= $diff) { + unset($this->cache_data[$key]); + } else { + $this->cache_data[$key]['ttl'] -= $diff; + $this->cache_data[$key]['cache_date'] = $now; + } + } + } + } + + /** + * runs a clean up process on the cache data. + * + * @return mixed + */ + protected function resize() { + if (cacti_sizeof($this->cache_data) > 0) { + // + // serialize the cache data + // + if ($this->cache_serializer == 'json') { + $cache = json_encode($this->cache_data); + } else { + $cache = serialize($this->cache_data); + } + + // + // only do this part if the size allocated to the cache storage + // is smaller than the actual cache data + // + if (strlen($cache) > $this->cache_size) { + while (strlen($cache) > $this->cache_size) { + // + // go through the data, and remove the entries closed to + // their expiration date. + // + $smallest_ttl = time(); + $smallest_key = null; + + foreach ($this->cache_data as $key => $data) { + if ($data['ttl'] < $smallest_ttl) { + $smallest_ttl = $data['ttl']; + $smallest_key = $key; + } + } + + // + // unset the key with the smallest TTL + // + unset($this->cache_data[$smallest_key]); + + // + // re-serialize + // + if ($this->cache_serializer == 'json') { + $cache = json_encode($this->cache_data); + } else { + $cache = serialize($this->cache_data); + } + } + } + + if (($cache == 'a:0:{}') || ($cache == '{}')) { + return null; + } + + return $cache; + } + + return null; + } } diff --git a/Net/DNS2/Cache/File.php b/Net/DNS2/Cache/File.php index 00992419..d7c5a706 100644 --- a/Net/DNS2/Cache/File.php +++ b/Net/DNS2/Cache/File.php @@ -20,162 +20,163 @@ /** * File-based caching for the Net_DNS2_Cache class. */ -class Net_DNS2_Cache_File extends Net_DNS2_Cache -{ - /** - * Destructor. - */ - public function __destruct() - { - // - // if there's no cache file set, then there's nothing to do - // - if (0 == strlen($this->cache_file)) { - return; - } - - // - // open the file for reading/writing - // - $fp = fopen($this->cache_file, 'a+'); - if (false !== $fp) { - // - // lock the file just in case - // - flock($fp, LOCK_EX); - - // - // seek to the start of the file to read - // - fseek($fp, 0, SEEK_SET); - - // - // read the file contents - // - $data = @fread($fp, filesize($this->cache_file)); - if ((false !== $data) && (strlen($data) > 0)) { - // - // unserialize and store the data - // - $c = $this->cache_data; - - $decoded = null; - - if ('json' == $this->cache_serializer) { - $decoded = json_decode($data, true); - } else { - $decoded = unserialize($data); - } - - if (true == is_array($decoded)) { - $this->cache_data = array_merge($c, $decoded); - } - } - - // - // trucate the file - // - ftruncate($fp, 0); - - // - // clean the data - // - $this->clean(); - - // - // resize the data - // - $data = $this->resize(); - if (!is_null($data)) { - // - // write the file contents - // - fwrite($fp, $data); - } - - // - // unlock - // - flock($fp, LOCK_UN); - - // - // close the file - // - fclose($fp); - } - } - - /** - * open a cache object. - * - * @param string $cache_file path to a file to use for cache storage - * @param int $size the size of the shared memory segment to create - * @param string $serializer the name of the cache serialize to use - * - * @throws Net_DNS2_Exception - */ - public function open($cache_file, $size, $serializer) - { - $this->cache_size = $size; - $this->cache_file = $cache_file; - $this->cache_serializer = $serializer; - - // - // check that the file exists first - // - if ((false == $this->cache_opened) - && (true == file_exists($this->cache_file)) - && (filesize($this->cache_file) > 0) - ) { - // - // open the file for reading - // - $fp = @fopen($this->cache_file, 'r'); - if (false !== $fp) { - // - // lock the file just in case - // - flock($fp, LOCK_EX); - - // - // read the file contents - // - $data = fread($fp, filesize($this->cache_file)); - - $decoded = null; - - if ('json' == $this->cache_serializer) { - $decoded = json_decode($data, true); - } else { - $decoded = unserialize($data); - } - - if (true == is_array($decoded)) { - $this->cache_data = $decoded; - } else { - $this->cache_data = []; - } - - // - // unlock - // - flock($fp, LOCK_UN); - - // - // close the file - // - fclose($fp); - - // - // clean up the data - // - $this->clean(); - - // - // mark this so we don't read this contents more than once per instance. - // - $this->cache_opened = true; - } - } - } +class Net_DNS2_Cache_File extends Net_DNS2_Cache { + /** + * Destructor. + */ + public function __destruct() { + // + // if there's no cache file set, then there's nothing to do + // + if (strlen($this->cache_file) == 0) { + return; + } + + // + // open the file for reading/writing + // + $fp = fopen($this->cache_file, 'a+'); + + if ($fp !== false) { + // + // lock the file just in case + // + flock($fp, LOCK_EX); + + // + // seek to the start of the file to read + // + fseek($fp, 0, SEEK_SET); + + // + // read the file contents + // + $data = @fread($fp, filesize($this->cache_file)); + + if (($data !== false) && (strlen($data) > 0)) { + // + // unserialize and store the data + // + $c = $this->cache_data; + + $decoded = null; + + if ($this->cache_serializer == 'json') { + $decoded = json_decode($data, true); + } else { + $decoded = unserialize($data); + } + + if (is_array($decoded) == true) { + $this->cache_data = array_merge($c, $decoded); + } + } + + // + // trucate the file + // + ftruncate($fp, 0); + + // + // clean the data + // + $this->clean(); + + // + // resize the data + // + $data = $this->resize(); + + if (!is_null($data)) { + // + // write the file contents + // + fwrite($fp, $data); + } + + // + // unlock + // + flock($fp, LOCK_UN); + + // + // close the file + // + fclose($fp); + } + } + + /** + * open a cache object. + * + * @param string $cache_file path to a file to use for cache storage + * @param int $size the size of the shared memory segment to create + * @param string $serializer the name of the cache serialize to use + * + * @throws Net_DNS2_Exception + */ + public function open($cache_file, $size, $serializer) { + $this->cache_size = $size; + $this->cache_file = $cache_file; + $this->cache_serializer = $serializer; + + // + // check that the file exists first + // + if (($this->cache_opened == false) + && (file_exists($this->cache_file) == true) + && (filesize($this->cache_file) > 0) + ) { + // + // open the file for reading + // + $fp = @fopen($this->cache_file, 'r'); + + if ($fp !== false) { + // + // lock the file just in case + // + flock($fp, LOCK_EX); + + // + // read the file contents + // + $data = fread($fp, filesize($this->cache_file)); + + $decoded = null; + + if ($this->cache_serializer == 'json') { + $decoded = json_decode($data, true); + } else { + $decoded = unserialize($data); + } + + if (is_array($decoded) == true) { + $this->cache_data = $decoded; + } else { + $this->cache_data = []; + } + + // + // unlock + // + flock($fp, LOCK_UN); + + // + // close the file + // + fclose($fp); + + // + // clean up the data + // + $this->clean(); + + // + // mark this so we don't read this contents more than once per instance. + // + $this->cache_opened = true; + } + } + } } diff --git a/Net/DNS2/Cache/Shm.php b/Net/DNS2/Cache/Shm.php index 38b9c42c..fff5a655 100644 --- a/Net/DNS2/Cache/Shm.php +++ b/Net/DNS2/Cache/Shm.php @@ -20,230 +20,235 @@ /** * Shared Memory-based caching for the Net_DNS2_Cache class. */ -class Net_DNS2_Cache_Shm extends Net_DNS2_Cache -{ - // resource id of the shared memory cache - private $_cache_id = false; - - // the IPC key - private $_cache_file_tok = -1; - - /** - * Destructor. - */ - public function __destruct() - { - // - // if there's no cache file set, then there's nothing to do - // - if (0 == strlen($this->cache_file)) { - return; - } - - $fp = fopen($this->cache_file, 'r'); - if (false !== $fp) { - // - // lock the file - // - flock($fp, LOCK_EX); - - // - // check to see if we have an open shm segment - // - if (false === $this->_cache_id) { - // - // try opening it again, incase it was created by another - // process in the mean time - // - $this->_cache_id = @shmop_open( - $this->_cache_file_tok, - 'w', - 0, - 0 - ); - if (false === $this->_cache_id) { - // - // otherwise, create it. - // - $this->_cache_id = @shmop_open( - $this->_cache_file_tok, - 'c', - 0, - $this->cache_size - ); - } - } - - // - // get the size allocated to the segment - // - $allocated = shmop_size($this->_cache_id); - - // - // read the contents - // - $data = trim(shmop_read($this->_cache_id, 0, $allocated)); - - // - // if there was some data - // - if ((false !== $data) && (strlen($data) > 0)) { - // - // unserialize and store the data - // - $c = $this->cache_data; - - $decoded = null; - - if ('json' == $this->cache_serializer) { - $decoded = json_decode($data, true); - } else { - $decoded = unserialize($data); - } - - if (true == is_array($decoded)) { - $this->cache_data = array_merge($c, $decoded); - } - } - - // - // delete the segment - // - shmop_delete($this->_cache_id); - - // - // clean the data - // - $this->clean(); - - // - // clean up and write the data - // - $data = $this->resize(); - if (!is_null($data)) { - // - // re-create segment - // - $this->_cache_id = @shmop_open( - $this->_cache_file_tok, - 'c', - 0644, - $this->cache_size - ); - if (false === $this->_cache_id) { - return; - } - - $o = shmop_write($this->_cache_id, $data, 0); - } - - // - // close the segment - // - shmop_close($this->_cache_id); - - // - // unlock - // - flock($fp, LOCK_UN); - - // - // close the file - // - fclose($fp); - } - } - - /** - * open a cache object. - * - * @param string $cache_file path to a file to use for cache storage - * @param int $size the size of the shared memory segment to create - * @param string $serializer the name of the cache serialize to use - * - * @throws Net_DNS2_Exception - */ - public function open($cache_file, $size, $serializer) - { - $this->cache_size = $size; - $this->cache_file = $cache_file; - $this->cache_serializer = $serializer; - - // - // if we've already loaded the cache data, then just return right away - // - if (true == $this->cache_opened) { - return; - } - - // - // make sure the file exists first - // - if (!file_exists($cache_file)) { - if (false === file_put_contents($cache_file, '')) { - throw new Net_DNS2_Exception( - 'failed to create empty SHM file: '.$cache_file, - Net_DNS2_Lookups::E_CACHE_SHM_FILE - ); - } - } - - // - // convert the filename to a IPC key - // - $this->_cache_file_tok = ftok($cache_file, 't'); - if (-1 == $this->_cache_file_tok) { - throw new Net_DNS2_Exception( - 'failed on ftok() file: '.$this->_cache_file_tok, - Net_DNS2_Lookups::E_CACHE_SHM_FILE - ); - } - - // - // try to open an existing cache; if it doesn't exist, then there's no - // cache, and nothing to do. - // - $this->_cache_id = @shmop_open($this->_cache_file_tok, 'w', 0, 0); - if (false !== $this->_cache_id) { - // - // this returns the size allocated, and not the size used, but it's - // still a good check to make sure there's space allocated. - // - $allocated = shmop_size($this->_cache_id); - if ($allocated > 0) { - // - // read the data from the shared memory segment - // - $data = trim(shmop_read($this->_cache_id, 0, $allocated)); - if ((false !== $data) && (strlen($data) > 0)) { - // - // unserialize and store the data - // - $decoded = null; - - if ('json' == $this->cache_serializer) { - $decoded = json_decode($data, true); - } else { - $decoded = unserialize($data); - } - - if (true == is_array($decoded)) { - $this->cache_data = $decoded; - } else { - $this->cache_data = []; - } - - // - // call clean to clean up old entries - // - $this->clean(); - - // - // mark the cache as loaded, so we don't load it more than once - // - $this->cache_opened = true; - } - } - } - } +class Net_DNS2_Cache_Shm extends Net_DNS2_Cache { + // resource id of the shared memory cache + private $_cache_id = false; + + // the IPC key + private $_cache_file_tok = -1; + + /** + * Destructor. + */ + public function __destruct() { + // + // if there's no cache file set, then there's nothing to do + // + if (strlen($this->cache_file) == 0) { + return; + } + + $fp = fopen($this->cache_file, 'r'); + + if ($fp !== false) { + // + // lock the file + // + flock($fp, LOCK_EX); + + // + // check to see if we have an open shm segment + // + if ($this->_cache_id === false) { + // + // try opening it again, incase it was created by another + // process in the mean time + // + $this->_cache_id = @shmop_open( + $this->_cache_file_tok, + 'w', + 0, + 0 + ); + + if ($this->_cache_id === false) { + // + // otherwise, create it. + // + $this->_cache_id = @shmop_open( + $this->_cache_file_tok, + 'c', + 0, + $this->cache_size + ); + } + } + + // + // get the size allocated to the segment + // + $allocated = shmop_size($this->_cache_id); + + // + // read the contents + // + $data = trim(shmop_read($this->_cache_id, 0, $allocated)); + + // + // if there was some data + // + if (($data !== false) && (strlen($data) > 0)) { + // + // unserialize and store the data + // + $c = $this->cache_data; + + $decoded = null; + + if ($this->cache_serializer == 'json') { + $decoded = json_decode($data, true); + } else { + $decoded = unserialize($data); + } + + if (is_array($decoded) == true) { + $this->cache_data = array_merge($c, $decoded); + } + } + + // + // delete the segment + // + shmop_delete($this->_cache_id); + + // + // clean the data + // + $this->clean(); + + // + // clean up and write the data + // + $data = $this->resize(); + + if (!is_null($data)) { + // + // re-create segment + // + $this->_cache_id = @shmop_open( + $this->_cache_file_tok, + 'c', + 0644, + $this->cache_size + ); + + if ($this->_cache_id === false) { + return; + } + + $o = shmop_write($this->_cache_id, $data, 0); + } + + // + // close the segment + // + shmop_close($this->_cache_id); + + // + // unlock + // + flock($fp, LOCK_UN); + + // + // close the file + // + fclose($fp); + } + } + + /** + * open a cache object. + * + * @param string $cache_file path to a file to use for cache storage + * @param int $size the size of the shared memory segment to create + * @param string $serializer the name of the cache serialize to use + * + * @throws Net_DNS2_Exception + */ + public function open($cache_file, $size, $serializer) { + $this->cache_size = $size; + $this->cache_file = $cache_file; + $this->cache_serializer = $serializer; + + // + // if we've already loaded the cache data, then just return right away + // + if ($this->cache_opened == true) { + return; + } + + // + // make sure the file exists first + // + if (!file_exists($cache_file)) { + if (file_put_contents($cache_file, '') === false) { + throw new Net_DNS2_Exception( + 'failed to create empty SHM file: ' . $cache_file, + Net_DNS2_Lookups::E_CACHE_SHM_FILE + ); + } + } + + // + // convert the filename to a IPC key + // + $this->_cache_file_tok = ftok($cache_file, 't'); + + if ($this->_cache_file_tok == -1) { + throw new Net_DNS2_Exception( + 'failed on ftok() file: ' . $this->_cache_file_tok, + Net_DNS2_Lookups::E_CACHE_SHM_FILE + ); + } + + // + // try to open an existing cache; if it doesn't exist, then there's no + // cache, and nothing to do. + // + $this->_cache_id = @shmop_open($this->_cache_file_tok, 'w', 0, 0); + + if ($this->_cache_id !== false) { + // + // this returns the size allocated, and not the size used, but it's + // still a good check to make sure there's space allocated. + // + $allocated = shmop_size($this->_cache_id); + + if ($allocated > 0) { + // + // read the data from the shared memory segment + // + $data = trim(shmop_read($this->_cache_id, 0, $allocated)); + + if (($data !== false) && (strlen($data) > 0)) { + // + // unserialize and store the data + // + $decoded = null; + + if ($this->cache_serializer == 'json') { + $decoded = json_decode($data, true); + } else { + $decoded = unserialize($data); + } + + if (is_array($decoded) == true) { + $this->cache_data = $decoded; + } else { + $this->cache_data = []; + } + + // + // call clean to clean up old entries + // + $this->clean(); + + // + // mark the cache as loaded, so we don't load it more than once + // + $this->cache_opened = true; + } + } + } + } } diff --git a/Net/DNS2/Exception.php b/Net/DNS2/Exception.php index 0e802757..3a4d1f18 100644 --- a/Net/DNS2/Exception.php +++ b/Net/DNS2/Exception.php @@ -20,69 +20,66 @@ /** * Exception handler used by Net_DNS2. */ -class Net_DNS2_Exception extends Exception -{ - private $_request; - private $_response; +class Net_DNS2_Exception extends Exception { + private $_request; + private $_response; - /** - * Constructor - overload the constructor so we can pass in the request - * and response object (when it's available). - * - * @param string $message the exception message - * @param int $code the exception code - * @param object $previous the previous Exception object - * @param object $request the Net_DNS2_Packet_Request object for this request - * @param object $response the Net_DNS2_Packet_Response object for this request - */ - public function __construct( - $message = '', - $code = 0, - $previous = null, - ?Net_DNS2_Packet_Request $request = null, - ?Net_DNS2_Packet_Response $response = null - ) { - // - // store the request/response objects (if passed) - // - $this->_request = $request; - $this->_response = $response; + /** + * Constructor - overload the constructor so we can pass in the request + * and response object (when it's available). + * + * @param string $message the exception message + * @param int $code the exception code + * @param object $previous the previous Exception object + * @param object $request the Net_DNS2_Packet_Request object for this request + * @param object $response the Net_DNS2_Packet_Response object for this request + */ + public function __construct( + $message = '', + $code = 0, + $previous = null, + ?Net_DNS2_Packet_Request $request = null, + ?Net_DNS2_Packet_Response $response = null + ) { + // + // store the request/response objects (if passed) + // + $this->_request = $request; + $this->_response = $response; - // - // call the parent constructor - // - // the "previous" argument was added in PHP 5.3.0 - // - // https://code.google.com/p/netdns2/issues/detail?id=25 - // - if (true == version_compare(PHP_VERSION, '5.3.0', '>=')) { - parent::__construct($message, $code, $previous); - } else { - parent::__construct($message, $code); - } - } + // + // call the parent constructor + // + // the "previous" argument was added in PHP 5.3.0 + // + // https://code.google.com/p/netdns2/issues/detail?id=25 + // + if (version_compare(PHP_VERSION, '5.3.0', '>=') == true) { + parent::__construct($message, $code, $previous); + } else { + parent::__construct($message, $code); + } + } - /** - * returns the Net_DNS2_Packet_Request object (if available). - * - * @return Net_DNS2_Packet_Request object - * - * @since function available since release 1.3.1 - */ - public function getRequest() - { - return $this->_request; - } + /** + * returns the Net_DNS2_Packet_Request object (if available). + * + * @return Net_DNS2_Packet_Request object + * + * @since function available since release 1.3.1 + */ + public function getRequest() { + return $this->_request; + } - /** - * returns the Net_DNS2_Packet_Response object (if available). - * - * @return Net_DNS2_Packet_Response object - * - * @since function available since release 1.3.1 - */ - public function getResponse() - { - return $this->_response; - } + /** + * returns the Net_DNS2_Packet_Response object (if available). + * + * @return Net_DNS2_Packet_Response object + * + * @since function available since release 1.3.1 + */ + public function getResponse() { + return $this->_response; + } } diff --git a/Net/DNS2/Header.php b/Net/DNS2/Header.php index b3229215..812aa796 100644 --- a/Net/DNS2/Header.php +++ b/Net/DNS2/Header.php @@ -41,175 +41,169 @@ * | ARCOUNT | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_Header -{ - public $id; // 16 bit - identifier - public $qr; // 1 bit - 0 = query, 1 = response - public $opcode; // 4 bit - op code - public $aa; // 1 bit - Authoritative Answer - public $tc; // 1 bit - Truncation - public $rd; // 1 bit - Recursion Desired - public $ra; // 1 bit - Recursion Available - public $z; // 1 bit - Reserved - public $ad; // 1 bit - Authentic Data (RFC4035) - public $cd; // 1 bit - Checking Disabled (RFC4035) - public $rcode; // 4 bit - Response code - public $qdcount; // 16 bit - entries in the question section - public $ancount; // 16 bit - resource records in the answer section - public $nscount; // 16 bit - name server rr in the authority records section - public $arcount; // 16 bit - rr's in the additional records section - - /** - * Constructor - builds a new Net_DNS2_Header object. - * - * @param mixed &$packet either a Net_DNS2_Packet object or null - * - * @throws Net_DNS2_Exception - */ - public function __construct(?Net_DNS2_Packet &$packet = null) - { - if (!is_null($packet)) { - $this->set($packet); - } else { - $this->id = $this->nextPacketId(); - $this->qr = Net_DNS2_Lookups::QR_QUERY; - $this->opcode = Net_DNS2_Lookups::OPCODE_QUERY; - $this->aa = 0; - $this->tc = 0; - $this->rd = 1; - $this->ra = 0; - $this->z = 0; - $this->ad = 0; - $this->cd = 0; - $this->rcode = Net_DNS2_Lookups::RCODE_NOERROR; - $this->qdcount = 1; - $this->ancount = 0; - $this->nscount = 0; - $this->arcount = 0; - } - } - - /** - * magic __toString() method to return the header as a string. - * - * @return string - */ - public function __toString() - { - $output = ";;\n;; Header:\n"; - - $output .= ";;\t id = ".$this->id."\n"; - $output .= ";;\t qr = ".$this->qr."\n"; - $output .= ";;\t opcode = ".$this->opcode."\n"; - $output .= ";;\t aa = ".$this->aa."\n"; - $output .= ";;\t tc = ".$this->tc."\n"; - $output .= ";;\t rd = ".$this->rd."\n"; - $output .= ";;\t ra = ".$this->ra."\n"; - $output .= ";;\t z = ".$this->z."\n"; - $output .= ";;\t ad = ".$this->ad."\n"; - $output .= ";;\t cd = ".$this->cd."\n"; - $output .= ";;\t rcode = ".$this->rcode."\n"; - $output .= ";;\t qdcount = ".$this->qdcount."\n"; - $output .= ";;\t ancount = ".$this->ancount."\n"; - $output .= ";;\t nscount = ".$this->nscount."\n"; - $output .= ";;\t arcount = ".$this->arcount."\n"; - - return $output; - } - - /** - * returns the next available packet id. - * - * @return int - */ - public function nextPacketId() - { - if (++Net_DNS2_Lookups::$next_packet_id > 65535) { - Net_DNS2_Lookups::$next_packet_id = 1; - } - - return Net_DNS2_Lookups::$next_packet_id; - } - - /** - * constructs a Net_DNS2_Header from a Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet Object - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function set(Net_DNS2_Packet &$packet) - { - // - // the header must be at least 12 bytes long. - // - if ($packet->rdlength < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - throw new Net_DNS2_Exception( - 'invalid header data provided; too small', - Net_DNS2_Lookups::E_HEADER_INVALID - ); - } - - $offset = 0; - - // - // parse the values - // - $this->id = ord($packet->rdata[$offset]) << 8 - | ord($packet->rdata[++$offset]); - - ++$offset; - $this->qr = (ord($packet->rdata[$offset]) >> 7) & 0x1; - $this->opcode = (ord($packet->rdata[$offset]) >> 3) & 0xF; - $this->aa = (ord($packet->rdata[$offset]) >> 2) & 0x1; - $this->tc = (ord($packet->rdata[$offset]) >> 1) & 0x1; - $this->rd = ord($packet->rdata[$offset]) & 0x1; - - ++$offset; - $this->ra = (ord($packet->rdata[$offset]) >> 7) & 0x1; - $this->z = (ord($packet->rdata[$offset]) >> 6) & 0x1; - $this->ad = (ord($packet->rdata[$offset]) >> 5) & 0x1; - $this->cd = (ord($packet->rdata[$offset]) >> 4) & 0x1; - $this->rcode = ord($packet->rdata[$offset]) & 0xF; - - $this->qdcount = ord($packet->rdata[++$offset]) << 8 - | ord($packet->rdata[++$offset]); - $this->ancount = ord($packet->rdata[++$offset]) << 8 - | ord($packet->rdata[++$offset]); - $this->nscount = ord($packet->rdata[++$offset]) << 8 - | ord($packet->rdata[++$offset]); - $this->arcount = ord($packet->rdata[++$offset]) << 8 - | ord($packet->rdata[++$offset]); - - // - // increment the internal offset - // - $packet->offset += Net_DNS2_Lookups::DNS_HEADER_SIZE; - - return true; - } - - /** - * returns a binary packed DNS Header. - * - * @param Net_DNS2_Packet &$packet Object - * - * @return string - */ - public function get(Net_DNS2_Packet &$packet) - { - $packet->offset += Net_DNS2_Lookups::DNS_HEADER_SIZE; - - return pack('n', $this->id) - .chr( - ($this->qr << 7) | ($this->opcode << 3) - | ($this->aa << 2) | ($this->tc << 1) | $this->rd - ) - .chr( - ($this->ra << 7) | ($this->ad << 5) | ($this->cd << 4) | $this->rcode - ) - .pack('n4', $this->qdcount, $this->ancount, $this->nscount, $this->arcount); - } +class Net_DNS2_Header { + public $id; // 16 bit - identifier + public $qr; // 1 bit - 0 = query, 1 = response + public $opcode; // 4 bit - op code + public $aa; // 1 bit - Authoritative Answer + public $tc; // 1 bit - Truncation + public $rd; // 1 bit - Recursion Desired + public $ra; // 1 bit - Recursion Available + public $z; // 1 bit - Reserved + public $ad; // 1 bit - Authentic Data (RFC4035) + public $cd; // 1 bit - Checking Disabled (RFC4035) + public $rcode; // 4 bit - Response code + public $qdcount; // 16 bit - entries in the question section + public $ancount; // 16 bit - resource records in the answer section + public $nscount; // 16 bit - name server rr in the authority records section + public $arcount; // 16 bit - rr's in the additional records section + + /** + * Constructor - builds a new Net_DNS2_Header object. + * + * @param mixed &$packet either a Net_DNS2_Packet object or null + * + * @throws Net_DNS2_Exception + */ + public function __construct(?Net_DNS2_Packet &$packet = null) { + if (!is_null($packet)) { + $this->set($packet); + } else { + $this->id = $this->nextPacketId(); + $this->qr = Net_DNS2_Lookups::QR_QUERY; + $this->opcode = Net_DNS2_Lookups::OPCODE_QUERY; + $this->aa = 0; + $this->tc = 0; + $this->rd = 1; + $this->ra = 0; + $this->z = 0; + $this->ad = 0; + $this->cd = 0; + $this->rcode = Net_DNS2_Lookups::RCODE_NOERROR; + $this->qdcount = 1; + $this->ancount = 0; + $this->nscount = 0; + $this->arcount = 0; + } + } + + /** + * magic __toString() method to return the header as a string. + * + * @return string + */ + public function __toString() { + $output = ";;\n;; Header:\n"; + + $output .= ";;\t id = " . $this->id . "\n"; + $output .= ";;\t qr = " . $this->qr . "\n"; + $output .= ";;\t opcode = " . $this->opcode . "\n"; + $output .= ";;\t aa = " . $this->aa . "\n"; + $output .= ";;\t tc = " . $this->tc . "\n"; + $output .= ";;\t rd = " . $this->rd . "\n"; + $output .= ";;\t ra = " . $this->ra . "\n"; + $output .= ";;\t z = " . $this->z . "\n"; + $output .= ";;\t ad = " . $this->ad . "\n"; + $output .= ";;\t cd = " . $this->cd . "\n"; + $output .= ";;\t rcode = " . $this->rcode . "\n"; + $output .= ";;\t qdcount = " . $this->qdcount . "\n"; + $output .= ";;\t ancount = " . $this->ancount . "\n"; + $output .= ";;\t nscount = " . $this->nscount . "\n"; + $output .= ";;\t arcount = " . $this->arcount . "\n"; + + return $output; + } + + /** + * returns the next available packet id. + * + * @return int + */ + public function nextPacketId() { + if (++Net_DNS2_Lookups::$next_packet_id > 65535) { + Net_DNS2_Lookups::$next_packet_id = 1; + } + + return Net_DNS2_Lookups::$next_packet_id; + } + + /** + * constructs a Net_DNS2_Header from a Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet Object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function set(Net_DNS2_Packet &$packet) { + // + // the header must be at least 12 bytes long. + // + if ($packet->rdlength < Net_DNS2_Lookups::DNS_HEADER_SIZE) { + throw new Net_DNS2_Exception( + 'invalid header data provided; too small', + Net_DNS2_Lookups::E_HEADER_INVALID + ); + } + + $offset = 0; + + // + // parse the values + // + $this->id = ord($packet->rdata[$offset]) << 8 + | ord($packet->rdata[++$offset]); + + ++$offset; + $this->qr = (ord($packet->rdata[$offset]) >> 7) & 0x1; + $this->opcode = (ord($packet->rdata[$offset]) >> 3) & 0xF; + $this->aa = (ord($packet->rdata[$offset]) >> 2) & 0x1; + $this->tc = (ord($packet->rdata[$offset]) >> 1) & 0x1; + $this->rd = ord($packet->rdata[$offset]) & 0x1; + + ++$offset; + $this->ra = (ord($packet->rdata[$offset]) >> 7) & 0x1; + $this->z = (ord($packet->rdata[$offset]) >> 6) & 0x1; + $this->ad = (ord($packet->rdata[$offset]) >> 5) & 0x1; + $this->cd = (ord($packet->rdata[$offset]) >> 4) & 0x1; + $this->rcode = ord($packet->rdata[$offset]) & 0xF; + + $this->qdcount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + $this->ancount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + $this->nscount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + $this->arcount = ord($packet->rdata[++$offset]) << 8 + | ord($packet->rdata[++$offset]); + + // + // increment the internal offset + // + $packet->offset += Net_DNS2_Lookups::DNS_HEADER_SIZE; + + return true; + } + + /** + * returns a binary packed DNS Header. + * + * @param Net_DNS2_Packet &$packet Object + * + * @return string + */ + public function get(Net_DNS2_Packet &$packet) { + $packet->offset += Net_DNS2_Lookups::DNS_HEADER_SIZE; + + return pack('n', $this->id) + . chr( + ($this->qr << 7) | ($this->opcode << 3) + | ($this->aa << 2) | ($this->tc << 1) | $this->rd + ) + . chr( + ($this->ra << 7) | ($this->ad << 5) | ($this->cd << 4) | $this->rcode + ) + . pack('n4', $this->qdcount, $this->ancount, $this->nscount, $this->arcount); + } } diff --git a/Net/DNS2/Lookups.php b/Net/DNS2/Lookups.php index f1e86403..f4d393a6 100644 --- a/Net/DNS2/Lookups.php +++ b/Net/DNS2/Lookups.php @@ -26,488 +26,487 @@ // build the reverse lookup tables; this is just so we don't have to // have duplicate static content laying around. // -Net_DNS2_Lookups::$rr_types_by_id = array_flip(Net_DNS2_Lookups::$rr_types_by_name); -Net_DNS2_Lookups::$classes_by_id = array_flip(Net_DNS2_Lookups::$classes_by_name); +Net_DNS2_Lookups::$rr_types_by_id = array_flip(Net_DNS2_Lookups::$rr_types_by_name); +Net_DNS2_Lookups::$classes_by_id = array_flip(Net_DNS2_Lookups::$classes_by_name); Net_DNS2_Lookups::$rr_types_class_to_id = array_flip(Net_DNS2_Lookups::$rr_types_id_to_class); Net_DNS2_Lookups::$algorithm_name_to_id = array_flip(Net_DNS2_Lookups::$algorithm_id_to_name); -Net_DNS2_Lookups::$digest_name_to_id = array_flip(Net_DNS2_Lookups::$digest_id_to_name); -Net_DNS2_Lookups::$rr_qtypes_by_id = array_flip(Net_DNS2_Lookups::$rr_qtypes_by_name); -Net_DNS2_Lookups::$rr_metatypes_by_id = array_flip(Net_DNS2_Lookups::$rr_metatypes_by_name); -Net_DNS2_Lookups::$protocol_by_id = array_flip(Net_DNS2_Lookups::$protocol_by_name); +Net_DNS2_Lookups::$digest_name_to_id = array_flip(Net_DNS2_Lookups::$digest_id_to_name); +Net_DNS2_Lookups::$rr_qtypes_by_id = array_flip(Net_DNS2_Lookups::$rr_qtypes_by_name); +Net_DNS2_Lookups::$rr_metatypes_by_id = array_flip(Net_DNS2_Lookups::$rr_metatypes_by_name); +Net_DNS2_Lookups::$protocol_by_id = array_flip(Net_DNS2_Lookups::$protocol_by_name); /** * This class provides simple lookups used throughout the Net_DNS2 code. */ -class Net_DNS2_Lookups -{ - // size (in bytes) of a header in a standard DNS packet - public const DNS_HEADER_SIZE = 12; - - // max size of a UDP packet - public const DNS_MAX_UDP_SIZE = 512; - - // Query/Response flag - public const QR_QUERY = 0; // RFC 1035 - public const QR_RESPONSE = 1; // RFC 1035 - - // DNS Op Codes - public const OPCODE_QUERY = 0; // RFC 1035 - public const OPCODE_IQUERY = 1; // RFC 1035, RFC 3425 - public const OPCODE_STATUS = 2; // RFC 1035 - public const OPCODE_NOTIFY = 4; // RFC 1996 - public const OPCODE_UPDATE = 5; // RFC 2136 - public const OPCODE_DSO = 6; // RFC 8490 - - // Resource Record Classes - public const RR_CLASS_IN = 1; // RFC 1035 - public const RR_CLASS_CH = 3; // RFC 1035 - public const RR_CLASS_HS = 4; // RFC 1035 - public const RR_CLASS_NONE = 254; // RFC 2136 - public const RR_CLASS_ANY = 255; // RFC 1035 - - // DNS Response Codes - public const RCODE_NOERROR = 0; // RFC 1035 - public const RCODE_FORMERR = 1; // RFC 1035 - public const RCODE_SERVFAIL = 2; // RFC 1035 - public const RCODE_NXDOMAIN = 3; // RFC 1035 - public const RCODE_NOTIMP = 4; // RFC 1035 - public const RCODE_REFUSED = 5; // RFC 1035 - public const RCODE_YXDOMAIN = 6; // RFC 2136 - public const RCODE_YXRRSET = 7; // RFC 2136 - public const RCODE_NXRRSET = 8; // RFC 2136 - public const RCODE_NOTAUTH = 9; // RFC 2136 - public const RCODE_NOTZONE = 10; // RFC 2136 - public const RCODE_DSOTYPENI = 11; // RFC 8490 - - // 12-15 reserved - - public const RCODE_BADSIG = 16; // RFC 2845 - public const RCODE_BADVERS = 16; // RFC 6891 - public const RCODE_BADKEY = 17; // RFC 2845 - public const RCODE_BADTIME = 18; // RFC 2845 - public const RCODE_BADMODE = 19; // RFC 2930 - public const RCODE_BADNAME = 20; // RFC 2930 - public const RCODE_BADALG = 21; // RFC 2930 - public const RCODE_BADTRUNC = 22; // RFC 4635 - public const RCODE_BADCOOKIE = 23; // RFC 7873 - - // internal errors codes returned by the exceptions class - public const E_NONE = 0; - public const E_DNS_FORMERR = self::RCODE_FORMERR; - public const E_DNS_SERVFAIL = self::RCODE_SERVFAIL; - public const E_DNS_NXDOMAIN = self::RCODE_NXDOMAIN; - public const E_DNS_NOTIMP = self::RCODE_NOTIMP; - public const E_DNS_REFUSED = self::RCODE_REFUSED; - public const E_DNS_YXDOMAIN = self::RCODE_YXDOMAIN; - public const E_DNS_YXRRSET = self::RCODE_YXRRSET; - public const E_DNS_NXRRSET = self::RCODE_NXRRSET; - public const E_DNS_NOTAUTH = self::RCODE_NOTAUTH; - public const E_DNS_NOTZONE = self::RCODE_NOTZONE; - - // 11-15 reserved - - public const E_DNS_BADSIG = self::RCODE_BADSIG; - public const E_DNS_BADKEY = self::RCODE_BADKEY; - public const E_DNS_BADTIME = self::RCODE_BADTIME; - public const E_DNS_BADMODE = self::RCODE_BADMODE; - public const E_DNS_BADNAME = self::RCODE_BADNAME; - public const E_DNS_BADALG = self::RCODE_BADALG; - public const E_DNS_BADTRUNC = self::RCODE_BADTRUNC; - public const E_DNS_BADCOOKIE = self::RCODE_BADCOOKIE; - - // other error conditions - - public const E_NS_INVALID_FILE = 200; - public const E_NS_INVALID_ENTRY = 201; - public const E_NS_FAILED = 202; - public const E_NS_SOCKET_FAILED = 203; - public const E_NS_INVALID_SOCKET = 204; - - public const E_PACKET_INVALID = 300; - public const E_PARSE_ERROR = 301; - public const E_HEADER_INVALID = 302; - public const E_QUESTION_INVALID = 303; - public const E_RR_INVALID = 304; - - public const E_OPENSSL_ERROR = 400; - public const E_OPENSSL_UNAVAIL = 401; - public const E_OPENSSL_INV_PKEY = 402; - public const E_OPENSSL_INV_ALGO = 403; - - public const E_CACHE_UNSUPPORTED = 500; - public const E_CACHE_SHM_FILE = 501; - public const E_CACHE_SHM_UNAVAIL = 502; - - // EDNS0 Option Codes (OPT) - // 0 - Reserved - public const EDNS0_OPT_LLQ = 1; - public const EDNS0_OPT_UL = 2; - public const EDNS0_OPT_NSID = 3; - // 4 - Reserved - public const EDNS0_OPT_DAU = 5; - public const EDNS0_OPT_DHU = 6; - public const EDNS0_OPT_N3U = 7; - public const EDNS0_OPT_CLIENT_SUBNET = 8; - public const EDNS0_OPT_EXPIRE = 9; - public const EDNS0_OPT_COOKIE = 10; - public const EDNS0_OPT_TCP_KEEPALIVE = 11; - public const EDNS0_OPT_PADDING = 12; - public const EDNS0_OPT_CHAIN = 13; - public const EDNS0_OPT_KEY_TAG = 14; - // 15 - unsassigned - public const EDNS0_OPT_CLIENT_TAG = 16; - public const EDNS0_OPT_SERVER_TAG = 17; - // 18-26945 - unassigned - public const EDNS0_OPT_DEVICEID = 26946; - - // DNSSEC Algorithms - public const DNSSEC_ALGORITHM_RES = 0; - public const DNSSEC_ALGORITHM_RSAMD5 = 1; - public const DNSSEC_ALGORITHM_DH = 2; - public const DNSSEC_ALGORITHM_DSA = 3; - public const DNSSEC_ALGORITHM_ECC = 4; - public const DNSSEC_ALGORITHM_RSASHA1 = 5; - public const DNSSEC_ALGORITHM_DSANSEC3SHA1 = 6; - public const DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 = 7; - public const DNSSEC_ALGORITHM_RSASHA256 = 8; - public const DNSSEC_ALGORITHM_RSASHA512 = 10; - public const DNSSEC_ALGORITHM_ECCGOST = 12; - public const DNSSEC_ALGORITHM_ECDSAP256SHA256 = 13; - public const DNSSEC_ALGORITHM_ECDSAP384SHA384 = 14; - public const DNSSEC_ALGORITHM_ED25519 = 15; - public const DNSSEC_ALGORITHM_ED448 = 16; - public const DNSSEC_ALGORITHM_INDIRECT = 252; - public const DNSSEC_ALGORITHM_PRIVATEDNS = 253; - public const DNSSEC_ALGORITHM_PRIVATEOID = 254; - - // DNSSEC Digest Types - public const DNSSEC_DIGEST_RES = 0; - public const DNSSEC_DIGEST_SHA1 = 1; - public const DNSSEC_DIGEST_SHA256 = 2; - public const DNSSEC_DIGEST_GOST = 3; - public const DNSSEC_DIGEST_SHA384 = 4; - - // The packet id used when sending requests - public static $next_packet_id; - - // Used to map resource record types to their id's, and back - public static $rr_types_by_id = []; - public static $rr_types_by_name = [ - 'SIG0' => 0, // RFC 2931 pseudo type - 'A' => 1, // RFC 1035 - 'NS' => 2, // RFC 1035 - 'MD' => 3, // RFC 1035 - obsolete, Not implemented - 'MF' => 4, // RFC 1035 - obsolete, Not implemented - 'CNAME' => 5, // RFC 1035 - 'SOA' => 6, // RFC 1035 - 'MB' => 7, // RFC 1035 - obsolete, Not implemented - 'MG' => 8, // RFC 1035 - obsolete, Not implemented - 'MR' => 9, // RFC 1035 - obsolete, Not implemented - 'NULL' => 10, // RFC 1035 - obsolete, Not implemented - 'WKS' => 11, // RFC 1035 - 'PTR' => 12, // RFC 1035 - 'HINFO' => 13, // RFC 1035 - 'MINFO' => 14, // RFC 1035 - obsolete, Not implemented - 'MX' => 15, // RFC 1035 - 'TXT' => 16, // RFC 1035 - 'RP' => 17, // RFC 1183 - 'AFSDB' => 18, // RFC 1183 - 'X25' => 19, // RFC 1183 - 'ISDN' => 20, // RFC 1183 - 'RT' => 21, // RFC 1183 - 'NSAP' => 22, // RFC 1706 - 'NSAP_PTR' => 23, // RFC 1348 - obsolete, Not implemented - 'SIG' => 24, // RFC 2535 - 'KEY' => 25, // RFC 2535, RFC 2930 - 'PX' => 26, // RFC 2163 - 'GPOS' => 27, // RFC 1712 - Not implemented - 'AAAA' => 28, // RFC 3596 - 'LOC' => 29, // RFC 1876 - 'NXT' => 30, // RFC 2065, obsoleted by by RFC 3755 - 'EID' => 31, // [Patton][Patton1995] - 'NIMLOC' => 32, // [Patton][Patton1995] - 'SRV' => 33, // RFC 2782 - 'ATMA' => 34, // Windows only - 'NAPTR' => 35, // RFC 2915 - 'KX' => 36, // RFC 2230 - 'CERT' => 37, // RFC 4398 - 'A6' => 38, // downgraded to experimental by RFC 3363 - 'DNAME' => 39, // RFC 2672 - 'SINK' => 40, // Not implemented - 'OPT' => 41, // RFC 2671 - 'APL' => 42, // RFC 3123 - 'DS' => 43, // RFC 4034 - 'SSHFP' => 44, // RFC 4255 - 'IPSECKEY' => 45, // RFC 4025 - 'RRSIG' => 46, // RFC 4034 - 'NSEC' => 47, // RFC 4034 - 'DNSKEY' => 48, // RFC 4034 - 'DHCID' => 49, // RFC 4701 - 'NSEC3' => 50, // RFC 5155 - 'NSEC3PARAM' => 51, // RFC 5155 - 'TLSA' => 52, // RFC 6698 - 'SMIMEA' => 53, // RFC 8162 - - // 54 unassigned - - 'HIP' => 55, // RFC 5205 - 'NINFO' => 56, // Not implemented - 'RKEY' => 57, // Not implemented - 'TALINK' => 58, - 'CDS' => 59, // RFC 7344 - 'CDNSKEY' => 60, // RFC 7344 - 'OPENPGPKEY' => 61, // RFC 7929 - 'CSYNC' => 62, // RFC 7477 - 'ZONEMD' => 63, // Not implemented yet - 'SVCB' => 64, // Not implemented yet - 'HTTPS' => 65, // Not implemented yet - - // 66 - 98 unassigned - - 'SPF' => 99, // RFC 4408 - 'UINFO' => 100, // no RFC, Not implemented - 'UID' => 101, // no RFC, Not implemented - 'GID' => 102, // no RFC, Not implemented - 'UNSPEC' => 103, // no RFC, Not implemented - 'NID' => 104, // RFC 6742 - 'L32' => 105, // RFC 6742 - 'L64' => 106, // RFC 6742 - 'LP' => 107, // RFC 6742 - 'EUI48' => 108, // RFC 7043 - 'EUI64' => 109, // RFC 7043 - - // 110 - 248 unassigned - - 'TKEY' => 249, // RFC 2930 - 'TSIG' => 250, // RFC 2845 - 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported - 'AXFR' => 252, // RFC 1035 - 'MAILB' => 253, // RFC 883, Not implemented - 'MAILA' => 254, // RFC 973, Not implemented - 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' - 'URI' => 256, // RFC 7553 - 'CAA' => 257, // RFC 8659 - 'AVC' => 258, // Application Visibility and Control - 'DOA' => 259, // Not implemented yet - 'AMTRELAY' => 260, // RFC 8777 - - // 261 - 32767 unassigned - - 'TA' => 32768, // same as DS - 'DLV' => 32769, // RFC 4431 - 'TYPE65534' => 65534, // Private Bind record - ]; - - // Qtypes and Metatypes - defined in RFC2929 section 3.1 - public static $rr_qtypes_by_id = []; - public static $rr_qtypes_by_name = [ - 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported - 'AXFR' => 252, // RFC 1035 - 'MAILB' => 253, // RFC 883, Not implemented - 'MAILA' => 254, // RFC 973, Not implemented - 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' - ]; - - public static $rr_metatypes_by_id = []; - public static $rr_metatypes_by_name = [ - 'OPT' => 41, // RFC 2671 - 'TKEY' => 249, // RFC 2930 - 'TSIG' => 250, // RFC 2845 - ]; - - // used to map resource record id's to RR class names - public static $rr_types_class_to_id = []; - public static $rr_types_id_to_class = [ - 1 => 'Net_DNS2_RR_A', - 2 => 'Net_DNS2_RR_NS', - 5 => 'Net_DNS2_RR_CNAME', - 6 => 'Net_DNS2_RR_SOA', - 11 => 'Net_DNS2_RR_WKS', - 12 => 'Net_DNS2_RR_PTR', - 13 => 'Net_DNS2_RR_HINFO', - 15 => 'Net_DNS2_RR_MX', - 16 => 'Net_DNS2_RR_TXT', - 17 => 'Net_DNS2_RR_RP', - 18 => 'Net_DNS2_RR_AFSDB', - 19 => 'Net_DNS2_RR_X25', - 20 => 'Net_DNS2_RR_ISDN', - 21 => 'Net_DNS2_RR_RT', - 22 => 'Net_DNS2_RR_NSAP', - 24 => 'Net_DNS2_RR_SIG', - 25 => 'Net_DNS2_RR_KEY', - 26 => 'Net_DNS2_RR_PX', - 28 => 'Net_DNS2_RR_AAAA', - 29 => 'Net_DNS2_RR_LOC', - 31 => 'Net_DNS2_RR_EID', - 32 => 'Net_DNS2_RR_NIMLOC', - 33 => 'Net_DNS2_RR_SRV', - 34 => 'Net_DNS2_RR_ATMA', - 35 => 'Net_DNS2_RR_NAPTR', - 36 => 'Net_DNS2_RR_KX', - 37 => 'Net_DNS2_RR_CERT', - 39 => 'Net_DNS2_RR_DNAME', - 41 => 'Net_DNS2_RR_OPT', - 42 => 'Net_DNS2_RR_APL', - 43 => 'Net_DNS2_RR_DS', - 44 => 'Net_DNS2_RR_SSHFP', - 45 => 'Net_DNS2_RR_IPSECKEY', - 46 => 'Net_DNS2_RR_RRSIG', - 47 => 'Net_DNS2_RR_NSEC', - 48 => 'Net_DNS2_RR_DNSKEY', - 49 => 'Net_DNS2_RR_DHCID', - 50 => 'Net_DNS2_RR_NSEC3', - 51 => 'Net_DNS2_RR_NSEC3PARAM', - 52 => 'Net_DNS2_RR_TLSA', - 53 => 'Net_DNS2_RR_SMIMEA', - 55 => 'Net_DNS2_RR_HIP', - 58 => 'Net_DNS2_RR_TALINK', - 59 => 'Net_DNS2_RR_CDS', - 60 => 'Net_DNS2_RR_CDNSKEY', - 61 => 'Net_DNS2_RR_OPENPGPKEY', - 62 => 'Net_DNS2_RR_CSYNC', - 99 => 'Net_DNS2_RR_SPF', - 104 => 'Net_DNS2_RR_NID', - 105 => 'Net_DNS2_RR_L32', - 106 => 'Net_DNS2_RR_L64', - 107 => 'Net_DNS2_RR_LP', - 108 => 'Net_DNS2_RR_EUI48', - 109 => 'Net_DNS2_RR_EUI64', - - 249 => 'Net_DNS2_RR_TKEY', - 250 => 'Net_DNS2_RR_TSIG', - - // 251 - IXFR - handled as a full zone transfer (252) - // 252 - AXFR - handled as a function call - - 255 => 'Net_DNS2_RR_ANY', - 256 => 'Net_DNS2_RR_URI', - 257 => 'Net_DNS2_RR_CAA', - 258 => 'Net_DNS2_RR_AVC', - 260 => 'Net_DNS2_RR_AMTRELAY', - 32768 => 'Net_DNS2_RR_TA', - 32769 => 'Net_DNS2_RR_DLV', - 65534 => 'Net_DNS2_RR_TYPE65534', - ]; - - // used to map resource record class names to their id's, and back - public static $classes_by_id = []; - public static $classes_by_name = [ - 'IN' => self::RR_CLASS_IN, // RFC 1035 - 'CH' => self::RR_CLASS_CH, // RFC 1035 - 'HS' => self::RR_CLASS_HS, // RFC 1035 - 'NONE' => self::RR_CLASS_NONE, // RFC 2136 - 'ANY' => self::RR_CLASS_ANY, // RFC 1035 - ]; - - // maps response codes to error messages - public static $result_code_messages = [ - self::RCODE_NOERROR => 'The request completed successfully.', - self::RCODE_FORMERR => 'The name server was unable to interpret the query.', - self::RCODE_SERVFAIL => 'The name server was unable to process this query due to a problem with the name server.', - self::RCODE_NXDOMAIN => 'The domain name referenced in the query does not exist.', - self::RCODE_NOTIMP => 'The name server does not support the requested kind of query.', - self::RCODE_REFUSED => 'The name server refuses to perform the specified operation for policy reasons.', - self::RCODE_YXDOMAIN => 'Name Exists when it should not.', - self::RCODE_YXRRSET => 'RR Set Exists when it should not.', - self::RCODE_NXRRSET => 'RR Set that should exist does not.', - self::RCODE_NOTAUTH => 'Server Not Authoritative for zone.', - self::RCODE_NOTZONE => 'Name not contained in zone.', - - self::RCODE_BADSIG => 'TSIG Signature Failure.', - self::RCODE_BADKEY => 'Key not recognized.', - self::RCODE_BADTIME => 'Signature out of time window.', - self::RCODE_BADMODE => 'Bad TKEY Mode.', - self::RCODE_BADNAME => 'Duplicate key name.', - self::RCODE_BADALG => 'Algorithm not supported.', - self::RCODE_BADTRUNC => 'Bad truncation.', - ]; - - // maps DNS SEC alrorithms to their mnemonics - public static $algorithm_name_to_id = []; - public static $algorithm_id_to_name = [ - self::DNSSEC_ALGORITHM_RES => 'RES', - self::DNSSEC_ALGORITHM_RSAMD5 => 'RSAMD5', - self::DNSSEC_ALGORITHM_DH => 'DH', - self::DNSSEC_ALGORITHM_DSA => 'DSA', - self::DNSSEC_ALGORITHM_ECC => 'ECC', - self::DNSSEC_ALGORITHM_RSASHA1 => 'RSASHA1', - self::DNSSEC_ALGORITHM_DSANSEC3SHA1 => 'DSA-NSEC3-SHA1', - self::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 => 'RSASHA1-NSEC3-SHA1', - self::DNSSEC_ALGORITHM_RSASHA256 => 'RSASHA256', - self::DNSSEC_ALGORITHM_RSASHA512 => 'RSASHA512', - self::DNSSEC_ALGORITHM_ECCGOST => 'ECC-GOST', - self::DNSSEC_ALGORITHM_ECDSAP256SHA256 => 'ECDSAP256SHA256', - self::DNSSEC_ALGORITHM_ECDSAP384SHA384 => 'ECDSAP384SHA384', - self::DNSSEC_ALGORITHM_ED25519 => 'ED25519', - self::DNSSEC_ALGORITHM_ED448 => 'ED448', - self::DNSSEC_ALGORITHM_INDIRECT => 'INDIRECT', - self::DNSSEC_ALGORITHM_PRIVATEDNS => 'PRIVATEDNS', - self::DNSSEC_ALGORITHM_PRIVATEOID => 'PRIVATEOID', - ]; - - // maps DNSSEC digest types to their mnemonics - public static $digest_name_to_id = []; - public static $digest_id_to_name = [ - self::DNSSEC_DIGEST_RES => 'RES', - self::DNSSEC_DIGEST_SHA1 => 'SHA-1', - self::DNSSEC_DIGEST_SHA256 => 'SHA-256', - self::DNSSEC_DIGEST_GOST => 'GOST-R-34.11-94', - self::DNSSEC_DIGEST_SHA384 => 'SHA-384', - ]; - - // Protocols names - RFC 1010 - public static $protocol_by_id = []; - public static $protocol_by_name = [ - 'ICMP' => 1, - 'IGMP' => 2, - 'GGP' => 3, - 'ST' => 5, - 'TCP' => 6, - 'UCL' => 7, - 'EGP' => 8, - 'IGP' => 9, - 'BBN-RCC-MON' => 10, - 'NVP-II' => 11, - 'PUP' => 12, - 'ARGUS' => 13, - 'EMCON' => 14, - 'XNET' => 15, - 'CHAOS' => 16, - 'UDP' => 17, - 'MUX' => 18, - 'DCN-MEAS' => 19, - 'HMP' => 20, - 'PRM' => 21, - 'XNS-IDP' => 22, - 'TRUNK-1' => 23, - 'TRUNK-2' => 24, - 'LEAF-1' => 25, - 'LEAF-2' => 26, - 'RDP' => 27, - 'IRTP' => 28, - 'ISO-TP4' => 29, - 'NETBLT' => 30, - 'MFE-NSP' => 31, - 'MERIT-INP' => 32, - 'SEP' => 33, - // 34 - 60 - Unassigned - // 61 - any host internal protocol - 'CFTP' => 62, - // 63 - any local network - 'SAT-EXPAK' => 64, - 'MIT-SUBNET' => 65, - 'RVD' => 66, - 'IPPC' => 67, - // 68 - any distributed file system - 'SAT-MON' => 69, - // 70 - Unassigned - 'IPCV' => 71, - // 72 - 75 - Unassigned - 'BR-SAT-MON' => 76, - // 77 - Unassigned - 'WB-MON' => 78, - 'WB-EXPAK' => 79, - // 80 - 254 - Unassigned - // 255 - Reserved - ]; +class Net_DNS2_Lookups { + // size (in bytes) of a header in a standard DNS packet + public const DNS_HEADER_SIZE = 12; + + // max size of a UDP packet + public const DNS_MAX_UDP_SIZE = 512; + + // Query/Response flag + public const QR_QUERY = 0; // RFC 1035 + public const QR_RESPONSE = 1; // RFC 1035 + + // DNS Op Codes + public const OPCODE_QUERY = 0; // RFC 1035 + public const OPCODE_IQUERY = 1; // RFC 1035, RFC 3425 + public const OPCODE_STATUS = 2; // RFC 1035 + public const OPCODE_NOTIFY = 4; // RFC 1996 + public const OPCODE_UPDATE = 5; // RFC 2136 + public const OPCODE_DSO = 6; // RFC 8490 + + // Resource Record Classes + public const RR_CLASS_IN = 1; // RFC 1035 + public const RR_CLASS_CH = 3; // RFC 1035 + public const RR_CLASS_HS = 4; // RFC 1035 + public const RR_CLASS_NONE = 254; // RFC 2136 + public const RR_CLASS_ANY = 255; // RFC 1035 + + // DNS Response Codes + public const RCODE_NOERROR = 0; // RFC 1035 + public const RCODE_FORMERR = 1; // RFC 1035 + public const RCODE_SERVFAIL = 2; // RFC 1035 + public const RCODE_NXDOMAIN = 3; // RFC 1035 + public const RCODE_NOTIMP = 4; // RFC 1035 + public const RCODE_REFUSED = 5; // RFC 1035 + public const RCODE_YXDOMAIN = 6; // RFC 2136 + public const RCODE_YXRRSET = 7; // RFC 2136 + public const RCODE_NXRRSET = 8; // RFC 2136 + public const RCODE_NOTAUTH = 9; // RFC 2136 + public const RCODE_NOTZONE = 10; // RFC 2136 + public const RCODE_DSOTYPENI = 11; // RFC 8490 + + // 12-15 reserved + + public const RCODE_BADSIG = 16; // RFC 2845 + public const RCODE_BADVERS = 16; // RFC 6891 + public const RCODE_BADKEY = 17; // RFC 2845 + public const RCODE_BADTIME = 18; // RFC 2845 + public const RCODE_BADMODE = 19; // RFC 2930 + public const RCODE_BADNAME = 20; // RFC 2930 + public const RCODE_BADALG = 21; // RFC 2930 + public const RCODE_BADTRUNC = 22; // RFC 4635 + public const RCODE_BADCOOKIE = 23; // RFC 7873 + + // internal errors codes returned by the exceptions class + public const E_NONE = 0; + public const E_DNS_FORMERR = self::RCODE_FORMERR; + public const E_DNS_SERVFAIL = self::RCODE_SERVFAIL; + public const E_DNS_NXDOMAIN = self::RCODE_NXDOMAIN; + public const E_DNS_NOTIMP = self::RCODE_NOTIMP; + public const E_DNS_REFUSED = self::RCODE_REFUSED; + public const E_DNS_YXDOMAIN = self::RCODE_YXDOMAIN; + public const E_DNS_YXRRSET = self::RCODE_YXRRSET; + public const E_DNS_NXRRSET = self::RCODE_NXRRSET; + public const E_DNS_NOTAUTH = self::RCODE_NOTAUTH; + public const E_DNS_NOTZONE = self::RCODE_NOTZONE; + + // 11-15 reserved + + public const E_DNS_BADSIG = self::RCODE_BADSIG; + public const E_DNS_BADKEY = self::RCODE_BADKEY; + public const E_DNS_BADTIME = self::RCODE_BADTIME; + public const E_DNS_BADMODE = self::RCODE_BADMODE; + public const E_DNS_BADNAME = self::RCODE_BADNAME; + public const E_DNS_BADALG = self::RCODE_BADALG; + public const E_DNS_BADTRUNC = self::RCODE_BADTRUNC; + public const E_DNS_BADCOOKIE = self::RCODE_BADCOOKIE; + + // other error conditions + + public const E_NS_INVALID_FILE = 200; + public const E_NS_INVALID_ENTRY = 201; + public const E_NS_FAILED = 202; + public const E_NS_SOCKET_FAILED = 203; + public const E_NS_INVALID_SOCKET = 204; + + public const E_PACKET_INVALID = 300; + public const E_PARSE_ERROR = 301; + public const E_HEADER_INVALID = 302; + public const E_QUESTION_INVALID = 303; + public const E_RR_INVALID = 304; + + public const E_OPENSSL_ERROR = 400; + public const E_OPENSSL_UNAVAIL = 401; + public const E_OPENSSL_INV_PKEY = 402; + public const E_OPENSSL_INV_ALGO = 403; + + public const E_CACHE_UNSUPPORTED = 500; + public const E_CACHE_SHM_FILE = 501; + public const E_CACHE_SHM_UNAVAIL = 502; + + // EDNS0 Option Codes (OPT) + // 0 - Reserved + public const EDNS0_OPT_LLQ = 1; + public const EDNS0_OPT_UL = 2; + public const EDNS0_OPT_NSID = 3; + // 4 - Reserved + public const EDNS0_OPT_DAU = 5; + public const EDNS0_OPT_DHU = 6; + public const EDNS0_OPT_N3U = 7; + public const EDNS0_OPT_CLIENT_SUBNET = 8; + public const EDNS0_OPT_EXPIRE = 9; + public const EDNS0_OPT_COOKIE = 10; + public const EDNS0_OPT_TCP_KEEPALIVE = 11; + public const EDNS0_OPT_PADDING = 12; + public const EDNS0_OPT_CHAIN = 13; + public const EDNS0_OPT_KEY_TAG = 14; + // 15 - unsassigned + public const EDNS0_OPT_CLIENT_TAG = 16; + public const EDNS0_OPT_SERVER_TAG = 17; + // 18-26945 - unassigned + public const EDNS0_OPT_DEVICEID = 26946; + + // DNSSEC Algorithms + public const DNSSEC_ALGORITHM_RES = 0; + public const DNSSEC_ALGORITHM_RSAMD5 = 1; + public const DNSSEC_ALGORITHM_DH = 2; + public const DNSSEC_ALGORITHM_DSA = 3; + public const DNSSEC_ALGORITHM_ECC = 4; + public const DNSSEC_ALGORITHM_RSASHA1 = 5; + public const DNSSEC_ALGORITHM_DSANSEC3SHA1 = 6; + public const DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 = 7; + public const DNSSEC_ALGORITHM_RSASHA256 = 8; + public const DNSSEC_ALGORITHM_RSASHA512 = 10; + public const DNSSEC_ALGORITHM_ECCGOST = 12; + public const DNSSEC_ALGORITHM_ECDSAP256SHA256 = 13; + public const DNSSEC_ALGORITHM_ECDSAP384SHA384 = 14; + public const DNSSEC_ALGORITHM_ED25519 = 15; + public const DNSSEC_ALGORITHM_ED448 = 16; + public const DNSSEC_ALGORITHM_INDIRECT = 252; + public const DNSSEC_ALGORITHM_PRIVATEDNS = 253; + public const DNSSEC_ALGORITHM_PRIVATEOID = 254; + + // DNSSEC Digest Types + public const DNSSEC_DIGEST_RES = 0; + public const DNSSEC_DIGEST_SHA1 = 1; + public const DNSSEC_DIGEST_SHA256 = 2; + public const DNSSEC_DIGEST_GOST = 3; + public const DNSSEC_DIGEST_SHA384 = 4; + + // The packet id used when sending requests + public static $next_packet_id; + + // Used to map resource record types to their id's, and back + public static $rr_types_by_id = []; + public static $rr_types_by_name = [ + 'SIG0' => 0, // RFC 2931 pseudo type + 'A' => 1, // RFC 1035 + 'NS' => 2, // RFC 1035 + 'MD' => 3, // RFC 1035 - obsolete, Not implemented + 'MF' => 4, // RFC 1035 - obsolete, Not implemented + 'CNAME' => 5, // RFC 1035 + 'SOA' => 6, // RFC 1035 + 'MB' => 7, // RFC 1035 - obsolete, Not implemented + 'MG' => 8, // RFC 1035 - obsolete, Not implemented + 'MR' => 9, // RFC 1035 - obsolete, Not implemented + 'NULL' => 10, // RFC 1035 - obsolete, Not implemented + 'WKS' => 11, // RFC 1035 + 'PTR' => 12, // RFC 1035 + 'HINFO' => 13, // RFC 1035 + 'MINFO' => 14, // RFC 1035 - obsolete, Not implemented + 'MX' => 15, // RFC 1035 + 'TXT' => 16, // RFC 1035 + 'RP' => 17, // RFC 1183 + 'AFSDB' => 18, // RFC 1183 + 'X25' => 19, // RFC 1183 + 'ISDN' => 20, // RFC 1183 + 'RT' => 21, // RFC 1183 + 'NSAP' => 22, // RFC 1706 + 'NSAP_PTR' => 23, // RFC 1348 - obsolete, Not implemented + 'SIG' => 24, // RFC 2535 + 'KEY' => 25, // RFC 2535, RFC 2930 + 'PX' => 26, // RFC 2163 + 'GPOS' => 27, // RFC 1712 - Not implemented + 'AAAA' => 28, // RFC 3596 + 'LOC' => 29, // RFC 1876 + 'NXT' => 30, // RFC 2065, obsoleted by by RFC 3755 + 'EID' => 31, // [Patton][Patton1995] + 'NIMLOC' => 32, // [Patton][Patton1995] + 'SRV' => 33, // RFC 2782 + 'ATMA' => 34, // Windows only + 'NAPTR' => 35, // RFC 2915 + 'KX' => 36, // RFC 2230 + 'CERT' => 37, // RFC 4398 + 'A6' => 38, // downgraded to experimental by RFC 3363 + 'DNAME' => 39, // RFC 2672 + 'SINK' => 40, // Not implemented + 'OPT' => 41, // RFC 2671 + 'APL' => 42, // RFC 3123 + 'DS' => 43, // RFC 4034 + 'SSHFP' => 44, // RFC 4255 + 'IPSECKEY' => 45, // RFC 4025 + 'RRSIG' => 46, // RFC 4034 + 'NSEC' => 47, // RFC 4034 + 'DNSKEY' => 48, // RFC 4034 + 'DHCID' => 49, // RFC 4701 + 'NSEC3' => 50, // RFC 5155 + 'NSEC3PARAM' => 51, // RFC 5155 + 'TLSA' => 52, // RFC 6698 + 'SMIMEA' => 53, // RFC 8162 + + // 54 unassigned + + 'HIP' => 55, // RFC 5205 + 'NINFO' => 56, // Not implemented + 'RKEY' => 57, // Not implemented + 'TALINK' => 58, + 'CDS' => 59, // RFC 7344 + 'CDNSKEY' => 60, // RFC 7344 + 'OPENPGPKEY' => 61, // RFC 7929 + 'CSYNC' => 62, // RFC 7477 + 'ZONEMD' => 63, // Not implemented yet + 'SVCB' => 64, // Not implemented yet + 'HTTPS' => 65, // Not implemented yet + + // 66 - 98 unassigned + + 'SPF' => 99, // RFC 4408 + 'UINFO' => 100, // no RFC, Not implemented + 'UID' => 101, // no RFC, Not implemented + 'GID' => 102, // no RFC, Not implemented + 'UNSPEC' => 103, // no RFC, Not implemented + 'NID' => 104, // RFC 6742 + 'L32' => 105, // RFC 6742 + 'L64' => 106, // RFC 6742 + 'LP' => 107, // RFC 6742 + 'EUI48' => 108, // RFC 7043 + 'EUI64' => 109, // RFC 7043 + + // 110 - 248 unassigned + + 'TKEY' => 249, // RFC 2930 + 'TSIG' => 250, // RFC 2845 + 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported + 'AXFR' => 252, // RFC 1035 + 'MAILB' => 253, // RFC 883, Not implemented + 'MAILA' => 254, // RFC 973, Not implemented + 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' + 'URI' => 256, // RFC 7553 + 'CAA' => 257, // RFC 8659 + 'AVC' => 258, // Application Visibility and Control + 'DOA' => 259, // Not implemented yet + 'AMTRELAY' => 260, // RFC 8777 + + // 261 - 32767 unassigned + + 'TA' => 32768, // same as DS + 'DLV' => 32769, // RFC 4431 + 'TYPE65534' => 65534, // Private Bind record + ]; + + // Qtypes and Metatypes - defined in RFC2929 section 3.1 + public static $rr_qtypes_by_id = []; + public static $rr_qtypes_by_name = [ + 'IXFR' => 251, // RFC 1995 - only a full (AXFR) is supported + 'AXFR' => 252, // RFC 1035 + 'MAILB' => 253, // RFC 883, Not implemented + 'MAILA' => 254, // RFC 973, Not implemented + 'ANY' => 255, // RFC 1035 - we support both 'ANY' and '*' + ]; + + public static $rr_metatypes_by_id = []; + public static $rr_metatypes_by_name = [ + 'OPT' => 41, // RFC 2671 + 'TKEY' => 249, // RFC 2930 + 'TSIG' => 250, // RFC 2845 + ]; + + // used to map resource record id's to RR class names + public static $rr_types_class_to_id = []; + public static $rr_types_id_to_class = [ + 1 => 'Net_DNS2_RR_A', + 2 => 'Net_DNS2_RR_NS', + 5 => 'Net_DNS2_RR_CNAME', + 6 => 'Net_DNS2_RR_SOA', + 11 => 'Net_DNS2_RR_WKS', + 12 => 'Net_DNS2_RR_PTR', + 13 => 'Net_DNS2_RR_HINFO', + 15 => 'Net_DNS2_RR_MX', + 16 => 'Net_DNS2_RR_TXT', + 17 => 'Net_DNS2_RR_RP', + 18 => 'Net_DNS2_RR_AFSDB', + 19 => 'Net_DNS2_RR_X25', + 20 => 'Net_DNS2_RR_ISDN', + 21 => 'Net_DNS2_RR_RT', + 22 => 'Net_DNS2_RR_NSAP', + 24 => 'Net_DNS2_RR_SIG', + 25 => 'Net_DNS2_RR_KEY', + 26 => 'Net_DNS2_RR_PX', + 28 => 'Net_DNS2_RR_AAAA', + 29 => 'Net_DNS2_RR_LOC', + 31 => 'Net_DNS2_RR_EID', + 32 => 'Net_DNS2_RR_NIMLOC', + 33 => 'Net_DNS2_RR_SRV', + 34 => 'Net_DNS2_RR_ATMA', + 35 => 'Net_DNS2_RR_NAPTR', + 36 => 'Net_DNS2_RR_KX', + 37 => 'Net_DNS2_RR_CERT', + 39 => 'Net_DNS2_RR_DNAME', + 41 => 'Net_DNS2_RR_OPT', + 42 => 'Net_DNS2_RR_APL', + 43 => 'Net_DNS2_RR_DS', + 44 => 'Net_DNS2_RR_SSHFP', + 45 => 'Net_DNS2_RR_IPSECKEY', + 46 => 'Net_DNS2_RR_RRSIG', + 47 => 'Net_DNS2_RR_NSEC', + 48 => 'Net_DNS2_RR_DNSKEY', + 49 => 'Net_DNS2_RR_DHCID', + 50 => 'Net_DNS2_RR_NSEC3', + 51 => 'Net_DNS2_RR_NSEC3PARAM', + 52 => 'Net_DNS2_RR_TLSA', + 53 => 'Net_DNS2_RR_SMIMEA', + 55 => 'Net_DNS2_RR_HIP', + 58 => 'Net_DNS2_RR_TALINK', + 59 => 'Net_DNS2_RR_CDS', + 60 => 'Net_DNS2_RR_CDNSKEY', + 61 => 'Net_DNS2_RR_OPENPGPKEY', + 62 => 'Net_DNS2_RR_CSYNC', + 99 => 'Net_DNS2_RR_SPF', + 104 => 'Net_DNS2_RR_NID', + 105 => 'Net_DNS2_RR_L32', + 106 => 'Net_DNS2_RR_L64', + 107 => 'Net_DNS2_RR_LP', + 108 => 'Net_DNS2_RR_EUI48', + 109 => 'Net_DNS2_RR_EUI64', + + 249 => 'Net_DNS2_RR_TKEY', + 250 => 'Net_DNS2_RR_TSIG', + + // 251 - IXFR - handled as a full zone transfer (252) + // 252 - AXFR - handled as a function call + + 255 => 'Net_DNS2_RR_ANY', + 256 => 'Net_DNS2_RR_URI', + 257 => 'Net_DNS2_RR_CAA', + 258 => 'Net_DNS2_RR_AVC', + 260 => 'Net_DNS2_RR_AMTRELAY', + 32768 => 'Net_DNS2_RR_TA', + 32769 => 'Net_DNS2_RR_DLV', + 65534 => 'Net_DNS2_RR_TYPE65534', + ]; + + // used to map resource record class names to their id's, and back + public static $classes_by_id = []; + public static $classes_by_name = [ + 'IN' => self::RR_CLASS_IN, // RFC 1035 + 'CH' => self::RR_CLASS_CH, // RFC 1035 + 'HS' => self::RR_CLASS_HS, // RFC 1035 + 'NONE' => self::RR_CLASS_NONE, // RFC 2136 + 'ANY' => self::RR_CLASS_ANY, // RFC 1035 + ]; + + // maps response codes to error messages + public static $result_code_messages = [ + self::RCODE_NOERROR => 'The request completed successfully.', + self::RCODE_FORMERR => 'The name server was unable to interpret the query.', + self::RCODE_SERVFAIL => 'The name server was unable to process this query due to a problem with the name server.', + self::RCODE_NXDOMAIN => 'The domain name referenced in the query does not exist.', + self::RCODE_NOTIMP => 'The name server does not support the requested kind of query.', + self::RCODE_REFUSED => 'The name server refuses to perform the specified operation for policy reasons.', + self::RCODE_YXDOMAIN => 'Name Exists when it should not.', + self::RCODE_YXRRSET => 'RR Set Exists when it should not.', + self::RCODE_NXRRSET => 'RR Set that should exist does not.', + self::RCODE_NOTAUTH => 'Server Not Authoritative for zone.', + self::RCODE_NOTZONE => 'Name not contained in zone.', + + self::RCODE_BADSIG => 'TSIG Signature Failure.', + self::RCODE_BADKEY => 'Key not recognized.', + self::RCODE_BADTIME => 'Signature out of time window.', + self::RCODE_BADMODE => 'Bad TKEY Mode.', + self::RCODE_BADNAME => 'Duplicate key name.', + self::RCODE_BADALG => 'Algorithm not supported.', + self::RCODE_BADTRUNC => 'Bad truncation.', + ]; + + // maps DNS SEC alrorithms to their mnemonics + public static $algorithm_name_to_id = []; + public static $algorithm_id_to_name = [ + self::DNSSEC_ALGORITHM_RES => 'RES', + self::DNSSEC_ALGORITHM_RSAMD5 => 'RSAMD5', + self::DNSSEC_ALGORITHM_DH => 'DH', + self::DNSSEC_ALGORITHM_DSA => 'DSA', + self::DNSSEC_ALGORITHM_ECC => 'ECC', + self::DNSSEC_ALGORITHM_RSASHA1 => 'RSASHA1', + self::DNSSEC_ALGORITHM_DSANSEC3SHA1 => 'DSA-NSEC3-SHA1', + self::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1 => 'RSASHA1-NSEC3-SHA1', + self::DNSSEC_ALGORITHM_RSASHA256 => 'RSASHA256', + self::DNSSEC_ALGORITHM_RSASHA512 => 'RSASHA512', + self::DNSSEC_ALGORITHM_ECCGOST => 'ECC-GOST', + self::DNSSEC_ALGORITHM_ECDSAP256SHA256 => 'ECDSAP256SHA256', + self::DNSSEC_ALGORITHM_ECDSAP384SHA384 => 'ECDSAP384SHA384', + self::DNSSEC_ALGORITHM_ED25519 => 'ED25519', + self::DNSSEC_ALGORITHM_ED448 => 'ED448', + self::DNSSEC_ALGORITHM_INDIRECT => 'INDIRECT', + self::DNSSEC_ALGORITHM_PRIVATEDNS => 'PRIVATEDNS', + self::DNSSEC_ALGORITHM_PRIVATEOID => 'PRIVATEOID', + ]; + + // maps DNSSEC digest types to their mnemonics + public static $digest_name_to_id = []; + public static $digest_id_to_name = [ + self::DNSSEC_DIGEST_RES => 'RES', + self::DNSSEC_DIGEST_SHA1 => 'SHA-1', + self::DNSSEC_DIGEST_SHA256 => 'SHA-256', + self::DNSSEC_DIGEST_GOST => 'GOST-R-34.11-94', + self::DNSSEC_DIGEST_SHA384 => 'SHA-384', + ]; + + // Protocols names - RFC 1010 + public static $protocol_by_id = []; + public static $protocol_by_name = [ + 'ICMP' => 1, + 'IGMP' => 2, + 'GGP' => 3, + 'ST' => 5, + 'TCP' => 6, + 'UCL' => 7, + 'EGP' => 8, + 'IGP' => 9, + 'BBN-RCC-MON' => 10, + 'NVP-II' => 11, + 'PUP' => 12, + 'ARGUS' => 13, + 'EMCON' => 14, + 'XNET' => 15, + 'CHAOS' => 16, + 'UDP' => 17, + 'MUX' => 18, + 'DCN-MEAS' => 19, + 'HMP' => 20, + 'PRM' => 21, + 'XNS-IDP' => 22, + 'TRUNK-1' => 23, + 'TRUNK-2' => 24, + 'LEAF-1' => 25, + 'LEAF-2' => 26, + 'RDP' => 27, + 'IRTP' => 28, + 'ISO-TP4' => 29, + 'NETBLT' => 30, + 'MFE-NSP' => 31, + 'MERIT-INP' => 32, + 'SEP' => 33, + // 34 - 60 - Unassigned + // 61 - any host internal protocol + 'CFTP' => 62, + // 63 - any local network + 'SAT-EXPAK' => 64, + 'MIT-SUBNET' => 65, + 'RVD' => 66, + 'IPPC' => 67, + // 68 - any distributed file system + 'SAT-MON' => 69, + // 70 - Unassigned + 'IPCV' => 71, + // 72 - 75 - Unassigned + 'BR-SAT-MON' => 76, + // 77 - Unassigned + 'WB-MON' => 78, + 'WB-EXPAK' => 79, + // 80 - 254 - Unassigned + // 255 - Reserved + ]; } diff --git a/Net/DNS2/Notifier.php b/Net/DNS2/Notifier.php index 4cedc885..7925487d 100644 --- a/Net/DNS2/Notifier.php +++ b/Net/DNS2/Notifier.php @@ -28,185 +28,179 @@ * Generally, query (recursive) lookups are done against caching server, while * notify requests are done against authoritative servers. */ -class Net_DNS2_Notifier extends Net_DNS2 -{ - // a Net_DNS2_Packet_Request object used for the notify request - private $_packet; - - /** - * Constructor - builds a new Net_DNS2_Notifier objected used for doing - * DNS notification for a changed zone. - * - * @param string $zone the domain name to use for DNS updates - * @param mixed $options an array of config options or null - * - * @throws Net_DNS2_Exception - */ - public function __construct($zone, ?array $options = null) - { - parent::__construct($options); - - // - // create the packet - // - $this->_packet = new Net_DNS2_Packet_Request( - strtolower(trim($zone, " \n\r\t.")), - 'SOA', - 'IN' - ); - - // - // make sure the opcode on the packet is set to NOTIFY - // - $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_NOTIFY; - } - - /** - * 3.7 - Add RR to notify. - * - * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be sent in the notify message - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function add(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - // - // add the RR to the "notify" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * add a signature to the request for authentication. - * - * @param string $keyname the key name to use for the TSIG RR - * @param string $signature the key to sign the request - * @param mixed $algorithm - * - * @return bool - * - * @see Net_DNS2::signTSIG() - * @deprecated function deprecated in 1.1.0 - */ - public function signature($keyname, $signature, $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5) - { - return $this->signTSIG($keyname, $signature, $algorithm); - } - - /** - * returns the current internal packet object. - * - * @return Net_DNS2_Packet_Request - */ - public function packet() - { - // - // take a copy - // - $p = $this->_packet; - - // - // check for an authentication method; either TSIG or SIG - // - if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $p->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $p->header->qdcount = cacti_sizeof($p->question); - $p->header->ancount = cacti_sizeof($p->answer); - $p->header->nscount = cacti_sizeof($p->authority); - $p->header->arcount = cacti_sizeof($p->additional); - - return $p; - } - - /** - * executes the notify request. - * - * @param Net_DNS2_Packet_Response &$response ref to the response object - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function notify(&$response = null) - { - // - // check for an authentication method; either TSIG or SIG - // - if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $this->_packet->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); - $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); - $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); - $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); - - // - // make sure we have some data to send - // - if (0 == $this->_packet->header->qdcount) { - throw new Net_DNS2_Exception( - 'empty headers- nothing to send!', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - // - // send the packet and get back the response - // - $response = $this->sendPacket($this->_packet, $this->use_tcp); - - // - // clear the internal packet so if we make another request, we don't have - // old data being sent. - // - $this->_packet->reset(); - - // - // for notifies, we just need to know it worked- we don't actually need to - // return the response object - // - return true; - } - - /** - * checks that the given name matches the name for the zone we're notifying. - * - * @param string $name the name to be checked - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - private function _checkName($name) - { - if (!preg_match('/'.$this->_packet->question[0]->qname.'$/', $name)) { - throw new Net_DNS2_Exception( - 'name provided ('.$name.') does not match zone name (' - .$this->_packet->question[0]->qname.')', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - return true; - } +class Net_DNS2_Notifier extends Net_DNS2 { + // a Net_DNS2_Packet_Request object used for the notify request + private $_packet; + + /** + * Constructor - builds a new Net_DNS2_Notifier objected used for doing + * DNS notification for a changed zone. + * + * @param string $zone the domain name to use for DNS updates + * @param mixed $options an array of config options or null + * + * @throws Net_DNS2_Exception + */ + public function __construct($zone, ?array $options = null) { + parent::__construct($options); + + // + // create the packet + // + $this->_packet = new Net_DNS2_Packet_Request( + strtolower(trim($zone, " \n\r\t.")), + 'SOA', + 'IN' + ); + + // + // make sure the opcode on the packet is set to NOTIFY + // + $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_NOTIFY; + } + + /** + * 3.7 - Add RR to notify. + * + * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be sent in the notify message + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function add(Net_DNS2_RR $rr) { + $this->_checkName($rr->name); + + // + // add the RR to the "notify" section + // + if (!in_array($rr, $this->_packet->answer, true)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * add a signature to the request for authentication. + * + * @param string $keyname the key name to use for the TSIG RR + * @param string $signature the key to sign the request + * @param mixed $algorithm + * + * @return bool + * + * @see Net_DNS2::signTSIG() + * @deprecated function deprecated in 1.1.0 + */ + public function signature($keyname, $signature, $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5) { + return $this->signTSIG($keyname, $signature, $algorithm); + } + + /** + * returns the current internal packet object. + * + * @return Net_DNS2_Packet_Request + */ + public function packet() { + // + // take a copy + // + $p = $this->_packet; + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $p->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $p->header->qdcount = cacti_sizeof($p->question); + $p->header->ancount = cacti_sizeof($p->answer); + $p->header->nscount = cacti_sizeof($p->authority); + $p->header->arcount = cacti_sizeof($p->additional); + + return $p; + } + + /** + * executes the notify request. + * + * @param Net_DNS2_Packet_Response &$response ref to the response object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function notify(&$response = null) { + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $this->_packet->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); + $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); + $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); + $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); + + // + // make sure we have some data to send + // + if ($this->_packet->header->qdcount == 0) { + throw new Net_DNS2_Exception( + 'empty headers- nothing to send!', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + // + // send the packet and get back the response + // + $response = $this->sendPacket($this->_packet, $this->use_tcp); + + // + // clear the internal packet so if we make another request, we don't have + // old data being sent. + // + $this->_packet->reset(); + + // + // for notifies, we just need to know it worked- we don't actually need to + // return the response object + // + return true; + } + + /** + * checks that the given name matches the name for the zone we're notifying. + * + * @param string $name the name to be checked + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + private function _checkName($name) { + if (!preg_match('/' . $this->_packet->question[0]->qname . '$/', $name)) { + throw new Net_DNS2_Exception( + 'name provided (' . $name . ') does not match zone name (' + . $this->_packet->question[0]->qname . ')', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + return true; + } } diff --git a/Net/DNS2/Packet.php b/Net/DNS2/Packet.php index 466a1735..863f18bb 100644 --- a/Net/DNS2/Packet.php +++ b/Net/DNS2/Packet.php @@ -31,324 +31,325 @@ * The Net_DNS2_Packet_Request and Net_DNS2_Packet_Response classes extend this * class. */ -class Net_DNS2_Packet -{ - // the full binary data and length for this packet - public $rdata; - public $rdlength; - - // the offset pointer used when building/parsing packets - public $offset = 0; - - // Net_DNS2_Header object with the DNS packet header - public $header; - - /* - * array of Net_DNS2_Question objects - * - * used as "zone" for updates per RFC2136 - * - */ - public $question = []; - - /* - * array of Net_DNS2_RR Objects for Answers - * - * used as "prerequisite" for updates per RFC2136 - * - */ - public $answer = []; - - /* - * array of Net_DNS2_RR Objects for Authority - * - * used as "update" for updates per RFC2136 - * - */ - public $authority = []; - - // array of Net_DNS2_RR Objects for Additional - public $additional = []; - - // array of compressed labeles - private $_compressed = []; - - /** - * magic __toString() method to return the Net_DNS2_Packet as a string. - * - * @return string - */ - public function __toString() - { - $output = $this->header->__toString(); - - foreach ($this->question as $x) { - $output .= $x->__toString()."\n"; - } - foreach ($this->answer as $x) { - $output .= $x->__toString()."\n"; - } - foreach ($this->authority as $x) { - $output .= $x->__toString()."\n"; - } - foreach ($this->additional as $x) { - $output .= $x->__toString()."\n"; - } - - return $output; - } - - /** - * returns a full binary DNS packet. - * - * @return string - * - * @throws Net_DNS2_Exception - */ - public function get() - { - $data = $this->header->get($this); - - foreach ($this->question as $x) { - $data .= $x->get($this); - } - foreach ($this->answer as $x) { - $data .= $x->get($this); - } - foreach ($this->authority as $x) { - $data .= $x->get($this); - } - foreach ($this->additional as $x) { - $data .= $x->get($this); - } - - return $data; - } - - /** - * applies a standard DNS name compression on the given name/offset. - * - * This logic was based on the Net::DNS::Packet::dn_comp() function - * by Michanel Fuhr - * - * @param string $name the name to be compressed - * @param int &$offset the offset into the given packet object - * - * @return string - */ - public function compress($name, &$offset) - { - // - // we're using preg_split() rather than explode() so that we can use the negative lookbehind, - // to catch cases where we have escaped dots in strings. - // - // there's only a few cases like this- the rname in SOA for example - // - $names = str_replace('\.', '.', preg_split('/(?_compressed[$dname])) { - $compname .= pack('n', 0xC000 | $this->_compressed[$dname]); - $offset += 2; - - break; - } - - $this->_compressed[$dname] = $offset; - - $first = array_shift($names); - - $length = strlen($first); - if ($length <= 0) { - continue; - } - - // - // truncate see RFC1035 2.3.1 - // - if ($length > 63) { - $length = 63; - $first = substr($first, 0, $length); - } - - $compname .= pack('Ca*', $length, $first); - $offset += $length + 1; - } - - if (empty($names)) { - $compname .= pack('C', 0); - ++$offset; - } - - return $compname; - } - - /** - * applies a standard DNS name compression on the given name/offset. - * - * This logic was based on the Net::DNS::Packet::dn_comp() function - * by Michanel Fuhr - * - * @param string $name the name to be compressed - * - * @return string - */ - public static function pack($name) - { - $offset = 0; - $names = explode('.', $name); - $compname = ''; - - while (!empty($names)) { - $first = array_shift($names); - $length = strlen($first); - - $compname .= pack('Ca*', $length, $first); - $offset += $length + 1; - } - - $compname .= "\0"; - ++$offset; - - return $compname; - } - - /** - * expands the domain name stored at a given offset in a DNS Packet. - * - * This logic was based on the Net::DNS::Packet::dn_expand() function - * by Michanel Fuhr - * - * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name - * @param int &$offset the offset into the given packet object - * @param bool $escape_dot_literals if we should escape periods in names - * - * @return mixed either the domain name or null if it's not found - */ - public static function expand(Net_DNS2_Packet &$packet, &$offset, $escape_dot_literals = false) - { - $name = ''; - - while (1) { - if ($packet->rdlength < ($offset + 1)) { - return null; - } - - $xlen = ord($packet->rdata[$offset]); - if (0 == $xlen) { - ++$offset; - - break; - } - if (($xlen & 0xC0) == 0xC0) { - if ($packet->rdlength < ($offset + 2)) { - return null; - } - - $ptr = ord($packet->rdata[$offset]) << 8 | ord($packet->rdata[$offset + 1]); - $ptr = $ptr & 0x3FFF; - - $name2 = Net_DNS2_Packet::expand($packet, $ptr); - if (is_null($name2)) { - return null; - } - - $name .= $name2; - $offset += 2; - - break; - } - ++$offset; - - if ($packet->rdlength < ($offset + $xlen)) { - return null; - } - - $elem = ''; - $elem = substr($packet->rdata, $offset, $xlen); - - // - // escape literal dots in certain cases (SOA rname) - // - if ((true == $escape_dot_literals) && (false !== strpos($elem, '.'))) { - $elem = str_replace('.', '\.', $elem); - } - - $name .= $elem.'.'; - $offset += $xlen; - } - - return trim($name, '.'); - } - - /** - * parses a domain label from a DNS Packet at the given offset. - * - * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name - * @param int &$offset the offset into the given packet object - * - * @return mixed either the domain name or null if it's not found - */ - public static function label(Net_DNS2_Packet &$packet, &$offset) - { - $name = ''; - - if ($packet->rdlength < ($offset + 1)) { - return null; - } - - $xlen = ord($packet->rdata[$offset]); - ++$offset; - - if (($xlen + $offset) > $packet->rdlength) { - $name = substr($packet->rdata, $offset); - $offset = $packet->rdlength; - } else { - $name = substr($packet->rdata, $offset, $xlen); - $offset += $xlen; - } - - return $name; - } - - /** - * copies the contents of the given packet, to the local packet object. this - * function intentionally ignores some of the packet data. - * - * @param Net_DNS2_Packet $packet the DNS packet to copy the data from - * - * @return bool - */ - public function copy(Net_DNS2_Packet $packet) - { - $this->header = $packet->header; - $this->question = $packet->question; - $this->answer = $packet->answer; - $this->authority = $packet->authority; - $this->additional = $packet->additional; - - return true; - } - - /** - * resets the values in the current packet object. - * - * @return bool - */ - public function reset() - { - $this->header->id = $this->header->nextPacketId(); - $this->rdata = ''; - $this->rdlength = 0; - $this->offset = 0; - $this->answer = []; - $this->authority = []; - $this->additional = []; - $this->_compressed = []; - - return true; - } +class Net_DNS2_Packet { + // the full binary data and length for this packet + public $rdata; + public $rdlength; + + // the offset pointer used when building/parsing packets + public $offset = 0; + + // Net_DNS2_Header object with the DNS packet header + public $header; + + /* + * array of Net_DNS2_Question objects + * + * used as "zone" for updates per RFC2136 + * + */ + public $question = []; + + /* + * array of Net_DNS2_RR Objects for Answers + * + * used as "prerequisite" for updates per RFC2136 + * + */ + public $answer = []; + + /* + * array of Net_DNS2_RR Objects for Authority + * + * used as "update" for updates per RFC2136 + * + */ + public $authority = []; + + // array of Net_DNS2_RR Objects for Additional + public $additional = []; + + // array of compressed labeles + private $_compressed = []; + + /** + * magic __toString() method to return the Net_DNS2_Packet as a string. + * + * @return string + */ + public function __toString() { + $output = $this->header->__toString(); + + foreach ($this->question as $x) { + $output .= $x->__toString() . "\n"; + } + + foreach ($this->answer as $x) { + $output .= $x->__toString() . "\n"; + } + + foreach ($this->authority as $x) { + $output .= $x->__toString() . "\n"; + } + + foreach ($this->additional as $x) { + $output .= $x->__toString() . "\n"; + } + + return $output; + } + + /** + * returns a full binary DNS packet. + * + * @return string + * + * @throws Net_DNS2_Exception + */ + public function get() { + $data = $this->header->get($this); + + foreach ($this->question as $x) { + $data .= $x->get($this); + } + + foreach ($this->answer as $x) { + $data .= $x->get($this); + } + + foreach ($this->authority as $x) { + $data .= $x->get($this); + } + + foreach ($this->additional as $x) { + $data .= $x->get($this); + } + + return $data; + } + + /** + * applies a standard DNS name compression on the given name/offset. + * + * This logic was based on the Net::DNS::Packet::dn_comp() function + * by Michanel Fuhr + * + * @param string $name the name to be compressed + * @param int &$offset the offset into the given packet object + * + * @return string + */ + public function compress($name, &$offset) { + // + // we're using preg_split() rather than explode() so that we can use the negative lookbehind, + // to catch cases where we have escaped dots in strings. + // + // there's only a few cases like this- the rname in SOA for example + // + $names = str_replace('\.', '.', preg_split('/(?_compressed[$dname])) { + $compname .= pack('n', 0xC000 | $this->_compressed[$dname]); + $offset += 2; + + break; + } + + $this->_compressed[$dname] = $offset; + + $first = array_shift($names); + + $length = strlen($first); + + if ($length <= 0) { + continue; + } + + // + // truncate see RFC1035 2.3.1 + // + if ($length > 63) { + $length = 63; + $first = substr($first, 0, $length); + } + + $compname .= pack('Ca*', $length, $first); + $offset += $length + 1; + } + + if (empty($names)) { + $compname .= pack('C', 0); + ++$offset; + } + + return $compname; + } + + /** + * applies a standard DNS name compression on the given name/offset. + * + * This logic was based on the Net::DNS::Packet::dn_comp() function + * by Michanel Fuhr + * + * @param string $name the name to be compressed + * + * @return string + */ + public static function pack($name) { + $offset = 0; + $names = explode('.', $name); + $compname = ''; + + while (!empty($names)) { + $first = array_shift($names); + $length = strlen($first); + + $compname .= pack('Ca*', $length, $first); + $offset += $length + 1; + } + + $compname .= "\0"; + ++$offset; + + return $compname; + } + + /** + * expands the domain name stored at a given offset in a DNS Packet. + * + * This logic was based on the Net::DNS::Packet::dn_expand() function + * by Michanel Fuhr + * + * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name + * @param int &$offset the offset into the given packet object + * @param bool $escape_dot_literals if we should escape periods in names + * + * @return mixed either the domain name or null if it's not found + */ + public static function expand(Net_DNS2_Packet &$packet, &$offset, $escape_dot_literals = false) { + $name = ''; + + while (1) { + if ($packet->rdlength < ($offset + 1)) { + return null; + } + + $xlen = ord($packet->rdata[$offset]); + + if ($xlen == 0) { + ++$offset; + + break; + } + + if (($xlen & 0xC0) == 0xC0) { + if ($packet->rdlength < ($offset + 2)) { + return null; + } + + $ptr = ord($packet->rdata[$offset]) << 8 | ord($packet->rdata[$offset + 1]); + $ptr = $ptr & 0x3FFF; + + $name2 = Net_DNS2_Packet::expand($packet, $ptr); + + if (is_null($name2)) { + return null; + } + + $name .= $name2; + $offset += 2; + + break; + } + ++$offset; + + if ($packet->rdlength < ($offset + $xlen)) { + return null; + } + + $elem = ''; + $elem = substr($packet->rdata, $offset, $xlen); + + // + // escape literal dots in certain cases (SOA rname) + // + if (($escape_dot_literals == true) && (strpos($elem, '.') !== false)) { + $elem = str_replace('.', '\.', $elem); + } + + $name .= $elem . '.'; + $offset += $xlen; + } + + return trim($name, '.'); + } + + /** + * parses a domain label from a DNS Packet at the given offset. + * + * @param Net_DNS2_Packet &$packet the DNS packet to look in for the domain name + * @param int &$offset the offset into the given packet object + * + * @return mixed either the domain name or null if it's not found + */ + public static function label(Net_DNS2_Packet &$packet, &$offset) { + $name = ''; + + if ($packet->rdlength < ($offset + 1)) { + return null; + } + + $xlen = ord($packet->rdata[$offset]); + ++$offset; + + if (($xlen + $offset) > $packet->rdlength) { + $name = substr($packet->rdata, $offset); + $offset = $packet->rdlength; + } else { + $name = substr($packet->rdata, $offset, $xlen); + $offset += $xlen; + } + + return $name; + } + + /** + * copies the contents of the given packet, to the local packet object. this + * function intentionally ignores some of the packet data. + * + * @param Net_DNS2_Packet $packet the DNS packet to copy the data from + * + * @return bool + */ + public function copy(Net_DNS2_Packet $packet) { + $this->header = $packet->header; + $this->question = $packet->question; + $this->answer = $packet->answer; + $this->authority = $packet->authority; + $this->additional = $packet->additional; + + return true; + } + + /** + * resets the values in the current packet object. + * + * @return bool + */ + public function reset() { + $this->header->id = $this->header->nextPacketId(); + $this->rdata = ''; + $this->rdlength = 0; + $this->offset = 0; + $this->answer = []; + $this->authority = []; + $this->additional = []; + $this->_compressed = []; + + return true; + } } diff --git a/Net/DNS2/Packet/Request.php b/Net/DNS2/Packet/Request.php index 92391ee3..2483fe1e 100644 --- a/Net/DNS2/Packet/Request.php +++ b/Net/DNS2/Packet/Request.php @@ -21,136 +21,134 @@ * This class handles building new DNS request packets; packets used for DNS * queries and updates. */ -class Net_DNS2_Packet_Request extends Net_DNS2_Packet -{ - /** - * Constructor - builds a new Net_DNS2_Packet_Request object. - * - * @param string $name the domain name for the packet - * @param string $type the DNS RR type for the packet - * @param string $class the DNS class for the packet - * - * @throws Net_DNS2_Exception - */ - public function __construct($name, $type = null, $class = null) - { - $this->set($name, $type, $class); - } - - /** - * builds a new Net_DNS2_Packet_Request object. - * - * @param string $name the domain name for the packet - * @param string $type the DNS RR type for the packet - * @param string $class the DNS class for the packet - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function set($name, $type = 'A', $class = 'IN') - { - // - // generate a new header - // - $this->header = new Net_DNS2_Header(); - - // - // add a new question - // - $q = new Net_DNS2_Question(); - - // - // allow queries directly to . for the root name servers - // - if ('.' != $name) { - $name = trim(strtolower($name), " \t\n\r\0\x0B."); - } - - $type = strtoupper(trim($type)); - $class = strtoupper(trim($class)); - - // - // check that the input string has some data in it - // - if (empty($name)) { - throw new Net_DNS2_Exception( - 'empty query string provided', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - // - // if the type is "*", rename it to "ANY"- both are acceptable. - // - if ('*' == $type) { - $type = 'ANY'; - } - - // - // check that the type and class are valid - // - if ((!isset(Net_DNS2_Lookups::$rr_types_by_name[$type])) - || (!isset(Net_DNS2_Lookups::$classes_by_name[$class])) - ) { - throw new Net_DNS2_Exception( - 'invalid type ('.$type.') or class ('.$class.') specified.', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - if ('PTR' == $type) { - // - // if it's a PTR request for an IP address, then make sure we tack on - // the arpa domain. - // - // there are other types of PTR requests, so if an IP adress doesn't match, - // then just let it flow through and assume it's a hostname - // - if (true == Net_DNS2::isIPv4($name)) { - // - // IPv4 - // - $name = implode('.', array_reverse(explode('.', $name))); - $name .= '.in-addr.arpa'; - } elseif (true == Net_DNS2::isIPv6($name)) { - // - // IPv6 - // - $e = Net_DNS2::expandIPv6($name); - if (false !== $e) { - $name = implode( - '.', - array_reverse(str_split(str_replace(':', '', $e))) - ); - - $name .= '.ip6.arpa'; - } else { - throw new Net_DNS2_Exception( - 'unsupported PTR value: '.$name, - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - } - } - - // - // store the data - // - $q->qname = $name; - $q->qtype = $type; - $q->qclass = $class; - - $this->question[] = $q; - - // - // the answer, authority and additional are empty; they can be modified - // after the request is created for UPDATE requests if needed. - // - $this->answer = []; - $this->authority = []; - $this->additional = []; - - return true; - } +class Net_DNS2_Packet_Request extends Net_DNS2_Packet { + /** + * Constructor - builds a new Net_DNS2_Packet_Request object. + * + * @param string $name the domain name for the packet + * @param string $type the DNS RR type for the packet + * @param string $class the DNS class for the packet + * + * @throws Net_DNS2_Exception + */ + public function __construct($name, $type = null, $class = null) { + $this->set($name, $type, $class); + } + + /** + * builds a new Net_DNS2_Packet_Request object. + * + * @param string $name the domain name for the packet + * @param string $type the DNS RR type for the packet + * @param string $class the DNS class for the packet + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function set($name, $type = 'A', $class = 'IN') { + // + // generate a new header + // + $this->header = new Net_DNS2_Header(); + + // + // add a new question + // + $q = new Net_DNS2_Question(); + + // + // allow queries directly to . for the root name servers + // + if ($name != '.') { + $name = trim(strtolower($name), " \t\n\r\0\x0B."); + } + + $type = strtoupper(trim($type)); + $class = strtoupper(trim($class)); + + // + // check that the input string has some data in it + // + if (empty($name)) { + throw new Net_DNS2_Exception( + 'empty query string provided', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + // + // if the type is "*", rename it to "ANY"- both are acceptable. + // + if ($type == '*') { + $type = 'ANY'; + } + + // + // check that the type and class are valid + // + if ((!isset(Net_DNS2_Lookups::$rr_types_by_name[$type])) + || (!isset(Net_DNS2_Lookups::$classes_by_name[$class])) + ) { + throw new Net_DNS2_Exception( + 'invalid type (' . $type . ') or class (' . $class . ') specified.', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + if ($type == 'PTR') { + // + // if it's a PTR request for an IP address, then make sure we tack on + // the arpa domain. + // + // there are other types of PTR requests, so if an IP adress doesn't match, + // then just let it flow through and assume it's a hostname + // + if (Net_DNS2::isIPv4($name) == true) { + // + // IPv4 + // + $name = implode('.', array_reverse(explode('.', $name))); + $name .= '.in-addr.arpa'; + } elseif (Net_DNS2::isIPv6($name) == true) { + // + // IPv6 + // + $e = Net_DNS2::expandIPv6($name); + + if ($e !== false) { + $name = implode( + '.', + array_reverse(str_split(str_replace(':', '', $e))) + ); + + $name .= '.ip6.arpa'; + } else { + throw new Net_DNS2_Exception( + 'unsupported PTR value: ' . $name, + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + } + } + + // + // store the data + // + $q->qname = $name; + $q->qtype = $type; + $q->qclass = $class; + + $this->question[] = $q; + + // + // the answer, authority and additional are empty; they can be modified + // after the request is created for UPDATE requests if needed. + // + $this->answer = []; + $this->authority = []; + $this->additional = []; + + return true; + } } diff --git a/Net/DNS2/Packet/Response.php b/Net/DNS2/Packet/Response.php index a5d1f0a4..4849f734 100644 --- a/Net/DNS2/Packet/Response.php +++ b/Net/DNS2/Packet/Response.php @@ -21,107 +21,107 @@ * This class handles building new DNS response packets; it parses binary packed * packets that come off the wire. */ -class Net_DNS2_Packet_Response extends Net_DNS2_Packet -{ - // The name servers that this response came from - public $answer_from; - - // The socket type the answer came from (TCP/UDP) - public $answer_socket_type; - - // The query response time in microseconds - public $response_time = 0; - - /** - * Constructor - builds a new Net_DNS2_Packet_Response object. - * - * @param string $data binary DNS packet - * @param int $size the length of the DNS packet - * - * @throws Net_DNS2_Exception - */ - public function __construct($data, $size) - { - $this->set($data, $size); - } - - /** - * builds a new Net_DNS2_Packet_Response object. - * - * @param string $data binary DNS packet - * @param int $size the length of the DNS packet - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function set($data, $size) - { - // - // store the full packet - // - $this->rdata = $data; - $this->rdlength = $size; - - // - // parse the header - // - // we don't bother checking the size earlier, because the first thing the - // header class does, is check the size and throw and exception if it's - // invalid. - // - $this->header = new Net_DNS2_Header($this); - - // - // if the truncation bit is set, then just return right here, because the - // rest of the packet is probably empty; and there's no point in processing - // anything else. - // - // we also don't need to worry about checking to see if the the header is - // null or not, since the Net_DNS2_Header() constructor will throw an - // exception if the packet is invalid. - // - if (1 == $this->header->tc) { - return false; - } - - // - // parse the questions - // - for ($x = 0; $x < $this->header->qdcount; ++$x) { - $this->question[$x] = new Net_DNS2_Question($this); - } - - // - // parse the answers - // - for ($x = 0; $x < $this->header->ancount; ++$x) { - $o = Net_DNS2_RR::parse($this); - if (!is_null($o)) { - $this->answer[] = $o; - } - } - - // - // parse the authority section - // - for ($x = 0; $x < $this->header->nscount; ++$x) { - $o = Net_DNS2_RR::parse($this); - if (!is_null($o)) { - $this->authority[] = $o; - } - } - - // - // parse the additional section - // - for ($x = 0; $x < $this->header->arcount; ++$x) { - $o = Net_DNS2_RR::parse($this); - if (!is_null($o)) { - $this->additional[] = $o; - } - } - - return true; - } +class Net_DNS2_Packet_Response extends Net_DNS2_Packet { + // The name servers that this response came from + public $answer_from; + + // The socket type the answer came from (TCP/UDP) + public $answer_socket_type; + + // The query response time in microseconds + public $response_time = 0; + + /** + * Constructor - builds a new Net_DNS2_Packet_Response object. + * + * @param string $data binary DNS packet + * @param int $size the length of the DNS packet + * + * @throws Net_DNS2_Exception + */ + public function __construct($data, $size) { + $this->set($data, $size); + } + + /** + * builds a new Net_DNS2_Packet_Response object. + * + * @param string $data binary DNS packet + * @param int $size the length of the DNS packet + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function set($data, $size) { + // + // store the full packet + // + $this->rdata = $data; + $this->rdlength = $size; + + // + // parse the header + // + // we don't bother checking the size earlier, because the first thing the + // header class does, is check the size and throw and exception if it's + // invalid. + // + $this->header = new Net_DNS2_Header($this); + + // + // if the truncation bit is set, then just return right here, because the + // rest of the packet is probably empty; and there's no point in processing + // anything else. + // + // we also don't need to worry about checking to see if the the header is + // null or not, since the Net_DNS2_Header() constructor will throw an + // exception if the packet is invalid. + // + if ($this->header->tc == 1) { + return false; + } + + // + // parse the questions + // + for ($x = 0; $x < $this->header->qdcount; ++$x) { + $this->question[$x] = new Net_DNS2_Question($this); + } + + // + // parse the answers + // + for ($x = 0; $x < $this->header->ancount; ++$x) { + $o = Net_DNS2_RR::parse($this); + + if (!is_null($o)) { + $this->answer[] = $o; + } + } + + // + // parse the authority section + // + for ($x = 0; $x < $this->header->nscount; ++$x) { + $o = Net_DNS2_RR::parse($this); + + if (!is_null($o)) { + $this->authority[] = $o; + } + } + + // + // parse the additional section + // + for ($x = 0; $x < $this->header->arcount; ++$x) { + $o = Net_DNS2_RR::parse($this); + + if (!is_null($o)) { + $this->additional[] = $o; + } + } + + return true; + } } diff --git a/Net/DNS2/PrivateKey.php b/Net/DNS2/PrivateKey.php index 3aa3f713..128b9f11 100644 --- a/Net/DNS2/PrivateKey.php +++ b/Net/DNS2/PrivateKey.php @@ -20,315 +20,298 @@ /** * SSL Private Key container class. */ -class Net_DNS2_PrivateKey -{ - // the filename that was loaded; stored for reference - public $filename; - - // the keytag for the signature - public $keytag; - - // the sign name for the signature - public $signname; - - // the algorithm used for the signature - public $algorithm; - - // the key format of the signature - public $key_format; - - // the openssl private key id - public $instance; - - // DSA: prime - public $prime; - - // DSA: subprime - public $subprime; - - // DSA: base - public $base; - - // DSA: private value - public $private_value; - - // DSA: public value - public $public_value; - - // RSA: modulus - private $_modulus; - - // RSA: public exponent - private $_public_exponent; - - // RSA: rivate exponent - private $_private_exponent; - - // RSA: prime1 - private $_prime1; - - // RSA: prime2 - private $_prime2; - - // RSA: exponent 1 - private $_exponent1; - - // RSA: exponent 2 - private $_exponent2; - - // RSA: coefficient - private $_coefficient; - - /** - * Constructor - base constructor the private key container class. - * - * @param string $file path to a private-key file to parse and load - * - * @throws Net_DNS2_Exception - */ - public function __construct($file = null) - { - if (isset($file)) { - $this->parseFile($file); - } - } - - /** - * parses a private key file generated by dnssec-keygen. - * - * @param string $file path to a private-key file to parse and load - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function parseFile($file) - { - // - // check for OpenSSL - // - if (false === extension_loaded('openssl')) { - throw new Net_DNS2_Exception( - 'the OpenSSL extension is required to use parse private key.', - Net_DNS2_Lookups::E_OPENSSL_UNAVAIL - ); - } - - // - // check to make sure the file exists - // - if (false == is_readable($file)) { - throw new Net_DNS2_Exception( - 'invalid private key file: '.$file, - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // get the base filename, and parse it for the local value - // - $keyname = basename($file); - if (0 == strlen($keyname)) { - throw new Net_DNS2_Exception( - 'failed to get basename() for: '.$file, - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // parse the keyname - // - if (preg_match('/K(.*)\\.\\+(\\d{3})\\+(\\d*)\\.private/', $keyname, $matches)) { - $this->signname = $matches[1]; - $this->algorithm = intval($matches[2]); - $this->keytag = intval($matches[3]); - } else { - throw new Net_DNS2_Exception( - 'file '.$keyname.' does not look like a private key file!', - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // read all the data from the - // - $data = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if (0 == cacti_sizeof($data)) { - throw new Net_DNS2_Exception( - 'file '.$keyname.' is empty!', - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - foreach ($data as $line) { - list($key, $value) = explode(':', $line); - - $key = trim($key); - $value = trim($value); - - switch (strtolower($key)) { - case 'private-key-format': - $this->key_format = $value; - - break; - - case 'algorithm': - if ($this->algorithm != $value) { - throw new Net_DNS2_Exception( - 'Algorithm mismatch! filename is '.$this->algorithm - .', contents say '.$value, - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - break; - - // - // RSA - // - case 'modulus': - $this->_modulus = $value; - - break; - - case 'publicexponent': - $this->_public_exponent = $value; - - break; - - case 'privateexponent': - $this->_private_exponent = $value; - - break; - - case 'prime1': - $this->_prime1 = $value; - - break; - - case 'prime2': - $this->_prime2 = $value; - - break; - - case 'exponent1': - $this->_exponent1 = $value; - - break; - - case 'exponent2': - $this->_exponent2 = $value; - - break; - - case 'coefficient': - $this->_coefficient = $value; - - break; - - // - // DSA - this won't work in PHP until the OpenSSL extension is better - // - case 'prime(p)': - $this->prime = $value; - - break; - - case 'subprime(q)': - $this->subprime = $value; - - break; - - case 'base(g)': - $this->base = $value; - - break; - - case 'private_value(x)': - $this->private_value = $value; - - break; - - case 'public_value(y)': - $this->public_value = $value; - - break; - - default: - throw new Net_DNS2_Exception( - 'unknown private key data: '.$key.': '.$value, - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - } - - // - // generate the private key - // - $args = []; - - switch ($this->algorithm) { - // - // RSA - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - $args = [ - 'rsa' => [ - 'n' => base64_decode($this->_modulus), - 'e' => base64_decode($this->_public_exponent), - 'd' => base64_decode($this->_private_exponent), - 'p' => base64_decode($this->_prime1), - 'q' => base64_decode($this->_prime2), - 'dmp1' => base64_decode($this->_exponent1), - 'dmq1' => base64_decode($this->_exponent2), - 'iqmp' => base64_decode($this->_coefficient), - ], - ]; - - break; - - // - // DSA - this won't work in PHP until the OpenSSL extension is better - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: - $args = [ - 'dsa' => [ - 'p' => base64_decode($this->prime), - 'q' => base64_decode($this->subprime), - 'g' => base64_decode($this->base), - 'priv_key' => base64_decode($this->private_value), - 'pub_key' => base64_decode($this->public_value), - ], - ]; - - break; - - default: - throw new Net_DNS2_Exception( - 'we only currently support RSAMD5 and RSASHA1 encryption.', - Net_DNS2_Lookups::E_OPENSSL_INV_PKEY - ); - } - - // - // generate and store the key - // - $this->instance = openssl_pkey_new($args); - if (false === $this->instance) { - throw new Net_DNS2_Exception( - openssl_error_string(), - Net_DNS2_Lookups::E_OPENSSL_ERROR - ); - } - - // - // store the filename incase we need it for something - // - $this->filename = $file; - - return true; - } +class Net_DNS2_PrivateKey { + // the filename that was loaded; stored for reference + public $filename; + + // the keytag for the signature + public $keytag; + + // the sign name for the signature + public $signname; + + // the algorithm used for the signature + public $algorithm; + + // the key format of the signature + public $key_format; + + // the openssl private key id + public $instance; + + // DSA: prime + public $prime; + + // DSA: subprime + public $subprime; + + // DSA: base + public $base; + + // DSA: private value + public $private_value; + + // DSA: public value + public $public_value; + + // RSA: modulus + private $_modulus; + + // RSA: public exponent + private $_public_exponent; + + // RSA: rivate exponent + private $_private_exponent; + + // RSA: prime1 + private $_prime1; + + // RSA: prime2 + private $_prime2; + + // RSA: exponent 1 + private $_exponent1; + + // RSA: exponent 2 + private $_exponent2; + + // RSA: coefficient + private $_coefficient; + + /** + * Constructor - base constructor the private key container class. + * + * @param string $file path to a private-key file to parse and load + * + * @throws Net_DNS2_Exception + */ + public function __construct($file = null) { + if (isset($file)) { + $this->parseFile($file); + } + } + + /** + * parses a private key file generated by dnssec-keygen. + * + * @param string $file path to a private-key file to parse and load + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function parseFile($file) { + // + // check for OpenSSL + // + if (extension_loaded('openssl') === false) { + throw new Net_DNS2_Exception( + 'the OpenSSL extension is required to use parse private key.', + Net_DNS2_Lookups::E_OPENSSL_UNAVAIL + ); + } + + // + // check to make sure the file exists + // + if (is_readable($file) == false) { + throw new Net_DNS2_Exception( + 'invalid private key file: ' . $file, + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // get the base filename, and parse it for the local value + // + $keyname = basename($file); + + if (strlen($keyname) == 0) { + throw new Net_DNS2_Exception( + 'failed to get basename() for: ' . $file, + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // parse the keyname + // + if (preg_match('/K(.*)\\.\\+(\\d{3})\\+(\\d*)\\.private/', $keyname, $matches)) { + $this->signname = $matches[1]; + $this->algorithm = intval($matches[2]); + $this->keytag = intval($matches[3]); + } else { + throw new Net_DNS2_Exception( + 'file ' . $keyname . ' does not look like a private key file!', + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // read all the data from the + // + $data = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + + if (cacti_sizeof($data) == 0) { + throw new Net_DNS2_Exception( + 'file ' . $keyname . ' is empty!', + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + foreach ($data as $line) { + [$key, $value] = explode(':', $line); + + $key = trim($key); + $value = trim($value); + + switch (strtolower($key)) { + case 'private-key-format': + $this->key_format = $value; + + break; + case 'algorithm': + if ($this->algorithm != $value) { + throw new Net_DNS2_Exception( + 'Algorithm mismatch! filename is ' . $this->algorithm + . ', contents say ' . $value, + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + break; + // + // RSA + // + case 'modulus': + $this->_modulus = $value; + + break; + case 'publicexponent': + $this->_public_exponent = $value; + + break; + case 'privateexponent': + $this->_private_exponent = $value; + + break; + case 'prime1': + $this->_prime1 = $value; + + break; + case 'prime2': + $this->_prime2 = $value; + + break; + case 'exponent1': + $this->_exponent1 = $value; + + break; + case 'exponent2': + $this->_exponent2 = $value; + + break; + case 'coefficient': + $this->_coefficient = $value; + + break; + // + // DSA - this won't work in PHP until the OpenSSL extension is better + // + case 'prime(p)': + $this->prime = $value; + + break; + case 'subprime(q)': + $this->subprime = $value; + + break; + case 'base(g)': + $this->base = $value; + + break; + case 'private_value(x)': + $this->private_value = $value; + + break; + case 'public_value(y)': + $this->public_value = $value; + + break; + default: + throw new Net_DNS2_Exception( + 'unknown private key data: ' . $key . ': ' . $value, + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + } + + // + // generate the private key + // + $args = []; + + switch ($this->algorithm) { + // + // RSA + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + $args = [ + 'rsa' => [ + 'n' => base64_decode($this->_modulus, true), + 'e' => base64_decode($this->_public_exponent, true), + 'd' => base64_decode($this->_private_exponent, true), + 'p' => base64_decode($this->_prime1, true), + 'q' => base64_decode($this->_prime2, true), + 'dmp1' => base64_decode($this->_exponent1, true), + 'dmq1' => base64_decode($this->_exponent2, true), + 'iqmp' => base64_decode($this->_coefficient, true), + ], + ]; + + break; + // + // DSA - this won't work in PHP until the OpenSSL extension is better + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: + $args = [ + 'dsa' => [ + 'p' => base64_decode($this->prime, true), + 'q' => base64_decode($this->subprime, true), + 'g' => base64_decode($this->base, true), + 'priv_key' => base64_decode($this->private_value, true), + 'pub_key' => base64_decode($this->public_value, true), + ], + ]; + + break; + default: + throw new Net_DNS2_Exception( + 'we only currently support RSAMD5 and RSASHA1 encryption.', + Net_DNS2_Lookups::E_OPENSSL_INV_PKEY + ); + } + + // + // generate and store the key + // + $this->instance = openssl_pkey_new($args); + + if ($this->instance === false) { + throw new Net_DNS2_Exception( + openssl_error_string(), + Net_DNS2_Lookups::E_OPENSSL_ERROR + ); + } + + // + // store the filename incase we need it for something + // + $this->filename = $file; + + return true; + } } diff --git a/Net/DNS2/Question.php b/Net/DNS2/Question.php index aa7393ec..0c127770 100644 --- a/Net/DNS2/Question.php +++ b/Net/DNS2/Question.php @@ -36,149 +36,145 @@ * | QCLASS | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_Question -{ - /* - * The name of the question - * - * referred to as "zname" for updates per RFC2136 - * - */ - public $qname; - - /* - * The RR type for the questino - * - * referred to as "ztype" for updates per RFC2136 - * - */ - public $qtype; - - /* - * The RR class for the questino - * - * referred to as "zclass" for updates per RFC2136 - * - */ - public $qclass; - - /** - * Constructor - builds a new Net_DNS2_Question object. - * - * @param mixed &$packet either a Net_DNS2_Packet object, or null to - * build an empty object - * - * @throws Net_DNS2_Exception - */ - public function __construct(?Net_DNS2_Packet &$packet = null) - { - if (!is_null($packet)) { - $this->set($packet); - } else { - $this->qname = ''; - $this->qtype = 'A'; - $this->qclass = 'IN'; - } - } - - /** - * magic __toString() function to return the Net_DNS2_Question object as a string. - * - * @return string - */ - public function __toString() - { - return ";;\n;; Question:\n;;\t ".$this->qname.'. ' - .$this->qtype.' '.$this->qclass."\n"; - } - - /** - * builds a new Net_DNS2_Header object from a Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet object - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function set(Net_DNS2_Packet &$packet) - { - // - // expand the name - // - $this->qname = $packet->expand($packet, $packet->offset); - if ($packet->rdlength < ($packet->offset + 4)) { - throw new Net_DNS2_Exception( - 'invalid question section: to small', - Net_DNS2_Lookups::E_QUESTION_INVALID - ); - } - - // - // unpack the type and class - // - $type = ord($packet->rdata[$packet->offset++]) << 8 - | ord($packet->rdata[$packet->offset++]); - $class = ord($packet->rdata[$packet->offset++]) << 8 - | ord($packet->rdata[$packet->offset++]); - - // - // validate it - // - $type_name = Net_DNS2_Lookups::$rr_types_by_id[$type]; - $class_name = Net_DNS2_Lookups::$classes_by_id[$class]; - - if ((!isset($type_name)) || (!isset($class_name))) { - throw new Net_DNS2_Exception( - 'invalid question section: invalid type ('.$type - .') or class ('.$class.') specified.', - Net_DNS2_Lookups::E_QUESTION_INVALID - ); - } - - // - // store it - // - $this->qtype = $type_name; - $this->qclass = $class_name; - - return true; - } - - /** - * returns a binary packed Net_DNS2_Question object. - * - * @param Net_DNS2_Packet &$packet the Net_DNS2_Packet object this question is - * part of. This needs to be passed in so that - * the compressed qname value can be packed in - * with the names of the other parts of the - * packet. - * - * @return string - * - * @throws Net_DNS2_Exception - */ - public function get(Net_DNS2_Packet &$packet) - { - // - // validate the type and class - // - $type = Net_DNS2_Lookups::$rr_types_by_name[$this->qtype]; - $class = Net_DNS2_Lookups::$classes_by_name[$this->qclass]; - - if ((!isset($type)) || (!isset($class))) { - throw new Net_DNS2_Exception( - 'invalid question section: invalid type ('.$this->qtype - .') or class ('.$this->qclass.') specified.', - Net_DNS2_Lookups::E_QUESTION_INVALID - ); - } - - $data = $packet->compress($this->qname, $packet->offset); - - $data .= chr($type >> 8).chr($type).chr($class >> 8).chr($class); - $packet->offset += 4; - - return $data; - } +class Net_DNS2_Question { + /* + * The name of the question + * + * referred to as "zname" for updates per RFC2136 + * + */ + public $qname; + + /* + * The RR type for the questino + * + * referred to as "ztype" for updates per RFC2136 + * + */ + public $qtype; + + /* + * The RR class for the questino + * + * referred to as "zclass" for updates per RFC2136 + * + */ + public $qclass; + + /** + * Constructor - builds a new Net_DNS2_Question object. + * + * @param mixed &$packet either a Net_DNS2_Packet object, or null to + * build an empty object + * + * @throws Net_DNS2_Exception + */ + public function __construct(?Net_DNS2_Packet &$packet = null) { + if (!is_null($packet)) { + $this->set($packet); + } else { + $this->qname = ''; + $this->qtype = 'A'; + $this->qclass = 'IN'; + } + } + + /** + * magic __toString() function to return the Net_DNS2_Question object as a string. + * + * @return string + */ + public function __toString() { + return ";;\n;; Question:\n;;\t " . $this->qname . '. ' + . $this->qtype . ' ' . $this->qclass . "\n"; + } + + /** + * builds a new Net_DNS2_Header object from a Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function set(Net_DNS2_Packet &$packet) { + // + // expand the name + // + $this->qname = $packet->expand($packet, $packet->offset); + + if ($packet->rdlength < ($packet->offset + 4)) { + throw new Net_DNS2_Exception( + 'invalid question section: to small', + Net_DNS2_Lookups::E_QUESTION_INVALID + ); + } + + // + // unpack the type and class + // + $type = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + $class = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + // + // validate it + // + $type_name = Net_DNS2_Lookups::$rr_types_by_id[$type]; + $class_name = Net_DNS2_Lookups::$classes_by_id[$class]; + + if ((!isset($type_name)) || (!isset($class_name))) { + throw new Net_DNS2_Exception( + 'invalid question section: invalid type (' . $type + . ') or class (' . $class . ') specified.', + Net_DNS2_Lookups::E_QUESTION_INVALID + ); + } + + // + // store it + // + $this->qtype = $type_name; + $this->qclass = $class_name; + + return true; + } + + /** + * returns a binary packed Net_DNS2_Question object. + * + * @param Net_DNS2_Packet &$packet the Net_DNS2_Packet object this question is + * part of. This needs to be passed in so that + * the compressed qname value can be packed in + * with the names of the other parts of the + * packet. + * + * @return string + * + * @throws Net_DNS2_Exception + */ + public function get(Net_DNS2_Packet &$packet) { + // + // validate the type and class + // + $type = Net_DNS2_Lookups::$rr_types_by_name[$this->qtype]; + $class = Net_DNS2_Lookups::$classes_by_name[$this->qclass]; + + if ((!isset($type)) || (!isset($class))) { + throw new Net_DNS2_Exception( + 'invalid question section: invalid type (' . $this->qtype + . ') or class (' . $this->qclass . ') specified.', + Net_DNS2_Lookups::E_QUESTION_INVALID + ); + } + + $data = $packet->compress($this->qname, $packet->offset); + + $data .= chr($type >> 8) . chr($type) . chr($class >> 8) . chr($class); + $packet->offset += 4; + + return $data; + } } diff --git a/Net/DNS2/RR.php b/Net/DNS2/RR.php index 4131342c..eb489f19 100644 --- a/Net/DNS2/RR.php +++ b/Net/DNS2/RR.php @@ -49,499 +49,491 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -abstract class Net_DNS2_RR -{ - // The name of the resource record - public $name; - - // The resource record type - public $type; - - // The resource record class - public $class; - - // The time to live for this resource record - public $ttl; - - // The length of the rdata field - public $rdlength; - - // The resource record specific data as a packed binary string - public $rdata; - - /** - * Constructor - builds a new Net_DNS2_RR object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create - * an empty object - * @param array $rr an array with RR parse values or null to - * create an empty object - * - * @throws Net_DNS2_Exception - */ - public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) - { - if ((!is_null($packet)) && (!is_null($rr))) { - if (false == $this->set($packet, $rr)) { - throw new Net_DNS2_Exception( - 'failed to generate resource record', - Net_DNS2_Lookups::E_RR_INVALID - ); - } - } else { - $class = Net_DNS2_Lookups::$rr_types_class_to_id[get_class($this)]; - if (isset($class)) { - $this->type = Net_DNS2_Lookups::$rr_types_by_id[$class]; - } - - $this->class = 'IN'; - $this->ttl = 86400; - } - } - - /** - * magic __toString() method to return the Net_DNS2_RR object object as a string. - * - * @return string - */ - public function __toString() - { - return $this->name.'. '.$this->ttl.' '.$this->class - .' '.$this->type.' '.$this->rrToString(); - } - - /** - * return the same data as __toString(), but as an array, so each value can be - * used without having to parse the string. - * - * @return array - */ - public function asArray() - { - return [ - 'name' => $this->name, - 'ttl' => $this->ttl, - 'class' => $this->class, - 'type' => $this->type, - 'rdata' => $this->rrToString(), - ]; - } - - /** - * builds a new Net_DNS2_RR object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create - * an empty object - * @param array $rr an array with RR parse values or null to - * create an empty object - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function set(Net_DNS2_Packet &$packet, array $rr) - { - $this->name = $rr['name']; - $this->type = Net_DNS2_Lookups::$rr_types_by_id[$rr['type']]; - - // - // for RR OPT (41), the class value includes the requesters UDP payload size, - // and not a class value - // - if ('OPT' == $this->type) { - $this->class = $rr['class']; - } else { - $this->class = Net_DNS2_Lookups::$classes_by_id[$rr['class']]; - } - - $this->ttl = $rr['ttl']; - $this->rdlength = $rr['rdlength']; - $this->rdata = substr($packet->rdata, $packet->offset, $rr['rdlength']); - - return $this->rrSet($packet); - } - - /** - * returns a binary packed DNS RR object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for - * compressing names - * - * @return string - * - * @throws Net_DNS2_Exception - */ - public function get(Net_DNS2_Packet &$packet) - { - $data = ''; - $rdata = ''; - - // - // pack the name - // - $data = $packet->compress($this->name, $packet->offset); - - // - // pack the main values - // - if ('OPT' == $this->type) { - // - // pre-build the TTL value - // - $this->preBuild(); - - // - // the class value is different for OPT types - // - $data .= pack( - 'nnN', - Net_DNS2_Lookups::$rr_types_by_name[$this->type], - $this->class, - $this->ttl - ); - } else { - $data .= pack( - 'nnN', - Net_DNS2_Lookups::$rr_types_by_name[$this->type], - Net_DNS2_Lookups::$classes_by_name[$this->class], - $this->ttl - ); - } - - // - // increase the offset, and allow for the rdlength - // - $packet->offset += 10; - - // - // get the RR specific details - // - if (-1 != $this->rdlength) { - $rdata = $this->rrGet($packet); - } - - // - // add the RR - // - $data .= pack('n', strlen($rdata)).$rdata; - - return $data; - } - - /** - * parses a binary packet, and returns the appropriate Net_DNS2_RR object, - * based on the RR type of the binary content. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for - * decompressing names - * - * @return mixed returns a new Net_DNS2_RR_* object for - * the given RR - * - * @throws Net_DNS2_Exception - */ - public static function parse(Net_DNS2_Packet &$packet) - { - $object = []; - - // - // expand the name - // - $object['name'] = $packet->expand($packet, $packet->offset); - if (is_null($object['name'])) { - throw new Net_DNS2_Exception( - 'failed to parse resource record: failed to expand name.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - if ($packet->rdlength < ($packet->offset + 10)) { - throw new Net_DNS2_Exception( - 'failed to parse resource record: packet too small.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - // - // unpack the RR details - // - $object['type'] = ord($packet->rdata[$packet->offset++]) << 8 - | ord($packet->rdata[$packet->offset++]); - $object['class'] = ord($packet->rdata[$packet->offset++]) << 8 - | ord($packet->rdata[$packet->offset++]); - - $object['ttl'] = ord($packet->rdata[$packet->offset++]) << 24 - | ord($packet->rdata[$packet->offset++]) << 16 - | ord($packet->rdata[$packet->offset++]) << 8 - | ord($packet->rdata[$packet->offset++]); - - $object['rdlength'] = ord($packet->rdata[$packet->offset++]) << 8 - | ord($packet->rdata[$packet->offset++]); - - if ($packet->rdlength < ($packet->offset + $object['rdlength'])) { - return null; - } - - // - // lookup the class to use - // - $o = null; - $class = Net_DNS2_Lookups::$rr_types_id_to_class[$object['type']]; - - if (isset($class)) { - $o = new $class($packet, $object); - if ($o) { - $packet->offset += $object['rdlength']; - } - } else { - throw new Net_DNS2_Exception( - 'un-implemented resource record type: '.$object['type'], - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - return $o; - } - - /** - * cleans up some RR data. - * - * @param string $data the text string to clean - * - * @return string returns the cleaned string - */ - public function cleanString($data) - { - return strtolower(rtrim($data, '.')); - } - - /** - * parses a standard RR format lines, as defined by rfc1035 (kinda). - * - * In our implementation, the domain *must* be specified- format must be - * - * [] [] - * or - * [] [] - * - * name, title, class and type are parsed by this function, rdata is passed - * to the RR specific classes for parsing. - * - * @param string $line a standard DNS config line - * - * @return mixed returns a new Net_DNS2_RR_* object for the given RR - * - * @throws Net_DNS2_Exception - */ - public static function fromString($line) - { - if (0 == strlen($line)) { - throw new Net_DNS2_Exception( - 'empty config line provided.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - $name = ''; - $type = ''; - $class = 'IN'; - $ttl = 86400; - - // - // split the line by spaces - // - $values = preg_split('/[\s]+/', $line); - if (cacti_sizeof($values) < 3) { - throw new Net_DNS2_Exception( - 'failed to parse config: minimum of name, type and rdata required.', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - // - // assume the first value is the name - // - $name = trim(strtolower(array_shift($values)), '.'); - - // - // The next value is either a TTL, Class or Type - // - foreach ($values as $value) { - switch (true) { - case is_numeric($value): - $ttl = array_shift($values); - - break; - - // - // this is here because of a bug in is_numeric() in certain versions of - // PHP on windows. - // - case 0 === $value: - $ttl = array_shift($values); - - break; - - case isset(Net_DNS2_Lookups::$classes_by_name[strtoupper($value)]): - $class = strtoupper(array_shift($values)); - - break; - - case isset(Net_DNS2_Lookups::$rr_types_by_name[strtoupper($value)]): - $type = strtoupper(array_shift($values)); - - break 2; - - break; - - default: - throw new Net_DNS2_Exception( - 'invalid config line provided: unknown file: '.$value, - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - } - - // - // lookup the class to use - // - $o = null; - $class_name = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - - if (isset($class_name)) { - $o = new $class_name(); - if (!is_null($o)) { - // - // set the parsed values - // - $o->name = $name; - $o->class = $class; - $o->ttl = $ttl; - - // - // parse the rdata - // - if (false === $o->rrFromString($values)) { - throw new Net_DNS2_Exception( - 'failed to parse rdata for config: '.$line, - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - } else { - throw new Net_DNS2_Exception( - 'failed to create new RR record for type: '.$type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - } else { - throw new Net_DNS2_Exception( - 'un-implemented resource record type: '.$type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - return $o; - } - - /** - * abstract definition - method to return a RR as a string; not to - * be confused with the __toString() magic method. - * - * @return string - */ - abstract protected function rrToString(); - - /** - * abstract definition - parses a RR from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - abstract protected function rrFromString(array $rdata); - - /** - * abstract definition - sets a Net_DNS2_RR from a Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - abstract protected function rrSet(Net_DNS2_Packet &$packet); - - /** - * abstract definition - returns a binary packet DNS RR object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed string or - * null on failure - */ - abstract protected function rrGet(Net_DNS2_Packet &$packet); - - /** - * return a formatted string; if a string has spaces in it, then return - * it with double quotes around it, otherwise, return it as it was passed in. - * - * @param string $string the string to format - * - * @return string - */ - protected function formatString($string) - { - return '"'.str_replace('"', '\"', trim($string, '"')).'"'; - } - - /** - * builds an array of strings from an array of chunks of text split by spaces. - * - * @param array $chunks an array of chunks of text split by spaces - * - * @return array - */ - protected function buildString(array $chunks) - { - $data = []; - $c = 0; - $in = false; - - foreach ($chunks as $r) { - $r = trim($r); - if (0 == strlen($r)) { - continue; - } - - if (('"' == $r[0]) - && ('"' == $r[strlen($r) - 1]) - && ('\\' != $r[strlen($r) - 2]) - ) { - $data[$c] = $r; - ++$c; - $in = false; - } elseif ('"' == $r[0]) { - $data[$c] = $r; - $in = true; - } elseif (('"' == $r[strlen($r) - 1]) - && ('\\' != $r[strlen($r) - 2]) - ) { - $data[$c] .= ' '.$r; - ++$c; - $in = false; - } else { - if (true == $in) { - $data[$c] .= ' '.$r; - } else { - $data[$c++] = $r; - } - } - } - - foreach ($data as $index => $string) { - $data[$index] = str_replace('\"', '"', trim($string, '"')); - } - - return $data; - } +abstract class Net_DNS2_RR { + // The name of the resource record + public $name; + + // The resource record type + public $type; + + // The resource record class + public $class; + + // The time to live for this resource record + public $ttl; + + // The length of the rdata field + public $rdlength; + + // The resource record specific data as a packed binary string + public $rdata; + + /** + * Constructor - builds a new Net_DNS2_RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create + * an empty object + * @param array $rr an array with RR parse values or null to + * create an empty object + * + * @throws Net_DNS2_Exception + */ + public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) { + if ((!is_null($packet)) && (!is_null($rr))) { + if ($this->set($packet, $rr) == false) { + throw new Net_DNS2_Exception( + 'failed to generate resource record', + Net_DNS2_Lookups::E_RR_INVALID + ); + } + } else { + $class = Net_DNS2_Lookups::$rr_types_class_to_id[get_class($this)]; + + if (isset($class)) { + $this->type = Net_DNS2_Lookups::$rr_types_by_id[$class]; + } + + $this->class = 'IN'; + $this->ttl = 86400; + } + } + + /** + * magic __toString() method to return the Net_DNS2_RR object object as a string. + * + * @return string + */ + public function __toString() { + return $this->name . '. ' . $this->ttl . ' ' . $this->class + . ' ' . $this->type . ' ' . $this->rrToString(); + } + + /** + * return the same data as __toString(), but as an array, so each value can be + * used without having to parse the string. + * + * @return array + */ + public function asArray() { + return [ + 'name' => $this->name, + 'ttl' => $this->ttl, + 'class' => $this->class, + 'type' => $this->type, + 'rdata' => $this->rrToString(), + ]; + } + + /** + * builds a new Net_DNS2_RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create + * an empty object + * @param array $rr an array with RR parse values or null to + * create an empty object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function set(Net_DNS2_Packet &$packet, array $rr) { + $this->name = $rr['name']; + $this->type = Net_DNS2_Lookups::$rr_types_by_id[$rr['type']]; + + // + // for RR OPT (41), the class value includes the requesters UDP payload size, + // and not a class value + // + if ($this->type == 'OPT') { + $this->class = $rr['class']; + } else { + $this->class = Net_DNS2_Lookups::$classes_by_id[$rr['class']]; + } + + $this->ttl = $rr['ttl']; + $this->rdlength = $rr['rdlength']; + $this->rdata = substr($packet->rdata, $packet->offset, $rr['rdlength']); + + return $this->rrSet($packet); + } + + /** + * returns a binary packed DNS RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for + * compressing names + * + * @return string + * + * @throws Net_DNS2_Exception + */ + public function get(Net_DNS2_Packet &$packet) { + $data = ''; + $rdata = ''; + + // + // pack the name + // + $data = $packet->compress($this->name, $packet->offset); + + // + // pack the main values + // + if ($this->type == 'OPT') { + // + // pre-build the TTL value + // + $this->preBuild(); + + // + // the class value is different for OPT types + // + $data .= pack( + 'nnN', + Net_DNS2_Lookups::$rr_types_by_name[$this->type], + $this->class, + $this->ttl + ); + } else { + $data .= pack( + 'nnN', + Net_DNS2_Lookups::$rr_types_by_name[$this->type], + Net_DNS2_Lookups::$classes_by_name[$this->class], + $this->ttl + ); + } + + // + // increase the offset, and allow for the rdlength + // + $packet->offset += 10; + + // + // get the RR specific details + // + if ($this->rdlength != -1) { + $rdata = $this->rrGet($packet); + } + + // + // add the RR + // + $data .= pack('n', strlen($rdata)) . $rdata; + + return $data; + } + + /** + * parses a binary packet, and returns the appropriate Net_DNS2_RR object, + * based on the RR type of the binary content. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet used for + * decompressing names + * + * @return mixed returns a new Net_DNS2_RR_* object for + * the given RR + * + * @throws Net_DNS2_Exception + */ + public static function parse(Net_DNS2_Packet &$packet) { + $object = []; + + // + // expand the name + // + $object['name'] = $packet->expand($packet, $packet->offset); + + if (is_null($object['name'])) { + throw new Net_DNS2_Exception( + 'failed to parse resource record: failed to expand name.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + if ($packet->rdlength < ($packet->offset + 10)) { + throw new Net_DNS2_Exception( + 'failed to parse resource record: packet too small.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + // + // unpack the RR details + // + $object['type'] = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + $object['class'] = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + $object['ttl'] = ord($packet->rdata[$packet->offset++]) << 24 + | ord($packet->rdata[$packet->offset++]) << 16 + | ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + $object['rdlength'] = ord($packet->rdata[$packet->offset++]) << 8 + | ord($packet->rdata[$packet->offset++]); + + if ($packet->rdlength < ($packet->offset + $object['rdlength'])) { + return null; + } + + // + // lookup the class to use + // + $o = null; + $class = Net_DNS2_Lookups::$rr_types_id_to_class[$object['type']]; + + if (isset($class)) { + $o = new $class($packet, $object); + + if ($o) { + $packet->offset += $object['rdlength']; + } + } else { + throw new Net_DNS2_Exception( + 'un-implemented resource record type: ' . $object['type'], + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + return $o; + } + + /** + * cleans up some RR data. + * + * @param string $data the text string to clean + * + * @return string returns the cleaned string + */ + public function cleanString($data) { + return strtolower(rtrim($data, '.')); + } + + /** + * parses a standard RR format lines, as defined by rfc1035 (kinda). + * + * In our implementation, the domain *must* be specified- format must be + * + * [] [] + * or + * [] [] + * + * name, title, class and type are parsed by this function, rdata is passed + * to the RR specific classes for parsing. + * + * @param string $line a standard DNS config line + * + * @return mixed returns a new Net_DNS2_RR_* object for the given RR + * + * @throws Net_DNS2_Exception + */ + public static function fromString($line) { + if (strlen($line) == 0) { + throw new Net_DNS2_Exception( + 'empty config line provided.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + $name = ''; + $type = ''; + $class = 'IN'; + $ttl = 86400; + + // + // split the line by spaces + // + $values = preg_split('/[\s]+/', $line); + + if (cacti_sizeof($values) < 3) { + throw new Net_DNS2_Exception( + 'failed to parse config: minimum of name, type and rdata required.', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + // + // assume the first value is the name + // + $name = trim(strtolower(array_shift($values)), '.'); + + // + // The next value is either a TTL, Class or Type + // + foreach ($values as $value) { + switch (true) { + case is_numeric($value): + $ttl = array_shift($values); + + break; + // + // this is here because of a bug in is_numeric() in certain versions of + // PHP on windows. + // + case $value === 0: + $ttl = array_shift($values); + + break; + case isset(Net_DNS2_Lookups::$classes_by_name[strtoupper($value)]): + $class = strtoupper(array_shift($values)); + + break; + case isset(Net_DNS2_Lookups::$rr_types_by_name[strtoupper($value)]): + $type = strtoupper(array_shift($values)); + + break 2; + + break; + default: + throw new Net_DNS2_Exception( + 'invalid config line provided: unknown file: ' . $value, + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + } + + // + // lookup the class to use + // + $o = null; + $class_name = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + + if (isset($class_name)) { + $o = new $class_name(); + + if (!is_null($o)) { + // + // set the parsed values + // + $o->name = $name; + $o->class = $class; + $o->ttl = $ttl; + + // + // parse the rdata + // + if ($o->rrFromString($values) === false) { + throw new Net_DNS2_Exception( + 'failed to parse rdata for config: ' . $line, + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + } else { + throw new Net_DNS2_Exception( + 'failed to create new RR record for type: ' . $type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + } else { + throw new Net_DNS2_Exception( + 'un-implemented resource record type: ' . $type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + return $o; + } + + /** + * abstract definition - method to return a RR as a string; not to + * be confused with the __toString() magic method. + * + * @return string + */ + abstract protected function rrToString(); + + /** + * abstract definition - parses a RR from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + abstract protected function rrFromString(array $rdata); + + /** + * abstract definition - sets a Net_DNS2_RR from a Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + abstract protected function rrSet(Net_DNS2_Packet &$packet); + + /** + * abstract definition - returns a binary packet DNS RR object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed string or + * null on failure + */ + abstract protected function rrGet(Net_DNS2_Packet &$packet); + + /** + * return a formatted string; if a string has spaces in it, then return + * it with double quotes around it, otherwise, return it as it was passed in. + * + * @param string $string the string to format + * + * @return string + */ + protected function formatString($string) { + return '"' . str_replace('"', '\"', trim($string, '"')) . '"'; + } + + /** + * builds an array of strings from an array of chunks of text split by spaces. + * + * @param array $chunks an array of chunks of text split by spaces + * + * @return array + */ + protected function buildString(array $chunks) { + $data = []; + $c = 0; + $in = false; + + foreach ($chunks as $r) { + $r = trim($r); + + if (strlen($r) == 0) { + continue; + } + + if (($r[0] == '"') + && ($r[strlen($r) - 1] == '"') + && ($r[strlen($r) - 2] != '\\') + ) { + $data[$c] = $r; + ++$c; + $in = false; + } elseif ($r[0] == '"') { + $data[$c] = $r; + $in = true; + } elseif (($r[strlen($r) - 1] == '"') + && ($r[strlen($r) - 2] != '\\') + ) { + $data[$c] .= ' ' . $r; + ++$c; + $in = false; + } else { + if ($in == true) { + $data[$c] .= ' ' . $r; + } else { + $data[$c++] = $r; + } + } + } + + foreach ($data as $index => $string) { + $data[$index] = str_replace('\"', '"', trim($string, '"')); + } + + return $data; + } } diff --git a/Net/DNS2/RR/A.php b/Net/DNS2/RR/A.php index c40f1944..e1cd4957 100644 --- a/Net/DNS2/RR/A.php +++ b/Net/DNS2/RR/A.php @@ -24,73 +24,69 @@ * | ADDRESS | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_A extends Net_DNS2_RR -{ - // The IPv4 address in quad-dotted notation - public $address; +class Net_DNS2_RR_A extends Net_DNS2_RR { + // The IPv4 address in quad-dotted notation + public $address; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->address; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->address; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $value = array_shift($rdata); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $value = array_shift($rdata); - if (true == Net_DNS2::isIPv4($value)) { - $this->address = $value; + if (Net_DNS2::isIPv4($value) == true) { + $this->address = $value; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $this->address = inet_ntop($this->rdata); - if (false !== $this->address) { - return true; - } - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $this->address = inet_ntop($this->rdata); - return false; - } + if ($this->address !== false) { + return true; + } + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $packet->offset += 4; + return false; + } - return inet_pton($this->address); - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $packet->offset += 4; + + return inet_pton($this->address); + } } diff --git a/Net/DNS2/RR/AAAA.php b/Net/DNS2/RR/AAAA.php index e8599acb..2ed5e2c0 100644 --- a/Net/DNS2/RR/AAAA.php +++ b/Net/DNS2/RR/AAAA.php @@ -31,90 +31,87 @@ * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_AAAA extends Net_DNS2_RR -{ - /* - * the IPv6 address in the preferred hexadecimal values of the eight - * 16-bit pieces - * per RFC1884 - * - */ - public $address; +class Net_DNS2_RR_AAAA extends Net_DNS2_RR { + /* + * the IPv6 address in the preferred hexadecimal values of the eight + * 16-bit pieces + * per RFC1884 + * + */ + public $address; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->address; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->address; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // expand out compressed formats - // - $value = array_shift($rdata); - if (true == Net_DNS2::isIPv6($value)) { - $this->address = $value; + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // expand out compressed formats + // + $value = array_shift($rdata); - return true; - } + if (Net_DNS2::isIPv6($value) == true) { + $this->address = $value; - return false; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - // - // must be 8 x 16bit chunks, or 16 x 8bit - // - if (16 == $this->rdlength) { - // - // PHP's inet_ntop returns IPv6 addresses in their compressed form, - // but we want to keep with the preferred standard, so we'll parse - // it manually. - // - $x = unpack('n8', $this->rdata); - if (8 == cacti_sizeof($x)) { - $this->address = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $x); + return false; + } - return true; - } - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + // + // must be 8 x 16bit chunks, or 16 x 8bit + // + if ($this->rdlength == 16) { + // + // PHP's inet_ntop returns IPv6 addresses in their compressed form, + // but we want to keep with the preferred standard, so we'll parse + // it manually. + // + $x = unpack('n8', $this->rdata); - return false; - } + if (cacti_sizeof($x) == 8) { + $this->address = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $x); - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $packet->offset += 16; + return true; + } + } - return inet_pton($this->address); - } + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $packet->offset += 16; + + return inet_pton($this->address); + } } diff --git a/Net/DNS2/RR/AFSDB.php b/Net/DNS2/RR/AFSDB.php index e726ad07..71a9004c 100644 --- a/Net/DNS2/RR/AFSDB.php +++ b/Net/DNS2/RR/AFSDB.php @@ -27,85 +27,80 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_AFSDB extends Net_DNS2_RR -{ - // The AFSDB sub type - public $subtype; +class Net_DNS2_RR_AFSDB extends Net_DNS2_RR { + // The AFSDB sub type + public $subtype; - // The AFSDB hostname - public $hostname; + // The AFSDB hostname + public $hostname; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->subtype.' '.$this->cleanString($this->hostname).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->subtype . ' ' . $this->cleanString($this->hostname) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->subtype = array_shift($rdata); - $this->hostname = $this->cleanString(array_shift($rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->subtype = array_shift($rdata); + $this->hostname = $this->cleanString(array_shift($rdata)); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the subtype - // - $x = unpack('nsubtype', $this->rdata); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the subtype + // + $x = unpack('nsubtype', $this->rdata); - $this->subtype = $x['subtype']; - $offset = $packet->offset + 2; + $this->subtype = $x['subtype']; + $offset = $packet->offset + 2; - $this->hostname = Net_DNS2_Packet::expand($packet, $offset); + $this->hostname = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->hostname) > 0) { - $data = pack('n', $this->subtype); - $packet->offset += 2; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->hostname) > 0) { + $data = pack('n', $this->subtype); + $packet->offset += 2; - $data .= $packet->compress($this->hostname, $packet->offset); + $data .= $packet->compress($this->hostname, $packet->offset); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/AMTRELAY.php b/Net/DNS2/RR/AMTRELAY.php index 85019bcd..4000130a 100644 --- a/Net/DNS2/RR/AMTRELAY.php +++ b/Net/DNS2/RR/AMTRELAY.php @@ -27,216 +27,201 @@ * ~ relay ~ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_AMTRELAY extends Net_DNS2_RR -{ - // type definitions that match the "type" field below - public const AMTRELAY_TYPE_NONE = 0; - public const AMTRELAY_TYPE_IPV4 = 1; - public const AMTRELAY_TYPE_IPV6 = 2; - public const AMTRELAY_TYPE_DOMAIN = 3; - - // the precedence for this record - public $precedence; - - // "Discovery Optional" flag - public $discovery; - - // The type field indicates the format of the information that is stored in the relay field. - public $relay_type; - - // The relay field is the address or domain name of the AMT relay. - public $relay; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->precedence.' '.$this->discovery.' '.$this->relay_type.' '.$this->relay; - - // - // 4.3.1 - If the relay type field is 0, the relay field MUST be ".". - // - if ((self::AMTRELAY_TYPE_NONE == $this->relay_type) || (self::AMTRELAY_TYPE_DOMAIN == $this->relay_type)) { - $out .= '.'; - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // extract the values from the array - // - $this->precedence = array_shift($rdata); - $this->discovery = array_shift($rdata); - $this->relay_type = array_shift($rdata); - $this->relay = trim(strtolower(trim(array_shift($rdata))), '.'); - - // - // if there's anything else other than 0 in the discovery value, then force it to one, so - // that it effectively is either "true" or "false". - // - if (0 != $this->discovery) { - $this->discovery = 1; - } - - // - // validate the type & relay values - // - switch ($this->relay_type) { - case self::AMTRELAY_TYPE_NONE: - $this->relay = ''; - - break; - - case self::AMTRELAY_TYPE_IPV4: - if (false == Net_DNS2::isIPv4($this->relay)) { - return false; - } - - break; - - case self::AMTRELAY_TYPE_IPV6: - if (false == Net_DNS2::isIPv6($this->relay)) { - return false; - } - - break; - - case self::AMTRELAY_TYPE_DOMAIN:; // do nothing - - break; - - default: - // - // invalid type value - // - return false; - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse off the first two octets - // - $x = unpack('Cprecedence/Csecond', $this->rdata); - - $this->precedence = $x['precedence']; - $this->discovery = ($x['second'] >> 7) & 0x1; - $this->relay_type = $x['second'] & 0xF; - - $offset = 2; - - // - // parse the relay value based on the type - // - switch ($this->relay_type) { - case self::AMTRELAY_TYPE_NONE: - $this->relay = ''; - - break; - - case self::AMTRELAY_TYPE_IPV4: - $this->relay = inet_ntop(substr($this->rdata, $offset, 4)); - - break; - - case self::AMTRELAY_TYPE_IPV6: - // - // PHP's inet_ntop returns IPv6 addresses in their compressed form, but we want to keep - // with the preferred standard, so we'll parse it manually. - // - $ip = unpack('n8', substr($this->rdata, $offset, 16)); - if (8 == cacti_sizeof($ip)) { - $this->relay = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); - } else { - return false; - } - - break; - - case self::AMTRELAY_TYPE_DOMAIN: - $doffset = $packet->offset + $offset; - $this->relay = Net_DNS2_Packet::label($packet, $doffset); - - break; - - default: - // - // invalid type value - // - return false; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // pack the precedence, discovery, and type - // - $data = pack('CC', $this->precedence, ($this->discovery << 7) | $this->relay_type); - - // - // add the relay data based on the type - // - switch ($this->relay_type) { - case self::AMTRELAY_TYPE_NONE:; // add nothing - - break; - - case self::AMTRELAY_TYPE_IPV4: - case self::AMTRELAY_TYPE_IPV6: - $data .= inet_pton($this->relay); - - break; - - case self::AMTRELAY_TYPE_DOMAIN: - $data .= pack('Ca*', strlen($this->relay), $this->relay); - - break; - - default: - return null; - } - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_AMTRELAY extends Net_DNS2_RR { + // type definitions that match the "type" field below + public const AMTRELAY_TYPE_NONE = 0; + public const AMTRELAY_TYPE_IPV4 = 1; + public const AMTRELAY_TYPE_IPV6 = 2; + public const AMTRELAY_TYPE_DOMAIN = 3; + + // the precedence for this record + public $precedence; + + // "Discovery Optional" flag + public $discovery; + + // The type field indicates the format of the information that is stored in the relay field. + public $relay_type; + + // The relay field is the address or domain name of the AMT relay. + public $relay; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->precedence . ' ' . $this->discovery . ' ' . $this->relay_type . ' ' . $this->relay; + + // + // 4.3.1 - If the relay type field is 0, the relay field MUST be ".". + // + if (($this->relay_type == self::AMTRELAY_TYPE_NONE) || ($this->relay_type == self::AMTRELAY_TYPE_DOMAIN)) { + $out .= '.'; + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // extract the values from the array + // + $this->precedence = array_shift($rdata); + $this->discovery = array_shift($rdata); + $this->relay_type = array_shift($rdata); + $this->relay = trim(strtolower(trim(array_shift($rdata))), '.'); + + // + // if there's anything else other than 0 in the discovery value, then force it to one, so + // that it effectively is either "true" or "false". + // + if ($this->discovery != 0) { + $this->discovery = 1; + } + + // + // validate the type & relay values + // + switch ($this->relay_type) { + case self::AMTRELAY_TYPE_NONE: + $this->relay = ''; + + break; + case self::AMTRELAY_TYPE_IPV4: + if (Net_DNS2::isIPv4($this->relay) == false) { + return false; + } + + break; + case self::AMTRELAY_TYPE_IPV6: + if (Net_DNS2::isIPv6($this->relay) == false) { + return false; + } + + break; + case self::AMTRELAY_TYPE_DOMAIN:; // do nothing + + break; + default: + // + // invalid type value + // + return false; + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse off the first two octets + // + $x = unpack('Cprecedence/Csecond', $this->rdata); + + $this->precedence = $x['precedence']; + $this->discovery = ($x['second'] >> 7) & 0x1; + $this->relay_type = $x['second'] & 0xF; + + $offset = 2; + + // + // parse the relay value based on the type + // + switch ($this->relay_type) { + case self::AMTRELAY_TYPE_NONE: + $this->relay = ''; + + break; + case self::AMTRELAY_TYPE_IPV4: + $this->relay = inet_ntop(substr($this->rdata, $offset, 4)); + + break; + case self::AMTRELAY_TYPE_IPV6: + // + // PHP's inet_ntop returns IPv6 addresses in their compressed form, but we want to keep + // with the preferred standard, so we'll parse it manually. + // + $ip = unpack('n8', substr($this->rdata, $offset, 16)); + + if (cacti_sizeof($ip) == 8) { + $this->relay = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); + } else { + return false; + } + + break; + case self::AMTRELAY_TYPE_DOMAIN: + $doffset = $packet->offset + $offset; + $this->relay = Net_DNS2_Packet::label($packet, $doffset); + + break; + default: + // + // invalid type value + // + return false; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + // + // pack the precedence, discovery, and type + // + $data = pack('CC', $this->precedence, ($this->discovery << 7) | $this->relay_type); + + // + // add the relay data based on the type + // + switch ($this->relay_type) { + case self::AMTRELAY_TYPE_NONE:; // add nothing + + break; + case self::AMTRELAY_TYPE_IPV4: + case self::AMTRELAY_TYPE_IPV6: + $data .= inet_pton($this->relay); + + break; + case self::AMTRELAY_TYPE_DOMAIN: + $data .= pack('Ca*', strlen($this->relay), $this->relay); + + break; + default: + return null; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/ANY.php b/Net/DNS2/RR/ANY.php index 95927f1a..33b3ba38 100644 --- a/Net/DNS2/RR/ANY.php +++ b/Net/DNS2/RR/ANY.php @@ -20,53 +20,48 @@ /** * This is only used for generating an empty ANY RR. */ -class Net_DNS2_RR_ANY extends Net_DNS2_RR -{ - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return ''; - } +class Net_DNS2_RR_ANY extends Net_DNS2_RR { + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return ''; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - return true; - } + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - return true; - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + return true; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - return ''; - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + return ''; + } } diff --git a/Net/DNS2/RR/APL.php b/Net/DNS2/RR/APL.php index 7b792324..96b83675 100644 --- a/Net/DNS2/RR/APL.php +++ b/Net/DNS2/RR/APL.php @@ -29,261 +29,249 @@ * | | * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ */ -class Net_DNS2_RR_APL extends Net_DNS2_RR -{ - // a list of all the address prefix list items - public $apl_items = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = ''; - - foreach ($this->apl_items as $item) { - if (1 == $item['n']) { - $out .= '!'; - } - - $out .= $item['address_family'].':' - .$item['afd_part'].'/'.$item['prefix'].' '; - } - - return trim($out); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - foreach ($rdata as $item) { - if (preg_match('/^(!?)([1|2])\:([^\/]*)\/([0-9]{1,3})$/', $item, $m)) { - $i = [ - 'address_family' => $m[2], - 'prefix' => $m[4], - 'n' => ('!' == $m[1]) ? 1 : 0, - 'afd_part' => strtolower($m[3]), - ]; - - $address = $this->_trimZeros( - $i['address_family'], - $i['afd_part'] - ); - - $i['afd_length'] = cacti_sizeof(explode('.', $address)); - - $this->apl_items[] = $i; - } - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = 0; - - while ($offset < $this->rdlength) { - // - // unpack the family, prefix, negate and length values - // - $x = unpack( - 'naddress_family/Cprefix/Cextra', - substr($this->rdata, $offset) - ); - - $item = [ - 'address_family' => $x['address_family'], - 'prefix' => $x['prefix'], - 'n' => ($x['extra'] >> 7) & 0x1, - 'afd_length' => $x['extra'] & 0xF, - ]; - - switch ($item['address_family']) { - case 1: - $r = unpack( - 'C*', - substr($this->rdata, $offset + 4, $item['afd_length']) - ); - if (cacti_sizeof($r) < 4) { - for ($c = cacti_sizeof($r) + 1; $c < 4 + 1; ++$c) { - $r[$c] = 0; - } - } - - $item['afd_part'] = implode('.', $r); - - break; - - case 2: - $r = unpack( - 'C*', - substr($this->rdata, $offset + 4, $item['afd_length']) - ); - if (cacti_sizeof($r) < 8) { - for ($c = cacti_sizeof($r) + 1; $c < 8 + 1; ++$c) { - $r[$c] = 0; - } - } - - $item['afd_part'] = sprintf( - '%x:%x:%x:%x:%x:%x:%x:%x', - $r[1], - $r[2], - $r[3], - $r[4], - $r[5], - $r[6], - $r[7], - $r[8] - ); - - break; - - default: - return false; - } - - $this->apl_items[] = $item; - - $offset += 4 + $item['afd_length']; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (cacti_sizeof($this->apl_items) > 0) { - $data = ''; - - foreach ($this->apl_items as $item) { - // - // pack the address_family and prefix values - // - $data .= pack( - 'nCC', - $item['address_family'], - $item['prefix'], - ($item['n'] << 7) | $item['afd_length'] - ); - - switch ($item['address_family']) { - case 1: - $address = explode( - '.', - $this->_trimZeros($item['address_family'], $item['afd_part']) - ); - - foreach ($address as $b) { - $data .= chr($b); - } - - break; - - case 2: - $address = explode( - ':', - $this->_trimZeros($item['address_family'], $item['afd_part']) - ); - - foreach ($address as $b) { - $data .= pack('H', $b); - } - - break; - - default: - return null; - } - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } - - /** - * returns an IP address with the right-hand zero's trimmed. - * - * @param int $family the IP address family from the rdata - * @param string $address the IP address - * - * @return string the trimmed IP addresss - */ - private function _trimZeros($family, $address) - { - $a = []; - - switch ($family) { - case 1: - $a = array_reverse(explode('.', $address)); - - break; - - case 2: - $a = array_reverse(explode(':', $address)); - - break; - - default: - return ''; - } - - foreach ($a as $value) { - if ('0' === $value) { - array_shift($a); - } - } - - $out = ''; - - switch ($family) { - case 1: - $out = implode('.', array_reverse($a)); - - break; - - case 2: - $out = implode(':', array_reverse($a)); - - break; - - default: - return ''; - } - - return $out; - } +class Net_DNS2_RR_APL extends Net_DNS2_RR { + // a list of all the address prefix list items + public $apl_items = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = ''; + + foreach ($this->apl_items as $item) { + if ($item['n'] == 1) { + $out .= '!'; + } + + $out .= $item['address_family'] . ':' + . $item['afd_part'] . '/' . $item['prefix'] . ' '; + } + + return trim($out); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + foreach ($rdata as $item) { + if (preg_match('/^(!?)([1|2])\:([^\/]*)\/([0-9]{1,3})$/', $item, $m)) { + $i = [ + 'address_family' => $m[2], + 'prefix' => $m[4], + 'n' => ($m[1] == '!') ? 1 : 0, + 'afd_part' => strtolower($m[3]), + ]; + + $address = $this->_trimZeros( + $i['address_family'], + $i['afd_part'] + ); + + $i['afd_length'] = cacti_sizeof(explode('.', $address)); + + $this->apl_items[] = $i; + } + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = 0; + + while ($offset < $this->rdlength) { + // + // unpack the family, prefix, negate and length values + // + $x = unpack( + 'naddress_family/Cprefix/Cextra', + substr($this->rdata, $offset) + ); + + $item = [ + 'address_family' => $x['address_family'], + 'prefix' => $x['prefix'], + 'n' => ($x['extra'] >> 7) & 0x1, + 'afd_length' => $x['extra'] & 0xF, + ]; + + switch ($item['address_family']) { + case 1: + $r = unpack( + 'C*', + substr($this->rdata, $offset + 4, $item['afd_length']) + ); + + if (cacti_sizeof($r) < 4) { + for ($c = cacti_sizeof($r) + 1; $c < 4 + 1; ++$c) { + $r[$c] = 0; + } + } + + $item['afd_part'] = implode('.', $r); + + break; + case 2: + $r = unpack( + 'C*', + substr($this->rdata, $offset + 4, $item['afd_length']) + ); + + if (cacti_sizeof($r) < 8) { + for ($c = cacti_sizeof($r) + 1; $c < 8 + 1; ++$c) { + $r[$c] = 0; + } + } + + $item['afd_part'] = sprintf( + '%x:%x:%x:%x:%x:%x:%x:%x', + $r[1], + $r[2], + $r[3], + $r[4], + $r[5], + $r[6], + $r[7], + $r[8] + ); + + break; + default: + return false; + } + + $this->apl_items[] = $item; + + $offset += 4 + $item['afd_length']; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (cacti_sizeof($this->apl_items) > 0) { + $data = ''; + + foreach ($this->apl_items as $item) { + // + // pack the address_family and prefix values + // + $data .= pack( + 'nCC', + $item['address_family'], + $item['prefix'], + ($item['n'] << 7) | $item['afd_length'] + ); + + switch ($item['address_family']) { + case 1: + $address = explode( + '.', + $this->_trimZeros($item['address_family'], $item['afd_part']) + ); + + foreach ($address as $b) { + $data .= chr($b); + } + + break; + case 2: + $address = explode( + ':', + $this->_trimZeros($item['address_family'], $item['afd_part']) + ); + + foreach ($address as $b) { + $data .= pack('H', $b); + } + + break; + default: + return null; + } + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } + + /** + * returns an IP address with the right-hand zero's trimmed. + * + * @param int $family the IP address family from the rdata + * @param string $address the IP address + * + * @return string the trimmed IP addresss + */ + private function _trimZeros($family, $address) { + $a = []; + + switch ($family) { + case 1: + $a = array_reverse(explode('.', $address)); + + break; + case 2: + $a = array_reverse(explode(':', $address)); + + break; + default: + return ''; + } + + foreach ($a as $value) { + if ($value === '0') { + array_shift($a); + } + } + + $out = ''; + + switch ($family) { + case 1: + $out = implode('.', array_reverse($a)); + + break; + case 2: + $out = implode(':', array_reverse($a)); + + break; + default: + return ''; + } + + return $out; + } } diff --git a/Net/DNS2/RR/ATMA.php b/Net/DNS2/RR/ATMA.php index 460c08ae..4ddf0da3 100644 --- a/Net/DNS2/RR/ATMA.php +++ b/Net/DNS2/RR/ATMA.php @@ -28,108 +28,103 @@ * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_ATMA extends Net_DNS2_RR -{ - /* - * One octet that indicates the format of ADDRESS. The two possible values - * for FORMAT are value 0 indicating ATM End System Address (AESA) format - * and value 1 indicating E.164 format - */ - public $format; - - // The IPv4 address in quad-dotted notation - public $address; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->address; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $value = array_shift($rdata); - - if (true == ctype_xdigit($value)) { - $this->format = 0; - $this->address = $value; - } elseif (true == is_numeric($value)) { - $this->format = 1; - $this->address = $value; - } else { - return false; - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the format - // - $x = unpack('Cformat/N*address', $this->rdata); - - $this->format = $x['format']; - - if (0 == $this->format) { - $a = unpack('@1/H*address', $this->rdata); - - $this->address = $a['address']; - } elseif (1 == $this->format) { - $this->address = substr($this->rdata, 1, $this->rdlength - 1); - } else { - return false; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = chr($this->format); - - if (0 == $this->format) { - $data .= pack('H*', $this->address); - } elseif (1 == $this->format) { - $data .= $this->address; - } else { - return null; - } - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_ATMA extends Net_DNS2_RR { + /* + * One octet that indicates the format of ADDRESS. The two possible values + * for FORMAT are value 0 indicating ATM End System Address (AESA) format + * and value 1 indicating E.164 format + */ + public $format; + + // The IPv4 address in quad-dotted notation + public $address; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->address; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $value = array_shift($rdata); + + if (ctype_xdigit($value) == true) { + $this->format = 0; + $this->address = $value; + } elseif (is_numeric($value) == true) { + $this->format = 1; + $this->address = $value; + } else { + return false; + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the format + // + $x = unpack('Cformat/N*address', $this->rdata); + + $this->format = $x['format']; + + if ($this->format == 0) { + $a = unpack('@1/H*address', $this->rdata); + + $this->address = $a['address']; + } elseif ($this->format == 1) { + $this->address = substr($this->rdata, 1, $this->rdlength - 1); + } else { + return false; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $data = chr($this->format); + + if ($this->format == 0) { + $data .= pack('H*', $this->address); + } elseif ($this->format == 1) { + $data .= $this->address; + } else { + return null; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/AVC.php b/Net/DNS2/RR/AVC.php index 67e1b953..8c6e58fe 100644 --- a/Net/DNS2/RR/AVC.php +++ b/Net/DNS2/RR/AVC.php @@ -21,4 +21,5 @@ * The AVC RR is implemented exactly like the TXT record, so * for now we just extend the TXT RR and use it. */ -class Net_DNS2_RR_AVC extends Net_DNS2_RR_TXT {} +class Net_DNS2_RR_AVC extends Net_DNS2_RR_TXT { +} diff --git a/Net/DNS2/RR/CAA.php b/Net/DNS2/RR/CAA.php index d9846c8b..1e398a94 100644 --- a/Net/DNS2/RR/CAA.php +++ b/Net/DNS2/RR/CAA.php @@ -28,94 +28,89 @@ * / DATA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_CAA extends Net_DNS2_RR -{ - // The critcal flag - public $flags; - - // The property identifier - public $tag; - - // The property value - public $value; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->flags.' '.$this->tag.' "' - .trim($this->cleanString($this->value), '"').'"'; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->flags = array_shift($rdata); - $this->tag = array_shift($rdata); - - $this->value = trim($this->cleanString(implode(' ', $rdata)), '"'); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the flags and tag length - // - $x = unpack('Cflags/Ctag_length', $this->rdata); - - $this->flags = $x['flags']; - $offset = 2; - - $this->tag = substr($this->rdata, $offset, $x['tag_length']); - $offset += $x['tag_length']; - - $this->value = substr($this->rdata, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->value) > 0) { - $data = chr($this->flags); - $data .= chr(strlen($this->tag)).$this->tag.$this->value; - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_CAA extends Net_DNS2_RR { + // The critcal flag + public $flags; + + // The property identifier + public $tag; + + // The property value + public $value; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->flags . ' ' . $this->tag . ' "' + . trim($this->cleanString($this->value), '"') . '"'; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->flags = array_shift($rdata); + $this->tag = array_shift($rdata); + + $this->value = trim($this->cleanString(implode(' ', $rdata)), '"'); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the flags and tag length + // + $x = unpack('Cflags/Ctag_length', $this->rdata); + + $this->flags = $x['flags']; + $offset = 2; + + $this->tag = substr($this->rdata, $offset, $x['tag_length']); + $offset += $x['tag_length']; + + $this->value = substr($this->rdata, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->value) > 0) { + $data = chr($this->flags); + $data .= chr(strlen($this->tag)) . $this->tag . $this->value; + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/CDNSKEY.php b/Net/DNS2/RR/CDNSKEY.php index 74bcfa84..8240977a 100644 --- a/Net/DNS2/RR/CDNSKEY.php +++ b/Net/DNS2/RR/CDNSKEY.php @@ -23,4 +23,5 @@ * * http://www.rfc-editor.org/rfc/rfc7344.txt */ -class Net_DNS2_RR_CDNSKEY extends Net_DNS2_RR_DNSKEY {} +class Net_DNS2_RR_CDNSKEY extends Net_DNS2_RR_DNSKEY { +} diff --git a/Net/DNS2/RR/CDS.php b/Net/DNS2/RR/CDS.php index 5346649e..e9eade5e 100644 --- a/Net/DNS2/RR/CDS.php +++ b/Net/DNS2/RR/CDS.php @@ -23,4 +23,5 @@ * * http://www.rfc-editor.org/rfc/rfc7344.txt */ -class Net_DNS2_RR_CDS extends Net_DNS2_RR_DS {} +class Net_DNS2_RR_CDS extends Net_DNS2_RR_DS { +} diff --git a/Net/DNS2/RR/CERT.php b/Net/DNS2/RR/CERT.php index 45e122c7..0b1fad32 100644 --- a/Net/DNS2/RR/CERT.php +++ b/Net/DNS2/RR/CERT.php @@ -29,183 +29,181 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-| */ -class Net_DNS2_RR_CERT extends Net_DNS2_RR -{ - // format's allowed for certificates - public const CERT_FORMAT_RES = 0; - public const CERT_FORMAT_PKIX = 1; - public const CERT_FORMAT_SPKI = 2; - public const CERT_FORMAT_PGP = 3; - public const CERT_FORMAT_IPKIX = 4; - public const CERT_FORMAT_ISPKI = 5; - public const CERT_FORMAT_IPGP = 6; - public const CERT_FORMAT_ACPKIX = 7; - public const CERT_FORMAT_IACPKIX = 8; - public const CERT_FORMAT_URI = 253; - public const CERT_FORMAT_OID = 254; - - public $cert_format_name_to_id = []; - public $cert_format_id_to_name = [ - self::CERT_FORMAT_RES => 'Reserved', - self::CERT_FORMAT_PKIX => 'PKIX', - self::CERT_FORMAT_SPKI => 'SPKI', - self::CERT_FORMAT_PGP => 'PGP', - self::CERT_FORMAT_IPKIX => 'IPKIX', - self::CERT_FORMAT_ISPKI => 'ISPKI', - self::CERT_FORMAT_IPGP => 'IPGP', - self::CERT_FORMAT_ACPKIX => 'ACPKIX', - self::CERT_FORMAT_IACPKIX => 'IACPKIX', - self::CERT_FORMAT_URI => 'URI', - self::CERT_FORMAT_OID => 'OID', - ]; - - // certificate format - public $format; - - // key tag - public $keytag; - - // The algorithm used for the CERt - public $algorithm; - - // certificate - public $certificate; - - /** - * we have our own constructor so that we can load our certificate - * information for parsing. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * @param array $rr a array with parsed RR values - */ - public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) - { - parent::__construct($packet, $rr); - - // - // load the lookup values - // - $this->cert_format_name_to_id = array_flip($this->cert_format_id_to_name); - } - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->format.' '.$this->keytag.' '.$this->algorithm - .' '.base64_encode($this->certificate); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // load and check the format; can be an int, or a mnemonic symbol - // - $this->format = array_shift($rdata); - if (!is_numeric($this->format)) { - $mnemonic = strtoupper(trim($this->format)); - if (!isset($this->cert_format_name_to_id[$mnemonic])) { - return false; - } - - $this->format = $this->cert_format_name_to_id[$mnemonic]; - } else { - if (!isset($this->cert_format_id_to_name[$this->format])) { - return false; - } - } - - $this->keytag = array_shift($rdata); - - // - // parse and check the algorithm; can be an int, or a mnemonic symbol - // - $this->algorithm = array_shift($rdata); - if (!is_numeric($this->algorithm)) { - $mnemonic = strtoupper(trim($this->algorithm)); - if (!isset(Net_DNS2_Lookups::$algorithm_name_to_id[$mnemonic])) { - return false; - } - - $this->algorithm = Net_DNS2_Lookups::$algorithm_name_to_id[ - $mnemonic - ]; - } else { - if (!isset(Net_DNS2_Lookups::$algorithm_id_to_name[$this->algorithm])) { - return false; - } - } - - // - // parse and base64 decode the certificate - // - // certificates MUST be provided base64 encoded, if not, everything will - // be broken after this point, as we assume it's base64 encoded. - // - $this->certificate = base64_decode(implode(' ', $rdata)); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the format, keytag and algorithm - // - $x = unpack('nformat/nkeytag/Calgorithm', $this->rdata); - - $this->format = $x['format']; - $this->keytag = $x['keytag']; - $this->algorithm = $x['algorithm']; - - // - // copy the certificate - // - $this->certificate = substr($this->rdata, 5, $this->rdlength - 5); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->certificate) > 0) { - $data = pack('nnC', $this->format, $this->keytag, $this->algorithm).$this->certificate; - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_CERT extends Net_DNS2_RR { + // format's allowed for certificates + public const CERT_FORMAT_RES = 0; + public const CERT_FORMAT_PKIX = 1; + public const CERT_FORMAT_SPKI = 2; + public const CERT_FORMAT_PGP = 3; + public const CERT_FORMAT_IPKIX = 4; + public const CERT_FORMAT_ISPKI = 5; + public const CERT_FORMAT_IPGP = 6; + public const CERT_FORMAT_ACPKIX = 7; + public const CERT_FORMAT_IACPKIX = 8; + public const CERT_FORMAT_URI = 253; + public const CERT_FORMAT_OID = 254; + + public $cert_format_name_to_id = []; + public $cert_format_id_to_name = [ + self::CERT_FORMAT_RES => 'Reserved', + self::CERT_FORMAT_PKIX => 'PKIX', + self::CERT_FORMAT_SPKI => 'SPKI', + self::CERT_FORMAT_PGP => 'PGP', + self::CERT_FORMAT_IPKIX => 'IPKIX', + self::CERT_FORMAT_ISPKI => 'ISPKI', + self::CERT_FORMAT_IPGP => 'IPGP', + self::CERT_FORMAT_ACPKIX => 'ACPKIX', + self::CERT_FORMAT_IACPKIX => 'IACPKIX', + self::CERT_FORMAT_URI => 'URI', + self::CERT_FORMAT_OID => 'OID', + ]; + + // certificate format + public $format; + + // key tag + public $keytag; + + // The algorithm used for the CERt + public $algorithm; + + // certificate + public $certificate; + + /** + * we have our own constructor so that we can load our certificate + * information for parsing. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * @param array $rr a array with parsed RR values + */ + public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) { + parent::__construct($packet, $rr); + + // + // load the lookup values + // + $this->cert_format_name_to_id = array_flip($this->cert_format_id_to_name); + } + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->format . ' ' . $this->keytag . ' ' . $this->algorithm + . ' ' . base64_encode($this->certificate); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // load and check the format; can be an int, or a mnemonic symbol + // + $this->format = array_shift($rdata); + + if (!is_numeric($this->format)) { + $mnemonic = strtoupper(trim($this->format)); + + if (!isset($this->cert_format_name_to_id[$mnemonic])) { + return false; + } + + $this->format = $this->cert_format_name_to_id[$mnemonic]; + } else { + if (!isset($this->cert_format_id_to_name[$this->format])) { + return false; + } + } + + $this->keytag = array_shift($rdata); + + // + // parse and check the algorithm; can be an int, or a mnemonic symbol + // + $this->algorithm = array_shift($rdata); + + if (!is_numeric($this->algorithm)) { + $mnemonic = strtoupper(trim($this->algorithm)); + + if (!isset(Net_DNS2_Lookups::$algorithm_name_to_id[$mnemonic])) { + return false; + } + + $this->algorithm = Net_DNS2_Lookups::$algorithm_name_to_id[ + $mnemonic + ]; + } else { + if (!isset(Net_DNS2_Lookups::$algorithm_id_to_name[$this->algorithm])) { + return false; + } + } + + // + // parse and base64 decode the certificate + // + // certificates MUST be provided base64 encoded, if not, everything will + // be broken after this point, as we assume it's base64 encoded. + // + $this->certificate = base64_decode(implode(' ', $rdata), true); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the format, keytag and algorithm + // + $x = unpack('nformat/nkeytag/Calgorithm', $this->rdata); + + $this->format = $x['format']; + $this->keytag = $x['keytag']; + $this->algorithm = $x['algorithm']; + + // + // copy the certificate + // + $this->certificate = substr($this->rdata, 5, $this->rdlength - 5); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->certificate) > 0) { + $data = pack('nnC', $this->format, $this->keytag, $this->algorithm) . $this->certificate; + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/CNAME.php b/Net/DNS2/RR/CNAME.php index b1ebd63c..8025963a 100644 --- a/Net/DNS2/RR/CNAME.php +++ b/Net/DNS2/RR/CNAME.php @@ -25,69 +25,64 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_CNAME extends Net_DNS2_RR -{ - // The canonical name - public $cname; +class Net_DNS2_RR_CNAME extends Net_DNS2_RR { + // The canonical name + public $cname; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->cname).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->cname) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->cname = $this->cleanString(array_shift($rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->cname = $this->cleanString(array_shift($rdata)); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; - $this->cname = Net_DNS2_Packet::expand($packet, $offset); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; + $this->cname = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->cname) > 0) { - return $packet->compress($this->cname, $packet->offset); - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->cname) > 0) { + return $packet->compress($this->cname, $packet->offset); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/CSYNC.php b/Net/DNS2/RR/CSYNC.php index 2782f3db..3962b4a1 100644 --- a/Net/DNS2/RR/CSYNC.php +++ b/Net/DNS2/RR/CSYNC.php @@ -29,110 +29,105 @@ * / Type Bit Map / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_CSYNC extends Net_DNS2_RR -{ - // serial number - public $serial; - - // flags - public $flags; - - // array of RR type names - public $type_bit_maps = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->serial.' '.$this->flags; - - // - // show the RR's - // - foreach ($this->type_bit_maps as $rr) { - $out .= ' '.strtoupper($rr); - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->serial = array_shift($rdata); - $this->flags = array_shift($rdata); - - $this->type_bit_maps = $rdata; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the serial and flags values - // - $x = unpack('@'.$packet->offset.'/Nserial/nflags', $packet->rdata); - - $this->serial = Net_DNS2::expandUint32($x['serial']); - $this->flags = $x['flags']; - - // - // parse out the RR bitmap - // - $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( - substr($this->rdata, 6) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // pack the serial and flags values - // - $data = pack('Nn', $this->serial, $this->flags); - - // - // convert the array of RR names to a type bitmap - // - $data .= Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); - - // - // advance the offset - // - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_CSYNC extends Net_DNS2_RR { + // serial number + public $serial; + + // flags + public $flags; + + // array of RR type names + public $type_bit_maps = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->serial . ' ' . $this->flags; + + // + // show the RR's + // + foreach ($this->type_bit_maps as $rr) { + $out .= ' ' . strtoupper($rr); + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->serial = array_shift($rdata); + $this->flags = array_shift($rdata); + + $this->type_bit_maps = $rdata; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the serial and flags values + // + $x = unpack('@' . $packet->offset . '/Nserial/nflags', $packet->rdata); + + $this->serial = Net_DNS2::expandUint32($x['serial']); + $this->flags = $x['flags']; + + // + // parse out the RR bitmap + // + $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( + substr($this->rdata, 6) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + // + // pack the serial and flags values + // + $data = pack('Nn', $this->serial, $this->flags); + + // + // convert the array of RR names to a type bitmap + // + $data .= Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); + + // + // advance the offset + // + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/DHCID.php b/Net/DNS2/RR/DHCID.php index 7ff54890..d2ee30b1 100644 --- a/Net/DNS2/RR/DHCID.php +++ b/Net/DNS2/RR/DHCID.php @@ -30,111 +30,107 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_DHCID extends Net_DNS2_RR -{ - // Identifier type - public $id_type; - - // Digest Type - public $digest_type; - - // The digest - public $digest; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = pack('nC', $this->id_type, $this->digest_type); - $out .= base64_decode($this->digest); - - return base64_encode($out); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $data = base64_decode(array_shift($rdata)); - if (strlen($data) > 0) { - // - // unpack the id type and digest type - // - $x = unpack('nid_type/Cdigest_type', $data); - - $this->id_type = $x['id_type']; - $this->digest_type = $x['digest_type']; - - // - // copy out the digest - // - $this->digest = base64_encode(substr($data, 3, strlen($data) - 3)); - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the id type and digest type - // - $x = unpack('nid_type/Cdigest_type', $this->rdata); - - $this->id_type = $x['id_type']; - $this->digest_type = $x['digest_type']; - - // - // copy out the digest - // - $this->digest = base64_encode( - substr($this->rdata, 3, $this->rdlength - 3) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->digest) > 0) { - $data = pack('nC', $this->id_type, $this->digest_type) - .base64_decode($this->digest); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_DHCID extends Net_DNS2_RR { + // Identifier type + public $id_type; + + // Digest Type + public $digest_type; + + // The digest + public $digest; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = pack('nC', $this->id_type, $this->digest_type); + $out .= base64_decode($this->digest, true); + + return base64_encode($out); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $data = base64_decode(array_shift($rdata), true); + + if (strlen($data) > 0) { + // + // unpack the id type and digest type + // + $x = unpack('nid_type/Cdigest_type', $data); + + $this->id_type = $x['id_type']; + $this->digest_type = $x['digest_type']; + + // + // copy out the digest + // + $this->digest = base64_encode(substr($data, 3, strlen($data) - 3)); + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the id type and digest type + // + $x = unpack('nid_type/Cdigest_type', $this->rdata); + + $this->id_type = $x['id_type']; + $this->digest_type = $x['digest_type']; + + // + // copy out the digest + // + $this->digest = base64_encode( + substr($this->rdata, 3, $this->rdlength - 3) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->digest) > 0) { + $data = pack('nC', $this->id_type, $this->digest_type) + . base64_decode($this->digest, true); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/DLV.php b/Net/DNS2/RR/DLV.php index 7dbbcfbc..6208ccda 100644 --- a/Net/DNS2/RR/DLV.php +++ b/Net/DNS2/RR/DLV.php @@ -21,4 +21,5 @@ * The DLV RR is implemented exactly like the DS RR; so we just extend that * class, and use all of it's methods. */ -class Net_DNS2_RR_DLV extends Net_DNS2_RR_DS {} +class Net_DNS2_RR_DLV extends Net_DNS2_RR_DS { +} diff --git a/Net/DNS2/RR/DNAME.php b/Net/DNS2/RR/DNAME.php index 2eb07a81..e8f49e3c 100644 --- a/Net/DNS2/RR/DNAME.php +++ b/Net/DNS2/RR/DNAME.php @@ -25,69 +25,64 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_DNAME extends Net_DNS2_RR -{ - // The target name - public $dname; +class Net_DNS2_RR_DNAME extends Net_DNS2_RR { + // The target name + public $dname; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->dname).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->dname) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->dname = $this->cleanString(array_shift($rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->dname = $this->cleanString(array_shift($rdata)); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; - $this->dname = Net_DNS2_Packet::expand($packet, $offset); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; + $this->dname = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->dname) > 0) { - return $packet->compress($this->dname, $packet->offset); - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->dname) > 0) { + return $packet->compress($this->dname, $packet->offset); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/DNSKEY.php b/Net/DNS2/RR/DNSKEY.php index cc3fa8f8..0d88ce1d 100644 --- a/Net/DNS2/RR/DNSKEY.php +++ b/Net/DNS2/RR/DNSKEY.php @@ -29,103 +29,98 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_DNSKEY extends Net_DNS2_RR -{ - // flags - public $flags; - - // protocol - public $protocol; - - // algorithm used - public $algorithm; - - // the public key - public $key; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->flags.' '.$this->protocol.' ' - .$this->algorithm.' '.$this->key; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->flags = array_shift($rdata); - $this->protocol = array_shift($rdata); - $this->algorithm = array_shift($rdata); - $this->key = implode(' ', $rdata); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the flags, protocol and algorithm - // - $x = unpack('nflags/Cprotocol/Calgorithm', $this->rdata); - - // - // TODO: right now we're just displaying what's in DNS; we really - // should be parsing bit 7 and bit 15 of the flags field, and store - // those separately. - // - // right now the DNSSEC implementation is really just for display, - // we don't validate or handle any of the keys - // - $this->flags = $x['flags']; - $this->protocol = $x['protocol']; - $this->algorithm = $x['algorithm']; - - $this->key = base64_encode(substr($this->rdata, 4)); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->key) > 0) { - $data = pack('nCC', $this->flags, $this->protocol, $this->algorithm); - $data .= base64_decode($this->key); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_DNSKEY extends Net_DNS2_RR { + // flags + public $flags; + + // protocol + public $protocol; + + // algorithm used + public $algorithm; + + // the public key + public $key; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->flags . ' ' . $this->protocol . ' ' + . $this->algorithm . ' ' . $this->key; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->flags = array_shift($rdata); + $this->protocol = array_shift($rdata); + $this->algorithm = array_shift($rdata); + $this->key = implode(' ', $rdata); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the flags, protocol and algorithm + // + $x = unpack('nflags/Cprotocol/Calgorithm', $this->rdata); + + // + // TODO: right now we're just displaying what's in DNS; we really + // should be parsing bit 7 and bit 15 of the flags field, and store + // those separately. + // + // right now the DNSSEC implementation is really just for display, + // we don't validate or handle any of the keys + // + $this->flags = $x['flags']; + $this->protocol = $x['protocol']; + $this->algorithm = $x['algorithm']; + + $this->key = base64_encode(substr($this->rdata, 4)); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->key) > 0) { + $data = pack('nCC', $this->flags, $this->protocol, $this->algorithm); + $data .= base64_decode($this->key, true); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/DS.php b/Net/DNS2/RR/DS.php index b4d81621..5e2d8c3d 100644 --- a/Net/DNS2/RR/DS.php +++ b/Net/DNS2/RR/DS.php @@ -29,92 +29,87 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_DS extends Net_DNS2_RR -{ - // key tag - public $keytag; - - // algorithm number - public $algorithm; - - // algorithm used to construct the digest - public $digesttype; - - // the digest data - public $digest; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->keytag.' '.$this->algorithm.' '.$this->digesttype.' '.$this->digest; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->keytag = array_shift($rdata); - $this->algorithm = array_shift($rdata); - $this->digesttype = array_shift($rdata); - $this->digest = implode('', $rdata); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the keytag, algorithm and digesttype - // - $x = unpack('nkeytag/Calgorithm/Cdigesttype/H*digest', $this->rdata); - - $this->keytag = $x['keytag']; - $this->algorithm = $x['algorithm']; - $this->digesttype = $x['digesttype']; - $this->digest = $x['digest']; - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->digest) > 0) { - $data = pack('nCCH*', $this->keytag, $this->algorithm, $this->digesttype, $this->digest); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_DS extends Net_DNS2_RR { + // key tag + public $keytag; + + // algorithm number + public $algorithm; + + // algorithm used to construct the digest + public $digesttype; + + // the digest data + public $digest; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->keytag . ' ' . $this->algorithm . ' ' . $this->digesttype . ' ' . $this->digest; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->keytag = array_shift($rdata); + $this->algorithm = array_shift($rdata); + $this->digesttype = array_shift($rdata); + $this->digest = implode('', $rdata); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the keytag, algorithm and digesttype + // + $x = unpack('nkeytag/Calgorithm/Cdigesttype/H*digest', $this->rdata); + + $this->keytag = $x['keytag']; + $this->algorithm = $x['algorithm']; + $this->digesttype = $x['digesttype']; + $this->digest = $x['digest']; + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->digest) > 0) { + $data = pack('nCCH*', $this->keytag, $this->algorithm, $this->digesttype, $this->digest); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/EID.php b/Net/DNS2/RR/EID.php index 91466717..0b08ccae 100644 --- a/Net/DNS2/RR/EID.php +++ b/Net/DNS2/RR/EID.php @@ -21,53 +21,48 @@ * EID Resource Record - undefined; the rdata is simply used as-is in it's * binary format, so not process has to be done. */ -class Net_DNS2_RR_EID extends Net_DNS2_RR -{ - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return ''; - } +class Net_DNS2_RR_EID extends Net_DNS2_RR { + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return ''; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - return true; - } + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - return true; - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + return true; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - return $this->rdata; - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + return $this->rdata; + } } diff --git a/Net/DNS2/RR/EUI48.php b/Net/DNS2/RR/EUI48.php index f238e003..089b3b36 100644 --- a/Net/DNS2/RR/EUI48.php +++ b/Net/DNS2/RR/EUI48.php @@ -28,99 +28,97 @@ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_EUI48 extends Net_DNS2_RR -{ - // The EUI48 address, in hex format - public $address; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->address; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $value = array_shift($rdata); - - // - // re: RFC 7043, the field must be represented as six two-digit hex numbers - // separated by hyphens. - // - $a = explode('-', $value); - if (6 != cacti_sizeof($a)) { - return false; - } - - // - // make sure they're all hex values - // - foreach ($a as $i) { - if (false == ctype_xdigit($i)) { - return false; - } - } - - // - // store it - // - $this->address = strtolower($value); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $x = unpack('C6', $this->rdata); - if (6 == cacti_sizeof($x)) { - $this->address = vsprintf('%02x-%02x-%02x-%02x-%02x-%02x', $x); - - return true; - } - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = ''; - - $a = explode('-', $this->address); - foreach ($a as $b) { - $data .= chr(hexdec($b)); - } - - $packet->offset += 6; - - return $data; - } +class Net_DNS2_RR_EUI48 extends Net_DNS2_RR { + // The EUI48 address, in hex format + public $address; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->address; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $value = array_shift($rdata); + + // + // re: RFC 7043, the field must be represented as six two-digit hex numbers + // separated by hyphens. + // + $a = explode('-', $value); + + if (cacti_sizeof($a) != 6) { + return false; + } + + // + // make sure they're all hex values + // + foreach ($a as $i) { + if (ctype_xdigit($i) == false) { + return false; + } + } + + // + // store it + // + $this->address = strtolower($value); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $x = unpack('C6', $this->rdata); + + if (cacti_sizeof($x) == 6) { + $this->address = vsprintf('%02x-%02x-%02x-%02x-%02x-%02x', $x); + + return true; + } + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $data = ''; + + $a = explode('-', $this->address); + + foreach ($a as $b) { + $data .= chr(hexdec($b)); + } + + $packet->offset += 6; + + return $data; + } } diff --git a/Net/DNS2/RR/EUI64.php b/Net/DNS2/RR/EUI64.php index 818aa1f5..7c7ab82b 100644 --- a/Net/DNS2/RR/EUI64.php +++ b/Net/DNS2/RR/EUI64.php @@ -27,102 +27,100 @@ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_EUI64 extends Net_DNS2_RR -{ - // The EUI64 address, in hex format - public $address; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->address; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $value = array_shift($rdata); - - // - // re: RFC 7043, the field must be represented as 8 two-digit hex numbers - // separated by hyphens. - // - $a = explode('-', $value); - if (8 != cacti_sizeof($a)) { - return false; - } - - // - // make sure they're all hex values - // - foreach ($a as $i) { - if (false == ctype_xdigit($i)) { - return false; - } - } - - // - // store it - // - $this->address = strtolower($value); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $x = unpack('C8', $this->rdata); - if (8 == cacti_sizeof($x)) { - $this->address = vsprintf( - '%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x', - $x - ); - - return true; - } - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = ''; - - $a = explode('-', $this->address); - foreach ($a as $b) { - $data .= chr(hexdec($b)); - } - - $packet->offset += 8; - - return $data; - } +class Net_DNS2_RR_EUI64 extends Net_DNS2_RR { + // The EUI64 address, in hex format + public $address; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->address; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $value = array_shift($rdata); + + // + // re: RFC 7043, the field must be represented as 8 two-digit hex numbers + // separated by hyphens. + // + $a = explode('-', $value); + + if (cacti_sizeof($a) != 8) { + return false; + } + + // + // make sure they're all hex values + // + foreach ($a as $i) { + if (ctype_xdigit($i) == false) { + return false; + } + } + + // + // store it + // + $this->address = strtolower($value); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $x = unpack('C8', $this->rdata); + + if (cacti_sizeof($x) == 8) { + $this->address = vsprintf( + '%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x', + $x + ); + + return true; + } + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $data = ''; + + $a = explode('-', $this->address); + + foreach ($a as $b) { + $data .= chr(hexdec($b)); + } + + $packet->offset += 8; + + return $data; + } } diff --git a/Net/DNS2/RR/HINFO.php b/Net/DNS2/RR/HINFO.php index 4b3981b7..c651e451 100644 --- a/Net/DNS2/RR/HINFO.php +++ b/Net/DNS2/RR/HINFO.php @@ -26,84 +26,80 @@ * / OS / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_HINFO extends Net_DNS2_RR -{ - // computer informatino - public $cpu; - - // operataing system - public $os; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->formatString($this->cpu).' '.$this->formatString($this->os); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (2 == cacti_sizeof($data)) { - $this->cpu = trim($data[0], '"'); - $this->os = trim($data[1], '"'); - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; - - $this->cpu = Net_DNS2_Packet::label($packet, $offset); - $this->os = Net_DNS2_Packet::label($packet, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->cpu) > 0) { - $data = pack('Ca*Ca*', strlen($this->cpu), $this->cpu, strlen($this->os), $this->os); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_HINFO extends Net_DNS2_RR { + // computer informatino + public $cpu; + + // operataing system + public $os; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->formatString($this->cpu) . ' ' . $this->formatString($this->os); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $data = $this->buildString($rdata); + + if (cacti_sizeof($data) == 2) { + $this->cpu = trim($data[0], '"'); + $this->os = trim($data[1], '"'); + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; + + $this->cpu = Net_DNS2_Packet::label($packet, $offset); + $this->os = Net_DNS2_Packet::label($packet, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->cpu) > 0) { + $data = pack('Ca*Ca*', strlen($this->cpu), $this->cpu, strlen($this->os), $this->os); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/HIP.php b/Net/DNS2/RR/HIP.php index 317f2b48..27e8ae53 100644 --- a/Net/DNS2/RR/HIP.php +++ b/Net/DNS2/RR/HIP.php @@ -43,171 +43,166 @@ * | | * +-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_HIP extends Net_DNS2_RR -{ - // The length of the HIT field - public $hit_length; - - // the public key cryptographic algorithm - public $pk_algorithm; - - // the length of the public key field - public $pk_length; - - // The HIT is stored as a binary value in network byte order. - public $hit; - - // The public key - public $public_key; - - // a list of rendezvous servers - public $rendezvous_servers = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->pk_algorithm.' ' - .$this->hit.' '.$this->public_key.' '; - - foreach ($this->rendezvous_servers as $index => $server) { - $out .= $server.'. '; - } - - return trim($out); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->pk_algorithm = array_shift($rdata); - $this->hit = strtoupper(array_shift($rdata)); - $this->public_key = array_shift($rdata); - - // - // anything left on the array, must be one or more rendezevous servers. add - // them and strip off the trailing dot - // - if (cacti_sizeof($rdata) > 0) { - $this->rendezvous_servers = preg_replace('/\.$/', '', $rdata); - } - - // - // store the lengths; - // - $this->hit_length = strlen(pack('H*', $this->hit)); - $this->pk_length = strlen(base64_decode($this->public_key)); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the algorithm and length values - // - $x = unpack('Chit_length/Cpk_algorithm/npk_length', $this->rdata); - - $this->hit_length = $x['hit_length']; - $this->pk_algorithm = $x['pk_algorithm']; - $this->pk_length = $x['pk_length']; - - $offset = 4; - - // - // copy out the HIT value - // - $hit = unpack('H*', substr($this->rdata, $offset, $this->hit_length)); - - $this->hit = strtoupper($hit[1]); - $offset += $this->hit_length; - - // - // copy out the public key - // - $this->public_key = base64_encode( - substr($this->rdata, $offset, $this->pk_length) - ); - $offset += $this->pk_length; - - // - // copy out any possible rendezvous servers - // - $offset = $packet->offset + $offset; - - while (($offset - $packet->offset) < $this->rdlength) { - $this->rendezvous_servers[] = Net_DNS2_Packet::expand( - $packet, - $offset - ); - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if ((strlen($this->hit) > 0) && (strlen($this->public_key) > 0)) { - // - // pack the length, algorithm and HIT values - // - $data = pack( - 'CCnH*', - $this->hit_length, - $this->pk_algorithm, - $this->pk_length, - $this->hit - ); - - // - // add the public key - // - $data .= base64_decode($this->public_key); - - // - // add the offset - // - $packet->offset += strlen($data); - - // - // add each rendezvous server - // - foreach ($this->rendezvous_servers as $index => $server) { - $data .= $packet->compress($server, $packet->offset); - } - - return $data; - } - - return null; - } +class Net_DNS2_RR_HIP extends Net_DNS2_RR { + // The length of the HIT field + public $hit_length; + + // the public key cryptographic algorithm + public $pk_algorithm; + + // the length of the public key field + public $pk_length; + + // The HIT is stored as a binary value in network byte order. + public $hit; + + // The public key + public $public_key; + + // a list of rendezvous servers + public $rendezvous_servers = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->pk_algorithm . ' ' + . $this->hit . ' ' . $this->public_key . ' '; + + foreach ($this->rendezvous_servers as $index => $server) { + $out .= $server . '. '; + } + + return trim($out); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->pk_algorithm = array_shift($rdata); + $this->hit = strtoupper(array_shift($rdata)); + $this->public_key = array_shift($rdata); + + // + // anything left on the array, must be one or more rendezevous servers. add + // them and strip off the trailing dot + // + if (cacti_sizeof($rdata) > 0) { + $this->rendezvous_servers = preg_replace('/\.$/', '', $rdata); + } + + // + // store the lengths; + // + $this->hit_length = strlen(pack('H*', $this->hit)); + $this->pk_length = strlen(base64_decode($this->public_key, true)); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the algorithm and length values + // + $x = unpack('Chit_length/Cpk_algorithm/npk_length', $this->rdata); + + $this->hit_length = $x['hit_length']; + $this->pk_algorithm = $x['pk_algorithm']; + $this->pk_length = $x['pk_length']; + + $offset = 4; + + // + // copy out the HIT value + // + $hit = unpack('H*', substr($this->rdata, $offset, $this->hit_length)); + + $this->hit = strtoupper($hit[1]); + $offset += $this->hit_length; + + // + // copy out the public key + // + $this->public_key = base64_encode( + substr($this->rdata, $offset, $this->pk_length) + ); + $offset += $this->pk_length; + + // + // copy out any possible rendezvous servers + // + $offset = $packet->offset + $offset; + + while (($offset - $packet->offset) < $this->rdlength) { + $this->rendezvous_servers[] = Net_DNS2_Packet::expand( + $packet, + $offset + ); + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if ((strlen($this->hit) > 0) && (strlen($this->public_key) > 0)) { + // + // pack the length, algorithm and HIT values + // + $data = pack( + 'CCnH*', + $this->hit_length, + $this->pk_algorithm, + $this->pk_length, + $this->hit + ); + + // + // add the public key + // + $data .= base64_decode($this->public_key, true); + + // + // add the offset + // + $packet->offset += strlen($data); + + // + // add each rendezvous server + // + foreach ($this->rendezvous_servers as $index => $server) { + $data .= $packet->compress($server, $packet->offset); + } + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/IPSECKEY.php b/Net/DNS2/RR/IPSECKEY.php index b4b514c3..7ee50851 100644 --- a/Net/DNS2/RR/IPSECKEY.php +++ b/Net/DNS2/RR/IPSECKEY.php @@ -31,309 +31,286 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-| */ -class Net_DNS2_RR_IPSECKEY extends Net_DNS2_RR -{ - public const GATEWAY_TYPE_NONE = 0; - public const GATEWAY_TYPE_IPV4 = 1; - public const GATEWAY_TYPE_IPV6 = 2; - public const GATEWAY_TYPE_DOMAIN = 3; - - public const ALGORITHM_NONE = 0; - public const ALGORITHM_DSA = 1; - public const ALGORITHM_RSA = 2; - - // Precedence (used the same was as a preference field) - public $precedence; - - /* - * Gateway type - specifies the format of the gataway information - * This can be either: - * - * 0 No Gateway - * 1 IPv4 address - * 2 IPV6 address - * 3 wire-encoded domain name (not compressed) - * - */ - public $gateway_type; - - /* - * The algorithm used - * - * This can be: - * - * 0 No key is present - * 1 DSA key is present - * 2 RSA key is present - * - */ - public $algorithm; - - // The gatway information - public $gateway; - - // the public key - public $key; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->precedence.' '.$this->gateway_type.' ' - .$this->algorithm.' '; - - switch ($this->gateway_type) { - case self::GATEWAY_TYPE_NONE: - $out .= '. '; - - break; - - case self::GATEWAY_TYPE_IPV4: - case self::GATEWAY_TYPE_IPV6: - $out .= $this->gateway.' '; - - break; - - case self::GATEWAY_TYPE_DOMAIN: - $out .= $this->gateway.'. '; - - break; - } - - $out .= $this->key; - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // load the data - // - $precedence = array_shift($rdata); - $gateway_type = array_shift($rdata); - $algorithm = array_shift($rdata); - $gateway = trim(strtolower(trim(array_shift($rdata))), '.'); - $key = array_shift($rdata); - - // - // validate it - // - switch ($gateway_type) { - case self::GATEWAY_TYPE_NONE: - $gateway = ''; - - break; - - case self::GATEWAY_TYPE_IPV4: - if (false == Net_DNS2::isIPv4($gateway)) { - return false; - } - - break; - - case self::GATEWAY_TYPE_IPV6: - if (false == Net_DNS2::isIPv6($gateway)) { - return false; - } - - break; - - case self::GATEWAY_TYPE_DOMAIN:; // do nothing - - break; - - default: - return false; - } - - // - // check the algorithm and key - // - switch ($algorithm) { - case self::ALGORITHM_NONE: - $key = ''; - - break; - - case self::ALGORITHM_DSA: - case self::ALGORITHM_RSA:; // do nothing - - break; - - default: - return false; - } - - // - // store the values - // - $this->precedence = $precedence; - $this->gateway_type = $gateway_type; - $this->algorithm = $algorithm; - $this->gateway = $gateway; - $this->key = $key; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse off the precedence, gateway type and algorithm - // - $x = unpack('Cprecedence/Cgateway_type/Calgorithm', $this->rdata); - - $this->precedence = $x['precedence']; - $this->gateway_type = $x['gateway_type']; - $this->algorithm = $x['algorithm']; - - $offset = 3; - - // - // extract the gatway based on the type - // - switch ($this->gateway_type) { - case self::GATEWAY_TYPE_NONE: - $this->gateway = ''; - - break; - - case self::GATEWAY_TYPE_IPV4: - $this->gateway = inet_ntop(substr($this->rdata, $offset, 4)); - $offset += 4; - - break; - - case self::GATEWAY_TYPE_IPV6: - $ip = unpack('n8', substr($this->rdata, $offset, 16)); - if (8 == cacti_sizeof($ip)) { - $this->gateway = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); - $offset += 16; - } else { - return false; - } - - break; - - case self::GATEWAY_TYPE_DOMAIN: - $doffset = $offset + $packet->offset; - $this->gateway = Net_DNS2_Packet::expand($packet, $doffset); - $offset = ($doffset - $packet->offset); - - break; - - default: - return false; - } - - // - // extract the key - // - switch ($this->algorithm) { - case self::ALGORITHM_NONE: - $this->key = ''; - - break; - - case self::ALGORITHM_DSA: - case self::ALGORITHM_RSA: - $this->key = base64_encode(substr($this->rdata, $offset)); - - break; - - default: - return false; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // pack the precedence, gateway type and algorithm - // - $data = pack( - 'CCC', - $this->precedence, - $this->gateway_type, - $this->algorithm - ); - - // - // add the gateway based on the type - // - switch ($this->gateway_type) { - case self::GATEWAY_TYPE_NONE:; // add nothing - - break; - - case self::GATEWAY_TYPE_IPV4: - case self::GATEWAY_TYPE_IPV6: - $data .= inet_pton($this->gateway); - - break; - - case self::GATEWAY_TYPE_DOMAIN: - $data .= chr(strlen($this->gateway)).$this->gateway; - - break; - - default: - return null; - } - - // - // add the key if there's one specified - // - switch ($this->algorithm) { - case self::ALGORITHM_NONE:; // add nothing - - break; - - case self::ALGORITHM_DSA: - case self::ALGORITHM_RSA: - $data .= base64_decode($this->key); - - break; - - default: - return null; - } - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_IPSECKEY extends Net_DNS2_RR { + public const GATEWAY_TYPE_NONE = 0; + public const GATEWAY_TYPE_IPV4 = 1; + public const GATEWAY_TYPE_IPV6 = 2; + public const GATEWAY_TYPE_DOMAIN = 3; + + public const ALGORITHM_NONE = 0; + public const ALGORITHM_DSA = 1; + public const ALGORITHM_RSA = 2; + + // Precedence (used the same was as a preference field) + public $precedence; + + /* + * Gateway type - specifies the format of the gataway information + * This can be either: + * + * 0 No Gateway + * 1 IPv4 address + * 2 IPV6 address + * 3 wire-encoded domain name (not compressed) + * + */ + public $gateway_type; + + /* + * The algorithm used + * + * This can be: + * + * 0 No key is present + * 1 DSA key is present + * 2 RSA key is present + * + */ + public $algorithm; + + // The gatway information + public $gateway; + + // the public key + public $key; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->precedence . ' ' . $this->gateway_type . ' ' + . $this->algorithm . ' '; + + switch ($this->gateway_type) { + case self::GATEWAY_TYPE_NONE: + $out .= '. '; + + break; + case self::GATEWAY_TYPE_IPV4: + case self::GATEWAY_TYPE_IPV6: + $out .= $this->gateway . ' '; + + break; + case self::GATEWAY_TYPE_DOMAIN: + $out .= $this->gateway . '. '; + + break; + } + + $out .= $this->key; + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // load the data + // + $precedence = array_shift($rdata); + $gateway_type = array_shift($rdata); + $algorithm = array_shift($rdata); + $gateway = trim(strtolower(trim(array_shift($rdata))), '.'); + $key = array_shift($rdata); + + // + // validate it + // + switch ($gateway_type) { + case self::GATEWAY_TYPE_NONE: + $gateway = ''; + + break; + case self::GATEWAY_TYPE_IPV4: + if (Net_DNS2::isIPv4($gateway) == false) { + return false; + } + + break; + case self::GATEWAY_TYPE_IPV6: + if (Net_DNS2::isIPv6($gateway) == false) { + return false; + } + + break; + case self::GATEWAY_TYPE_DOMAIN:; // do nothing + + break; + default: + return false; + } + + // + // check the algorithm and key + // + switch ($algorithm) { + case self::ALGORITHM_NONE: + $key = ''; + + break; + case self::ALGORITHM_DSA: + case self::ALGORITHM_RSA:; // do nothing + + break; + default: + return false; + } + + // + // store the values + // + $this->precedence = $precedence; + $this->gateway_type = $gateway_type; + $this->algorithm = $algorithm; + $this->gateway = $gateway; + $this->key = $key; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse off the precedence, gateway type and algorithm + // + $x = unpack('Cprecedence/Cgateway_type/Calgorithm', $this->rdata); + + $this->precedence = $x['precedence']; + $this->gateway_type = $x['gateway_type']; + $this->algorithm = $x['algorithm']; + + $offset = 3; + + // + // extract the gatway based on the type + // + switch ($this->gateway_type) { + case self::GATEWAY_TYPE_NONE: + $this->gateway = ''; + + break; + case self::GATEWAY_TYPE_IPV4: + $this->gateway = inet_ntop(substr($this->rdata, $offset, 4)); + $offset += 4; + + break; + case self::GATEWAY_TYPE_IPV6: + $ip = unpack('n8', substr($this->rdata, $offset, 16)); + + if (cacti_sizeof($ip) == 8) { + $this->gateway = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); + $offset += 16; + } else { + return false; + } + + break; + case self::GATEWAY_TYPE_DOMAIN: + $doffset = $offset + $packet->offset; + $this->gateway = Net_DNS2_Packet::expand($packet, $doffset); + $offset = ($doffset - $packet->offset); + + break; + default: + return false; + } + + // + // extract the key + // + switch ($this->algorithm) { + case self::ALGORITHM_NONE: + $this->key = ''; + + break; + case self::ALGORITHM_DSA: + case self::ALGORITHM_RSA: + $this->key = base64_encode(substr($this->rdata, $offset)); + + break; + default: + return false; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + // + // pack the precedence, gateway type and algorithm + // + $data = pack( + 'CCC', + $this->precedence, + $this->gateway_type, + $this->algorithm + ); + + // + // add the gateway based on the type + // + switch ($this->gateway_type) { + case self::GATEWAY_TYPE_NONE:; // add nothing + + break; + case self::GATEWAY_TYPE_IPV4: + case self::GATEWAY_TYPE_IPV6: + $data .= inet_pton($this->gateway); + + break; + case self::GATEWAY_TYPE_DOMAIN: + $data .= chr(strlen($this->gateway)) . $this->gateway; + + break; + default: + return null; + } + + // + // add the key if there's one specified + // + switch ($this->algorithm) { + case self::ALGORITHM_NONE:; // add nothing + + break; + case self::ALGORITHM_DSA: + case self::ALGORITHM_RSA: + $data .= base64_decode($this->key, true); + + break; + default: + return null; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/ISDN.php b/Net/DNS2/RR/ISDN.php index c1438236..703c6b8d 100644 --- a/Net/DNS2/RR/ISDN.php +++ b/Net/DNS2/RR/ISDN.php @@ -26,97 +26,95 @@ * / SA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_ISDN extends Net_DNS2_RR -{ - // ISDN Number - public $isdnaddress; - - // Sub-Address - public $sa; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->formatString($this->isdnaddress).' ' - .$this->formatString($this->sa); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (cacti_sizeof($data) >= 1) { - $this->isdnaddress = $data[0]; - if (isset($data[1])) { - $this->sa = $data[1]; - } - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $this->isdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); - - // - // look for a SA (sub address) - it's optional - // - if ((strlen($this->isdnaddress) + 1) < $this->rdlength) { - $this->sa = Net_DNS2_Packet::label($packet, $packet->offset); - } else { - $this->sa = ''; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->isdnaddress) > 0) { - $data = chr(strlen($this->isdnaddress)).$this->isdnaddress; - if (!empty($this->sa)) { - $data .= chr(strlen($this->sa)); - $data .= $this->sa; - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_ISDN extends Net_DNS2_RR { + // ISDN Number + public $isdnaddress; + + // Sub-Address + public $sa; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->formatString($this->isdnaddress) . ' ' + . $this->formatString($this->sa); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $data = $this->buildString($rdata); + + if (cacti_sizeof($data) >= 1) { + $this->isdnaddress = $data[0]; + + if (isset($data[1])) { + $this->sa = $data[1]; + } + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $this->isdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); + + // + // look for a SA (sub address) - it's optional + // + if ((strlen($this->isdnaddress) + 1) < $this->rdlength) { + $this->sa = Net_DNS2_Packet::label($packet, $packet->offset); + } else { + $this->sa = ''; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->isdnaddress) > 0) { + $data = chr(strlen($this->isdnaddress)) . $this->isdnaddress; + + if (!empty($this->sa)) { + $data .= chr(strlen($this->sa)); + $data .= $this->sa; + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/KEY.php b/Net/DNS2/RR/KEY.php index 0e124ede..c711a51b 100644 --- a/Net/DNS2/RR/KEY.php +++ b/Net/DNS2/RR/KEY.php @@ -31,4 +31,5 @@ * We're not doing anything with these flags right now, so duplicating the * class like this is fine. */ -class Net_DNS2_RR_KEY extends Net_DNS2_RR_DNSKEY {} +class Net_DNS2_RR_KEY extends Net_DNS2_RR_DNSKEY { +} diff --git a/Net/DNS2/RR/KX.php b/Net/DNS2/RR/KX.php index edf31f57..f1209d1b 100644 --- a/Net/DNS2/RR/KX.php +++ b/Net/DNS2/RR/KX.php @@ -30,87 +30,82 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_KX extends Net_DNS2_RR -{ - // the preference for this mail exchanger - public $preference; +class Net_DNS2_RR_KX extends Net_DNS2_RR { + // the preference for this mail exchanger + public $preference; - // the hostname of the mail exchanger - public $exchange; + // the hostname of the mail exchanger + public $exchange; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->cleanString($this->exchange).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->cleanString($this->exchange) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = array_shift($rdata); - $this->exchange = $this->cleanString(array_shift($rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = array_shift($rdata); + $this->exchange = $this->cleanString(array_shift($rdata)); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse the preference - // - $x = unpack('npreference', $this->rdata); - $this->preference = $x['preference']; + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse the preference + // + $x = unpack('npreference', $this->rdata); + $this->preference = $x['preference']; - // - // get the exchange entry server) - // - $offset = $packet->offset + 2; - $this->exchange = Net_DNS2_Packet::label($packet, $offset); + // + // get the exchange entry server) + // + $offset = $packet->offset + 2; + $this->exchange = Net_DNS2_Packet::label($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->exchange) > 0) { - $data = pack('nC', $this->preference, strlen($this->exchange)) - .$this->exchange; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->exchange) > 0) { + $data = pack('nC', $this->preference, strlen($this->exchange)) + . $this->exchange; - $packet->offset += strlen($data); + $packet->offset += strlen($data); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/L32.php b/Net/DNS2/RR/L32.php index d34ac9cc..9b87cd5b 100644 --- a/Net/DNS2/RR/L32.php +++ b/Net/DNS2/RR/L32.php @@ -27,91 +27,86 @@ * | Locator32 (16 LSBs) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_L32 extends Net_DNS2_RR -{ - // The preference - public $preference; +class Net_DNS2_RR_L32 extends Net_DNS2_RR { + // The preference + public $preference; - // The locator32 field - public $locator32; + // The locator32 field + public $locator32; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->locator32; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->locator32; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = array_shift($rdata); - $this->locator32 = array_shift($rdata); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = array_shift($rdata); + $this->locator32 = array_shift($rdata); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the values - // - $x = unpack('npreference/C4locator', $this->rdata); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the values + // + $x = unpack('npreference/C4locator', $this->rdata); - $this->preference = $x['preference']; + $this->preference = $x['preference']; - // - // build the locator value - // - $this->locator32 = $x['locator1'].'.'.$x['locator2'].'.' - .$x['locator3'].'.'.$x['locator4']; + // + // build the locator value + // + $this->locator32 = $x['locator1'] . '.' . $x['locator2'] . '.' + . $x['locator3'] . '.' . $x['locator4']; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->locator32) > 0) { - // - // break out the locator value - // - $n = explode('.', $this->locator32); + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->locator32) > 0) { + // + // break out the locator value + // + $n = explode('.', $this->locator32); - // - // pack the data - // - return pack('nC4', $this->preference, $n[0], $n[1], $n[2], $n[3]); - } + // + // pack the data + // + return pack('nC4', $this->preference, $n[0], $n[1], $n[2], $n[3]); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/L64.php b/Net/DNS2/RR/L64.php index 9efcba12..3650c5f6 100644 --- a/Net/DNS2/RR/L64.php +++ b/Net/DNS2/RR/L64.php @@ -29,100 +29,95 @@ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_L64 extends Net_DNS2_RR -{ - // The preference - public $preference; +class Net_DNS2_RR_L64 extends Net_DNS2_RR { + // The preference + public $preference; - // The locator64 field - public $locator64; + // The locator64 field + public $locator64; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->locator64; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->locator64; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = array_shift($rdata); - $this->locator64 = array_shift($rdata); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = array_shift($rdata); + $this->locator64 = array_shift($rdata); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the values - // - $x = unpack('npreference/n4locator', $this->rdata); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the values + // + $x = unpack('npreference/n4locator', $this->rdata); - $this->preference = $x['preference']; + $this->preference = $x['preference']; - // - // build the locator64 - // - $this->locator64 = dechex($x['locator1']).':' - .dechex($x['locator2']).':' - .dechex($x['locator3']).':' - .dechex($x['locator4']); + // + // build the locator64 + // + $this->locator64 = dechex($x['locator1']) . ':' + . dechex($x['locator2']) . ':' + . dechex($x['locator3']) . ':' + . dechex($x['locator4']); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->locator64) > 0) { - // - // break out the locator64 - // - $n = explode(':', $this->locator64); + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->locator64) > 0) { + // + // break out the locator64 + // + $n = explode(':', $this->locator64); - // - // pack the data - // - return pack( - 'n5', - $this->preference, - hexdec($n[0]), - hexdec($n[1]), - hexdec($n[2]), - hexdec($n[3]) - ); - } + // + // pack the data + // + return pack( + 'n5', + $this->preference, + hexdec($n[0]), + hexdec($n[1]), + hexdec($n[2]), + hexdec($n[3]) + ); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/LOC.php b/Net/DNS2/RR/LOC.php index c025b14c..9dcc3dcf 100644 --- a/Net/DNS2/RR/LOC.php +++ b/Net/DNS2/RR/LOC.php @@ -35,309 +35,302 @@ * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_LOC extends Net_DNS2_RR -{ - // some conversion values - public const CONV_SEC = 1000; - public const CONV_MIN = 60000; - public const CONV_DEG = 3600000; - - public const REFERENCE_ALT = 10000000; - public const REFERENCE_LATLON = 2147483648; - // the LOC version- should only ever be 0 - public $version; - - // The diameter of a sphere enclosing the described entity - public $size; - - // The horizontal precision of the data - public $horiz_pre; - - // The vertical precision of the data - public $vert_pre; - - // The latitude - stored in decimal degrees - public $latitude; - - // The longitude - stored in decimal degrees - public $longitude; - - // The altitude - stored in decimal - public $altitude; - - // used for quick power-of-ten lookups - private $_powerOfTen = [1, 10, 100, 1000, 10000, 100000, - 1000000, 10000000, 100000000, 1000000000]; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - if (0 == $this->version) { - return $this->_d2Dms($this->latitude, 'LAT').' ' - .$this->_d2Dms($this->longitude, 'LNG').' ' - .sprintf('%.2fm', $this->altitude).' ' - .sprintf('%.2fm', $this->size).' ' - .sprintf('%.2fm', $this->horiz_pre).' ' - .sprintf('%.2fm', $this->vert_pre); - } - - return ''; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // format as defined by RFC1876 section 3 - // - // d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] - // [siz["m"] [hp["m"] [vp["m"]]]] - // - $res = preg_match( - '/^(\d+) \s+((\d+) \s+)?(([\d.]+) \s+)?(N|S) \s+(\d+) ' - .'\s+((\d+) \s+)?(([\d.]+) \s+)?(E|W) \s+(-?[\d.]+) m?(\s+ ' - .'([\d.]+) m?)?(\s+ ([\d.]+) m?)?(\s+ ([\d.]+) m?)?/ix', - implode(' ', $rdata), - $x - ); - - if ($res) { - // - // latitude - // - $latdeg = $x[1]; - $latmin = (isset($x[3])) ? $x[3] : 0; - $latsec = (isset($x[5])) ? $x[5] : 0; - $lathem = strtoupper($x[6]); - - $this->latitude = $this->_dms2d($latdeg, $latmin, $latsec, $lathem); - - // - // longitude - // - $londeg = $x[7]; - $lonmin = (isset($x[9])) ? $x[9] : 0; - $lonsec = (isset($x[11])) ? $x[11] : 0; - $lonhem = strtoupper($x[12]); - - $this->longitude = $this->_dms2d($londeg, $lonmin, $lonsec, $lonhem); - - // - // the rest of teh values - // - $version = 0; - - $this->size = (isset($x[15])) ? $x[15] : 1; - $this->horiz_pre = ((isset($x[17])) ? $x[17] : 10000); - $this->vert_pre = ((isset($x[19])) ? $x[19] : 10); - $this->altitude = $x[13]; - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack all the values - // - $x = unpack( - 'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude', - $this->rdata - ); - - // - // version must be 0 per RFC 1876 section 2 - // - $this->version = $x['ver']; - if (0 == $this->version) { - $this->size = $this->_precsizeNtoA($x['size']); - $this->horiz_pre = $this->_precsizeNtoA($x['horiz_pre']); - $this->vert_pre = $this->_precsizeNtoA($x['vert_pre']); - - // - // convert the latitude and longitude to degress in decimal - // - if ($x['latitude'] < 0) { - $this->latitude = ($x['latitude'] - + self::REFERENCE_LATLON) / self::CONV_DEG; - } else { - $this->latitude = ($x['latitude'] - - self::REFERENCE_LATLON) / self::CONV_DEG; - } - - if ($x['longitude'] < 0) { - $this->longitude = ($x['longitude'] - + self::REFERENCE_LATLON) / self::CONV_DEG; - } else { - $this->longitude = ($x['longitude'] - - self::REFERENCE_LATLON) / self::CONV_DEG; - } - - // - // convert down the altitude - // - $this->altitude = ($x['altitude'] - self::REFERENCE_ALT) / 100; - - return true; - } - - return false; - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (0 == $this->version) { - $lat = 0; - $lng = 0; - - if ($this->latitude < 0) { - $lat = ($this->latitude * self::CONV_DEG) - self::REFERENCE_LATLON; - } else { - $lat = ($this->latitude * self::CONV_DEG) + self::REFERENCE_LATLON; - } - - if ($this->longitude < 0) { - $lng = ($this->longitude * self::CONV_DEG) - self::REFERENCE_LATLON; - } else { - $lng = ($this->longitude * self::CONV_DEG) + self::REFERENCE_LATLON; - } - - $packet->offset += 16; - - return pack( - 'CCCCNNN', - $this->version, - $this->_precsizeAtoN($this->size), - $this->_precsizeAtoN($this->horiz_pre), - $this->_precsizeAtoN($this->vert_pre), - $lat, - $lng, - ($this->altitude * 100) + self::REFERENCE_ALT - ); - } - - return null; - } - - /** - * takes an XeY precision/size value, returns a string representation. - * shamlessly stolen from RFC1876 Appendix A. - * - * @param int $prec the value to convert - * - * @return string - */ - private function _precsizeNtoA($prec) - { - $mantissa = (($prec >> 4) & 0x0F) % 10; - $exponent = (($prec >> 0) & 0x0F) % 10; - - return $mantissa * $this->_powerOfTen[$exponent]; - } - - /** - * converts ascii size/precision X * 10**Y(cm) to 0xXY. - * shamlessly stolen from RFC1876 Appendix A. - * - * @param string $prec the value to convert - * - * @return int - */ - private function _precsizeAtoN($prec) - { - $exponent = 0; - while ($prec >= 10) { - $prec /= 10; - ++$exponent; - } - - return ($prec << 4) | ($exponent & 0x0F); - } - - /** - * convert lat/lng in deg/min/sec/hem to decimal value. - * - * @param int $deg the degree value - * @param int $min the minutes value - * @param int $sec the seconds value - * @param string $hem the hemisphere (N/E/S/W) - * - * @return float the decinmal value - */ - private function _dms2d($deg, $min, $sec, $hem) - { - $deg = $deg - 0; - $min = $min - 0; - - $sign = ('W' == $hem || 'S' == $hem) ? -1 : 1; - - return ((($sec / 60 + $min) / 60) + $deg) * $sign; - } - - /** - * convert lat/lng in decimal to deg/min/sec/hem. - * - * @param float $data the decimal value - * @param string $latlng either LAT or LNG so we can determine the HEM value - * - * @return string - */ - private function _d2Dms($data, $latlng) - { - $deg = 0; - $min = 0; - $sec = 0; - $msec = 0; - $hem = ''; - - if ('LAT' == $latlng) { - $hem = ($data > 0) ? 'N' : 'S'; - } else { - $hem = ($data > 0) ? 'E' : 'W'; - } - - $data = abs($data); - - $deg = (int) $data; - $min = (int) (($data - $deg) * 60); - $sec = (int) (((($data - $deg) * 60) - $min) * 60); - $msec = round(((((($data - $deg) * 60) - $min) * 60) - $sec) * 1000); - - return sprintf('%d %02d %02d.%03d %s', $deg, $min, $sec, round($msec), $hem); - } +class Net_DNS2_RR_LOC extends Net_DNS2_RR { + // some conversion values + public const CONV_SEC = 1000; + public const CONV_MIN = 60000; + public const CONV_DEG = 3600000; + + public const REFERENCE_ALT = 10000000; + public const REFERENCE_LATLON = 2147483648; + // the LOC version- should only ever be 0 + public $version; + + // The diameter of a sphere enclosing the described entity + public $size; + + // The horizontal precision of the data + public $horiz_pre; + + // The vertical precision of the data + public $vert_pre; + + // The latitude - stored in decimal degrees + public $latitude; + + // The longitude - stored in decimal degrees + public $longitude; + + // The altitude - stored in decimal + public $altitude; + + // used for quick power-of-ten lookups + private $_powerOfTen = [1, 10, 100, 1000, 10000, 100000, + 1000000, 10000000, 100000000, 1000000000]; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + if ($this->version == 0) { + return $this->_d2Dms($this->latitude, 'LAT') . ' ' + . $this->_d2Dms($this->longitude, 'LNG') . ' ' + . sprintf('%.2fm', $this->altitude) . ' ' + . sprintf('%.2fm', $this->size) . ' ' + . sprintf('%.2fm', $this->horiz_pre) . ' ' + . sprintf('%.2fm', $this->vert_pre); + } + + return ''; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // format as defined by RFC1876 section 3 + // + // d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] + // [siz["m"] [hp["m"] [vp["m"]]]] + // + $res = preg_match( + '/^(\d+) \s+((\d+) \s+)?(([\d.]+) \s+)?(N|S) \s+(\d+) ' + . '\s+((\d+) \s+)?(([\d.]+) \s+)?(E|W) \s+(-?[\d.]+) m?(\s+ ' + . '([\d.]+) m?)?(\s+ ([\d.]+) m?)?(\s+ ([\d.]+) m?)?/ix', + implode(' ', $rdata), + $x + ); + + if ($res) { + // + // latitude + // + $latdeg = $x[1]; + $latmin = (isset($x[3])) ? $x[3] : 0; + $latsec = (isset($x[5])) ? $x[5] : 0; + $lathem = strtoupper($x[6]); + + $this->latitude = $this->_dms2d($latdeg, $latmin, $latsec, $lathem); + + // + // longitude + // + $londeg = $x[7]; + $lonmin = (isset($x[9])) ? $x[9] : 0; + $lonsec = (isset($x[11])) ? $x[11] : 0; + $lonhem = strtoupper($x[12]); + + $this->longitude = $this->_dms2d($londeg, $lonmin, $lonsec, $lonhem); + + // + // the rest of teh values + // + $version = 0; + + $this->size = (isset($x[15])) ? $x[15] : 1; + $this->horiz_pre = ((isset($x[17])) ? $x[17] : 10000); + $this->vert_pre = ((isset($x[19])) ? $x[19] : 10); + $this->altitude = $x[13]; + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack all the values + // + $x = unpack( + 'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude', + $this->rdata + ); + + // + // version must be 0 per RFC 1876 section 2 + // + $this->version = $x['ver']; + + if ($this->version == 0) { + $this->size = $this->_precsizeNtoA($x['size']); + $this->horiz_pre = $this->_precsizeNtoA($x['horiz_pre']); + $this->vert_pre = $this->_precsizeNtoA($x['vert_pre']); + + // + // convert the latitude and longitude to degress in decimal + // + if ($x['latitude'] < 0) { + $this->latitude = ($x['latitude'] + + self::REFERENCE_LATLON) / self::CONV_DEG; + } else { + $this->latitude = ($x['latitude'] + - self::REFERENCE_LATLON) / self::CONV_DEG; + } + + if ($x['longitude'] < 0) { + $this->longitude = ($x['longitude'] + + self::REFERENCE_LATLON) / self::CONV_DEG; + } else { + $this->longitude = ($x['longitude'] + - self::REFERENCE_LATLON) / self::CONV_DEG; + } + + // + // convert down the altitude + // + $this->altitude = ($x['altitude'] - self::REFERENCE_ALT) / 100; + + return true; + } + + return false; + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if ($this->version == 0) { + $lat = 0; + $lng = 0; + + if ($this->latitude < 0) { + $lat = ($this->latitude * self::CONV_DEG) - self::REFERENCE_LATLON; + } else { + $lat = ($this->latitude * self::CONV_DEG) + self::REFERENCE_LATLON; + } + + if ($this->longitude < 0) { + $lng = ($this->longitude * self::CONV_DEG) - self::REFERENCE_LATLON; + } else { + $lng = ($this->longitude * self::CONV_DEG) + self::REFERENCE_LATLON; + } + + $packet->offset += 16; + + return pack( + 'CCCCNNN', + $this->version, + $this->_precsizeAtoN($this->size), + $this->_precsizeAtoN($this->horiz_pre), + $this->_precsizeAtoN($this->vert_pre), + $lat, + $lng, + ($this->altitude * 100) + self::REFERENCE_ALT + ); + } + + return null; + } + + /** + * takes an XeY precision/size value, returns a string representation. + * shamlessly stolen from RFC1876 Appendix A. + * + * @param int $prec the value to convert + * + * @return string + */ + private function _precsizeNtoA($prec) { + $mantissa = (($prec >> 4) & 0x0F) % 10; + $exponent = (($prec >> 0) & 0x0F) % 10; + + return $mantissa * $this->_powerOfTen[$exponent]; + } + + /** + * converts ascii size/precision X * 10**Y(cm) to 0xXY. + * shamlessly stolen from RFC1876 Appendix A. + * + * @param string $prec the value to convert + * + * @return int + */ + private function _precsizeAtoN($prec) { + $exponent = 0; + + while ($prec >= 10) { + $prec /= 10; + ++$exponent; + } + + return ($prec << 4) | ($exponent & 0x0F); + } + + /** + * convert lat/lng in deg/min/sec/hem to decimal value. + * + * @param int $deg the degree value + * @param int $min the minutes value + * @param int $sec the seconds value + * @param string $hem the hemisphere (N/E/S/W) + * + * @return float the decinmal value + */ + private function _dms2d($deg, $min, $sec, $hem) { + $deg = $deg - 0; + $min = $min - 0; + + $sign = ($hem == 'W' || $hem == 'S') ? -1 : 1; + + return ((($sec / 60 + $min) / 60) + $deg) * $sign; + } + + /** + * convert lat/lng in decimal to deg/min/sec/hem. + * + * @param float $data the decimal value + * @param string $latlng either LAT or LNG so we can determine the HEM value + * + * @return string + */ + private function _d2Dms($data, $latlng) { + $deg = 0; + $min = 0; + $sec = 0; + $msec = 0; + $hem = ''; + + if ($latlng == 'LAT') { + $hem = ($data > 0) ? 'N' : 'S'; + } else { + $hem = ($data > 0) ? 'E' : 'W'; + } + + $data = abs($data); + + $deg = (int) $data; + $min = (int) (($data - $deg) * 60); + $sec = (int) (((($data - $deg) * 60) - $min) * 60); + $msec = round(((((($data - $deg) * 60) - $min) * 60) - $sec) * 1000); + + return sprintf('%d %02d %02d.%03d %s', $deg, $min, $sec, round($msec), $hem); + } } diff --git a/Net/DNS2/RR/LP.php b/Net/DNS2/RR/LP.php index 17282c5b..088b4c27 100644 --- a/Net/DNS2/RR/LP.php +++ b/Net/DNS2/RR/LP.php @@ -29,87 +29,82 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_LP extends Net_DNS2_RR -{ - // The preference - public $preference; +class Net_DNS2_RR_LP extends Net_DNS2_RR { + // The preference + public $preference; - // The fdqn field - public $fqdn; + // The fdqn field + public $fqdn; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->fqdn.'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->fqdn . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = array_shift($rdata); - $this->fqdn = trim(array_shift($rdata), '.'); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = array_shift($rdata); + $this->fqdn = trim(array_shift($rdata), '.'); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse the preference - // - $x = unpack('npreference', $this->rdata); - $this->preference = $x['preference']; - $offset = $packet->offset + 2; + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse the preference + // + $x = unpack('npreference', $this->rdata); + $this->preference = $x['preference']; + $offset = $packet->offset + 2; - // - // get the hostname - // - $this->fqdn = Net_DNS2_Packet::expand($packet, $offset); + // + // get the hostname + // + $this->fqdn = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->fqdn) > 0) { - $data = pack('n', $this->preference); - $packet->offset += 2; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->fqdn) > 0) { + $data = pack('n', $this->preference); + $packet->offset += 2; - $data .= $packet->compress($this->fqdn, $packet->offset); + $data .= $packet->compress($this->fqdn, $packet->offset); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/MX.php b/Net/DNS2/RR/MX.php index 42dcb452..25fb9e03 100644 --- a/Net/DNS2/RR/MX.php +++ b/Net/DNS2/RR/MX.php @@ -27,87 +27,82 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_MX extends Net_DNS2_RR -{ - // the preference for this mail exchanger - public $preference; +class Net_DNS2_RR_MX extends Net_DNS2_RR { + // the preference for this mail exchanger + public $preference; - // the hostname of the mail exchanger - public $exchange; + // the hostname of the mail exchanger + public $exchange; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->cleanString($this->exchange).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->cleanString($this->exchange) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = array_shift($rdata); - $this->exchange = $this->cleanString(array_shift($rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = array_shift($rdata); + $this->exchange = $this->cleanString(array_shift($rdata)); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse the preference - // - $x = unpack('npreference', $this->rdata); - $this->preference = $x['preference']; + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse the preference + // + $x = unpack('npreference', $this->rdata); + $this->preference = $x['preference']; - // - // get the exchange entry server) - // - $offset = $packet->offset + 2; - $this->exchange = Net_DNS2_Packet::expand($packet, $offset); + // + // get the exchange entry server) + // + $offset = $packet->offset + 2; + $this->exchange = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->exchange) > 0) { - $data = pack('n', $this->preference); - $packet->offset += 2; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->exchange) > 0) { + $data = pack('n', $this->preference); + $packet->offset += 2; - $data .= $packet->compress($this->exchange, $packet->offset); + $data .= $packet->compress($this->exchange, $packet->offset); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/NAPTR.php b/Net/DNS2/RR/NAPTR.php index bd22c6e2..7edde027 100644 --- a/Net/DNS2/RR/NAPTR.php +++ b/Net/DNS2/RR/NAPTR.php @@ -36,128 +36,124 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_NAPTR extends Net_DNS2_RR -{ - // the order in which the NAPTR records MUST be processed - public $order; - - /* - * specifies the order in which NAPTR records with equal "order" - * values SHOULD be processed - */ - public $preference; - - // rewrite flags - public $flags; - - // Specifies the service(s) available down this rewrite path - public $services; - - // regular expression - public $regexp; - - /* - * The next NAME to query for NAPTR, SRV, or address records - * depending on the value of the flags field - */ - public $replacement; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->order.' '.$this->preference.' ' - .$this->formatString($this->flags).' ' - .$this->formatString($this->services).' ' - .$this->formatString($this->regexp).' ' - .$this->cleanString($this->replacement).'.'; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->order = array_shift($rdata); - $this->preference = array_shift($rdata); - - $data = $this->buildString($rdata); - if (4 == cacti_sizeof($data)) { - $this->flags = $data[0]; - $this->services = $data[1]; - $this->regexp = $data[2]; - $this->replacement = $this->cleanString($data[3]); - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the order and preference - // - $x = unpack('norder/npreference', $this->rdata); - - $this->order = $x['order']; - $this->preference = $x['preference']; - - $offset = $packet->offset + 4; - - $this->flags = Net_DNS2_Packet::label($packet, $offset); - $this->services = Net_DNS2_Packet::label($packet, $offset); - $this->regexp = Net_DNS2_Packet::label($packet, $offset); - - $this->replacement = Net_DNS2_Packet::expand($packet, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if ((isset($this->order)) && (strlen($this->services) > 0)) { - $data = pack('nn', $this->order, $this->preference); - - $data .= chr(strlen($this->flags)).$this->flags; - $data .= chr(strlen($this->services)).$this->services; - $data .= chr(strlen($this->regexp)).$this->regexp; - - $packet->offset += strlen($data); - - $data .= $packet->compress($this->replacement, $packet->offset); - - return $data; - } - - return null; - } +class Net_DNS2_RR_NAPTR extends Net_DNS2_RR { + // the order in which the NAPTR records MUST be processed + public $order; + + /* + * specifies the order in which NAPTR records with equal "order" + * values SHOULD be processed + */ + public $preference; + + // rewrite flags + public $flags; + + // Specifies the service(s) available down this rewrite path + public $services; + + // regular expression + public $regexp; + + /* + * The next NAME to query for NAPTR, SRV, or address records + * depending on the value of the flags field + */ + public $replacement; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->order . ' ' . $this->preference . ' ' + . $this->formatString($this->flags) . ' ' + . $this->formatString($this->services) . ' ' + . $this->formatString($this->regexp) . ' ' + . $this->cleanString($this->replacement) . '.'; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->order = array_shift($rdata); + $this->preference = array_shift($rdata); + + $data = $this->buildString($rdata); + + if (cacti_sizeof($data) == 4) { + $this->flags = $data[0]; + $this->services = $data[1]; + $this->regexp = $data[2]; + $this->replacement = $this->cleanString($data[3]); + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the order and preference + // + $x = unpack('norder/npreference', $this->rdata); + + $this->order = $x['order']; + $this->preference = $x['preference']; + + $offset = $packet->offset + 4; + + $this->flags = Net_DNS2_Packet::label($packet, $offset); + $this->services = Net_DNS2_Packet::label($packet, $offset); + $this->regexp = Net_DNS2_Packet::label($packet, $offset); + + $this->replacement = Net_DNS2_Packet::expand($packet, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if ((isset($this->order)) && (strlen($this->services) > 0)) { + $data = pack('nn', $this->order, $this->preference); + + $data .= chr(strlen($this->flags)) . $this->flags; + $data .= chr(strlen($this->services)) . $this->services; + $data .= chr(strlen($this->regexp)) . $this->regexp; + + $packet->offset += strlen($data); + + $data .= $packet->compress($this->replacement, $packet->offset); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/NID.php b/Net/DNS2/RR/NID.php index 0f65ca11..bd64481f 100644 --- a/Net/DNS2/RR/NID.php +++ b/Net/DNS2/RR/NID.php @@ -29,100 +29,95 @@ * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_NID extends Net_DNS2_RR -{ - // The preference - public $preference; +class Net_DNS2_RR_NID extends Net_DNS2_RR { + // The preference + public $preference; - // The node ID field - public $nodeid; + // The node ID field + public $nodeid; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->nodeid; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->nodeid; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = array_shift($rdata); - $this->nodeid = array_shift($rdata); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = array_shift($rdata); + $this->nodeid = array_shift($rdata); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the values - // - $x = unpack('npreference/n4nodeid', $this->rdata); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the values + // + $x = unpack('npreference/n4nodeid', $this->rdata); - $this->preference = $x['preference']; + $this->preference = $x['preference']; - // - // build the node id - // - $this->nodeid = dechex($x['nodeid1']).':' - .dechex($x['nodeid2']).':' - .dechex($x['nodeid3']).':' - .dechex($x['nodeid4']); + // + // build the node id + // + $this->nodeid = dechex($x['nodeid1']) . ':' + . dechex($x['nodeid2']) . ':' + . dechex($x['nodeid3']) . ':' + . dechex($x['nodeid4']); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->nodeid) > 0) { - // - // break out the node id - // - $n = explode(':', $this->nodeid); + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->nodeid) > 0) { + // + // break out the node id + // + $n = explode(':', $this->nodeid); - // - // pack the data - // - return pack( - 'n5', - $this->preference, - hexdec($n[0]), - hexdec($n[1]), - hexdec($n[2]), - hexdec($n[3]) - ); - } + // + // pack the data + // + return pack( + 'n5', + $this->preference, + hexdec($n[0]), + hexdec($n[1]), + hexdec($n[2]), + hexdec($n[3]) + ); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/NIMLOC.php b/Net/DNS2/RR/NIMLOC.php index f534880e..25c45391 100644 --- a/Net/DNS2/RR/NIMLOC.php +++ b/Net/DNS2/RR/NIMLOC.php @@ -21,53 +21,48 @@ * NIMLOC Resource Record - undefined; the rdata is simply used as-is in it's * binary format, so not process has to be done. */ -class Net_DNS2_RR_NIMLOC extends Net_DNS2_RR -{ - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return ''; - } +class Net_DNS2_RR_NIMLOC extends Net_DNS2_RR { + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return ''; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - return true; - } + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - return true; - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + return true; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - return $this->rdata; - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + return $this->rdata; + } } diff --git a/Net/DNS2/RR/NS.php b/Net/DNS2/RR/NS.php index fd03d977..0693385b 100644 --- a/Net/DNS2/RR/NS.php +++ b/Net/DNS2/RR/NS.php @@ -25,69 +25,64 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_NS extends Net_DNS2_RR -{ - // the hostname of the DNS server - public $nsdname; +class Net_DNS2_RR_NS extends Net_DNS2_RR { + // the hostname of the DNS server + public $nsdname; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->nsdname).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->nsdname) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->nsdname = $this->cleanString(array_shift($rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->nsdname = $this->cleanString(array_shift($rdata)); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; - $this->nsdname = Net_DNS2_Packet::expand($packet, $offset); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; + $this->nsdname = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->nsdname) > 0) { - return $packet->compress($this->nsdname, $packet->offset); - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->nsdname) > 0) { + return $packet->compress($this->nsdname, $packet->offset); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/NSAP.php b/Net/DNS2/RR/NSAP.php index 1d4281ac..af4c3880 100644 --- a/Net/DNS2/RR/NSAP.php +++ b/Net/DNS2/RR/NSAP.php @@ -30,172 +30,167 @@ * octets | 1 | 2 | 1 | 3 | 2 | 2 | 2 | 6 | 1 | * |-----|--------|-----|----|-----|----|-----|----|----| */ -class Net_DNS2_RR_NSAP extends Net_DNS2_RR -{ - public $afi; - public $idi; - public $dfi; - public $aa; - public $rsvd; - public $rd; - public $area; - public $id; - public $sel; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->afi).'.' - .$this->cleanString($this->idi).'.' - .$this->cleanString($this->dfi).'.' - .$this->cleanString($this->aa).'.' - .$this->cleanString($this->rsvd).'.' - .$this->cleanString($this->rd).'.' - .$this->cleanString($this->area).'.' - .$this->cleanString($this->id).'.' - .$this->sel; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $data = strtolower(trim(array_shift($rdata))); - - // - // there is no real standard for format, so we can't rely on the fact that - // the value will come in with periods separating the values- so strip - // them out if they're included, and parse without them. - // - $data = str_replace(['.', '0x'], '', $data); - - // - // unpack it as ascii characters - // - $x = unpack('A2afi/A4idi/A2dfi/A6aa/A4rsvd/A4rd/A4area/A12id/A2sel', $data); - - // - // make sure the afi value is 47 - // - if ('47' == $x['afi']) { - $this->afi = '0x'.$x['afi']; - $this->idi = $x['idi']; - $this->dfi = $x['dfi']; - $this->aa = $x['aa']; - $this->rsvd = $x['rsvd']; - $this->rd = $x['rd']; - $this->area = $x['area']; - $this->id = $x['id']; - $this->sel = $x['sel']; - - return true; - } - - return false; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if (20 == $this->rdlength) { - // - // get the AFI value - // - $this->afi = dechex(ord($this->rdata[0])); - - // - // we only support AFI 47- there arent' any others defined. - // - if ('47' == $this->afi) { - // - // unpack the rest of the values - // - $x = unpack( - 'Cafi/nidi/Cdfi/C3aa/nrsvd/nrd/narea/Nidh/nidl/Csel', - $this->rdata - ); - - $this->afi = sprintf('0x%02x', $x['afi']); - $this->idi = sprintf('%04x', $x['idi']); - $this->dfi = sprintf('%02x', $x['dfi']); - $this->aa = sprintf( - '%06x', - $x['aa1'] << 16 | $x['aa2'] << 8 | $x['aa3'] - ); - $this->rsvd = sprintf('%04x', $x['rsvd']); - $this->rd = sprintf('%04x', $x['rd']); - $this->area = sprintf('%04x', $x['area']); - $this->id = sprintf('%08x', $x['idh']) - .sprintf('%04x', $x['idl']); - $this->sel = sprintf('%02x', $x['sel']); - - return true; - } - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if ('0x47' == $this->afi) { - // - // build the aa field - // - $aa = unpack('A2x/A2y/A2z', $this->aa); - - // - // build the id field - // - $id = unpack('A8a/A4b', $this->id); - - $data = pack( - 'CnCCCCnnnNnC', - hexdec($this->afi), - hexdec($this->idi), - hexdec($this->dfi), - hexdec($aa['x']), - hexdec($aa['y']), - hexdec($aa['z']), - hexdec($this->rsvd), - hexdec($this->rd), - hexdec($this->area), - hexdec($id['a']), - hexdec($id['b']), - hexdec($this->sel) - ); - - if (20 == strlen($data)) { - $packet->offset += 20; - - return $data; - } - } - - return null; - } +class Net_DNS2_RR_NSAP extends Net_DNS2_RR { + public $afi; + public $idi; + public $dfi; + public $aa; + public $rsvd; + public $rd; + public $area; + public $id; + public $sel; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->afi) . '.' + . $this->cleanString($this->idi) . '.' + . $this->cleanString($this->dfi) . '.' + . $this->cleanString($this->aa) . '.' + . $this->cleanString($this->rsvd) . '.' + . $this->cleanString($this->rd) . '.' + . $this->cleanString($this->area) . '.' + . $this->cleanString($this->id) . '.' + . $this->sel; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $data = strtolower(trim(array_shift($rdata))); + + // + // there is no real standard for format, so we can't rely on the fact that + // the value will come in with periods separating the values- so strip + // them out if they're included, and parse without them. + // + $data = str_replace(['.', '0x'], '', $data); + + // + // unpack it as ascii characters + // + $x = unpack('A2afi/A4idi/A2dfi/A6aa/A4rsvd/A4rd/A4area/A12id/A2sel', $data); + + // + // make sure the afi value is 47 + // + if ($x['afi'] == '47') { + $this->afi = '0x' . $x['afi']; + $this->idi = $x['idi']; + $this->dfi = $x['dfi']; + $this->aa = $x['aa']; + $this->rsvd = $x['rsvd']; + $this->rd = $x['rd']; + $this->area = $x['area']; + $this->id = $x['id']; + $this->sel = $x['sel']; + + return true; + } + + return false; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength == 20) { + // + // get the AFI value + // + $this->afi = dechex(ord($this->rdata[0])); + + // + // we only support AFI 47- there arent' any others defined. + // + if ($this->afi == '47') { + // + // unpack the rest of the values + // + $x = unpack( + 'Cafi/nidi/Cdfi/C3aa/nrsvd/nrd/narea/Nidh/nidl/Csel', + $this->rdata + ); + + $this->afi = sprintf('0x%02x', $x['afi']); + $this->idi = sprintf('%04x', $x['idi']); + $this->dfi = sprintf('%02x', $x['dfi']); + $this->aa = sprintf( + '%06x', + $x['aa1'] << 16 | $x['aa2'] << 8 | $x['aa3'] + ); + $this->rsvd = sprintf('%04x', $x['rsvd']); + $this->rd = sprintf('%04x', $x['rd']); + $this->area = sprintf('%04x', $x['area']); + $this->id = sprintf('%08x', $x['idh']) + . sprintf('%04x', $x['idl']); + $this->sel = sprintf('%02x', $x['sel']); + + return true; + } + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if ($this->afi == '0x47') { + // + // build the aa field + // + $aa = unpack('A2x/A2y/A2z', $this->aa); + + // + // build the id field + // + $id = unpack('A8a/A4b', $this->id); + + $data = pack( + 'CnCCCCnnnNnC', + hexdec($this->afi), + hexdec($this->idi), + hexdec($this->dfi), + hexdec($aa['x']), + hexdec($aa['y']), + hexdec($aa['z']), + hexdec($this->rsvd), + hexdec($this->rd), + hexdec($this->area), + hexdec($id['a']), + hexdec($id['b']), + hexdec($this->sel) + ); + + if (strlen($data) == 20) { + $packet->offset += 20; + + return $data; + } + } + + return null; + } } diff --git a/Net/DNS2/RR/NSEC.php b/Net/DNS2/RR/NSEC.php index ba7e2524..74b0984e 100644 --- a/Net/DNS2/RR/NSEC.php +++ b/Net/DNS2/RR/NSEC.php @@ -27,94 +27,89 @@ * / List of Type Bit Map(s) / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_NSEC extends Net_DNS2_RR -{ - // The next owner name - public $next_domain_name; - - // identifies the RRset types that exist at the NSEC RR's owner name. - public $type_bit_maps = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $data = $this->cleanString($this->next_domain_name).'.'; - - foreach ($this->type_bit_maps as $rr) { - $data .= ' '.$rr; - } - - return $data; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->next_domain_name = $this->cleanString(array_shift($rdata)); - $this->type_bit_maps = $rdata; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // expand the next domain name - // - $offset = $packet->offset; - $this->next_domain_name = Net_DNS2_Packet::expand($packet, $offset); - - // - // parse out the RR's from the bitmap - // - $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( - substr($this->rdata, $offset - $packet->offset) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->next_domain_name) > 0) { - $data = $packet->compress($this->next_domain_name, $packet->offset); - $bitmap = Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); - - $packet->offset += strlen($bitmap); - - return $data.$bitmap; - } - - return null; - } +class Net_DNS2_RR_NSEC extends Net_DNS2_RR { + // The next owner name + public $next_domain_name; + + // identifies the RRset types that exist at the NSEC RR's owner name. + public $type_bit_maps = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $data = $this->cleanString($this->next_domain_name) . '.'; + + foreach ($this->type_bit_maps as $rr) { + $data .= ' ' . $rr; + } + + return $data; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->next_domain_name = $this->cleanString(array_shift($rdata)); + $this->type_bit_maps = $rdata; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // expand the next domain name + // + $offset = $packet->offset; + $this->next_domain_name = Net_DNS2_Packet::expand($packet, $offset); + + // + // parse out the RR's from the bitmap + // + $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( + substr($this->rdata, $offset - $packet->offset) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->next_domain_name) > 0) { + $data = $packet->compress($this->next_domain_name, $packet->offset); + $bitmap = Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); + + $packet->offset += strlen($bitmap); + + return $data . $bitmap; + } + + return null; + } } diff --git a/Net/DNS2/RR/NSEC3.php b/Net/DNS2/RR/NSEC3.php index f8385b3a..7897e09b 100644 --- a/Net/DNS2/RR/NSEC3.php +++ b/Net/DNS2/RR/NSEC3.php @@ -31,201 +31,199 @@ * / Type Bit Maps / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_NSEC3 extends Net_DNS2_RR -{ - // Algorithm to use - public $algorithm; - - // flags - public $flags; - - // defines the number of additional times the hash is performed. - public $iterations; - - // the length of the salt- not displayed - public $salt_length; - - // the salt - public $salt; - - // the length of the hash value - public $hash_length; - - // the hashed value of the owner name - public $hashed_owner_name; - - // array of RR type names - public $type_bit_maps = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->algorithm.' '.$this->flags.' '.$this->iterations.' '; - - // - // per RFC5155, the salt_length value isn't displayed, and if the salt - // is empty, the salt is displayed as '-' - // - if ($this->salt_length > 0) { - $out .= $this->salt; - } else { - $out .= '-'; - } - - // - // per RFC5255 the hash length isn't shown - // - $out .= ' '.$this->hashed_owner_name; - - // - // show the RR's - // - foreach ($this->type_bit_maps as $rr) { - $out .= ' '.strtoupper($rr); - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->algorithm = array_shift($rdata); - $this->flags = array_shift($rdata); - $this->iterations = array_shift($rdata); - - // - // an empty salt is represented as '-' per RFC5155 section 3.3 - // - $salt = array_shift($rdata); - if ('-' == $salt) { - $this->salt_length = 0; - $this->salt = ''; - } else { - $this->salt_length = strlen(pack('H*', $salt)); - $this->salt = strtoupper($salt); - } - - $this->hashed_owner_name = array_shift($rdata); - $this->hash_length = strlen(base64_decode($this->hashed_owner_name)); - - $this->type_bit_maps = $rdata; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the first values - // - $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); - - $this->algorithm = $x['algorithm']; - $this->flags = $x['flags']; - $this->iterations = $x['iterations']; - $this->salt_length = $x['salt_length']; - - $offset = 5; - - if ($this->salt_length > 0) { - $x = unpack('H*', substr($this->rdata, $offset, $this->salt_length)); - $this->salt = strtoupper($x[1]); - $offset += $this->salt_length; - } - - // - // unpack the hash length - // - $x = unpack('@'.$offset.'/Chash_length', $this->rdata); - ++$offset; - - // - // copy out the hash - // - $this->hash_length = $x['hash_length']; - if ($this->hash_length > 0) { - $this->hashed_owner_name = base64_encode( - substr($this->rdata, $offset, $this->hash_length) - ); - $offset += $this->hash_length; - } - - // - // parse out the RR bitmap - // - $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( - substr($this->rdata, $offset) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // pull the salt and build the length - // - $salt = pack('H*', $this->salt); - $this->salt_length = strlen($salt); - - // - // pack the algorithm, flags, iterations and salt length - // - $data = pack( - 'CCnC', - $this->algorithm, - $this->flags, - $this->iterations, - $this->salt_length - ); - $data .= $salt; - - // - // add the hash length and hash - // - $data .= chr($this->hash_length); - if ($this->hash_length > 0) { - $data .= base64_decode($this->hashed_owner_name); - } - - // - // conver the array of RR names to a type bitmap - // - $data .= Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_NSEC3 extends Net_DNS2_RR { + // Algorithm to use + public $algorithm; + + // flags + public $flags; + + // defines the number of additional times the hash is performed. + public $iterations; + + // the length of the salt- not displayed + public $salt_length; + + // the salt + public $salt; + + // the length of the hash value + public $hash_length; + + // the hashed value of the owner name + public $hashed_owner_name; + + // array of RR type names + public $type_bit_maps = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->algorithm . ' ' . $this->flags . ' ' . $this->iterations . ' '; + + // + // per RFC5155, the salt_length value isn't displayed, and if the salt + // is empty, the salt is displayed as '-' + // + if ($this->salt_length > 0) { + $out .= $this->salt; + } else { + $out .= '-'; + } + + // + // per RFC5255 the hash length isn't shown + // + $out .= ' ' . $this->hashed_owner_name; + + // + // show the RR's + // + foreach ($this->type_bit_maps as $rr) { + $out .= ' ' . strtoupper($rr); + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->algorithm = array_shift($rdata); + $this->flags = array_shift($rdata); + $this->iterations = array_shift($rdata); + + // + // an empty salt is represented as '-' per RFC5155 section 3.3 + // + $salt = array_shift($rdata); + + if ($salt == '-') { + $this->salt_length = 0; + $this->salt = ''; + } else { + $this->salt_length = strlen(pack('H*', $salt)); + $this->salt = strtoupper($salt); + } + + $this->hashed_owner_name = array_shift($rdata); + $this->hash_length = strlen(base64_decode($this->hashed_owner_name, true)); + + $this->type_bit_maps = $rdata; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the first values + // + $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); + + $this->algorithm = $x['algorithm']; + $this->flags = $x['flags']; + $this->iterations = $x['iterations']; + $this->salt_length = $x['salt_length']; + + $offset = 5; + + if ($this->salt_length > 0) { + $x = unpack('H*', substr($this->rdata, $offset, $this->salt_length)); + $this->salt = strtoupper($x[1]); + $offset += $this->salt_length; + } + + // + // unpack the hash length + // + $x = unpack('@' . $offset . '/Chash_length', $this->rdata); + ++$offset; + + // + // copy out the hash + // + $this->hash_length = $x['hash_length']; + + if ($this->hash_length > 0) { + $this->hashed_owner_name = base64_encode( + substr($this->rdata, $offset, $this->hash_length) + ); + $offset += $this->hash_length; + } + + // + // parse out the RR bitmap + // + $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( + substr($this->rdata, $offset) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + // + // pull the salt and build the length + // + $salt = pack('H*', $this->salt); + $this->salt_length = strlen($salt); + + // + // pack the algorithm, flags, iterations and salt length + // + $data = pack( + 'CCnC', + $this->algorithm, + $this->flags, + $this->iterations, + $this->salt_length + ); + $data .= $salt; + + // + // add the hash length and hash + // + $data .= chr($this->hash_length); + + if ($this->hash_length > 0) { + $data .= base64_decode($this->hashed_owner_name, true); + } + + // + // conver the array of RR names to a type bitmap + // + $data .= Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/NSEC3PARAM.php b/Net/DNS2/RR/NSEC3PARAM.php index 990cb019..21ed2ed8 100644 --- a/Net/DNS2/RR/NSEC3PARAM.php +++ b/Net/DNS2/RR/NSEC3PARAM.php @@ -27,126 +27,122 @@ * | Salt Length | Salt / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_NSEC3PARAM extends Net_DNS2_RR -{ - /* - * Algorithm to use - * - * TODO: same as the NSEC3 - */ - public $algorithm; - - // flags - public $flags; - - // defines the number of additional times the hash is performed. - public $iterations; - - // the length of the salt- not displayed - public $salt_length; - - // the salt - public $salt; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->algorithm.' '.$this->flags.' '.$this->iterations.' '; - - // - // per RFC5155, the salt_length value isn't displayed, and if the salt - // is empty, the salt is displayed as "-" - // - if ($this->salt_length > 0) { - $out .= $this->salt; - } else { - $out .= '-'; - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->algorithm = array_shift($rdata); - $this->flags = array_shift($rdata); - $this->iterations = array_shift($rdata); - - $salt = array_shift($rdata); - if ('-' == $salt) { - $this->salt_length = 0; - $this->salt = ''; - } else { - $this->salt_length = strlen(pack('H*', $salt)); - $this->salt = strtoupper($salt); - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); - - $this->algorithm = $x['algorithm']; - $this->flags = $x['flags']; - $this->iterations = $x['iterations']; - $this->salt_length = $x['salt_length']; - - if ($this->salt_length > 0) { - $x = unpack('H*', substr($this->rdata, 5, $this->salt_length)); - $this->salt = strtoupper($x[1]); - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $salt = pack('H*', $this->salt); - $this->salt_length = strlen($salt); - - $data = pack( - 'CCnC', - $this->algorithm, - $this->flags, - $this->iterations, - $this->salt_length - ).$salt; - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_NSEC3PARAM extends Net_DNS2_RR { + /* + * Algorithm to use + * + * TODO: same as the NSEC3 + */ + public $algorithm; + + // flags + public $flags; + + // defines the number of additional times the hash is performed. + public $iterations; + + // the length of the salt- not displayed + public $salt_length; + + // the salt + public $salt; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->algorithm . ' ' . $this->flags . ' ' . $this->iterations . ' '; + + // + // per RFC5155, the salt_length value isn't displayed, and if the salt + // is empty, the salt is displayed as "-" + // + if ($this->salt_length > 0) { + $out .= $this->salt; + } else { + $out .= '-'; + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->algorithm = array_shift($rdata); + $this->flags = array_shift($rdata); + $this->iterations = array_shift($rdata); + + $salt = array_shift($rdata); + + if ($salt == '-') { + $this->salt_length = 0; + $this->salt = ''; + } else { + $this->salt_length = strlen(pack('H*', $salt)); + $this->salt = strtoupper($salt); + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); + + $this->algorithm = $x['algorithm']; + $this->flags = $x['flags']; + $this->iterations = $x['iterations']; + $this->salt_length = $x['salt_length']; + + if ($this->salt_length > 0) { + $x = unpack('H*', substr($this->rdata, 5, $this->salt_length)); + $this->salt = strtoupper($x[1]); + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $salt = pack('H*', $this->salt); + $this->salt_length = strlen($salt); + + $data = pack( + 'CCnC', + $this->algorithm, + $this->flags, + $this->iterations, + $this->salt_length + ) . $salt; + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/OPENPGPKEY.php b/Net/DNS2/RR/OPENPGPKEY.php index 53ea3645..4c10454e 100644 --- a/Net/DNS2/RR/OPENPGPKEY.php +++ b/Net/DNS2/RR/OPENPGPKEY.php @@ -27,72 +27,67 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_OPENPGPKEY extends Net_DNS2_RR -{ - // the public key - public $key; +class Net_DNS2_RR_OPENPGPKEY extends Net_DNS2_RR { + // the public key + public $key; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->key; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->key; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->key = array_shift($rdata); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->key = array_shift($rdata); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $this->key = base64_encode(substr($this->rdata, 0, $this->rdlength)); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $this->key = base64_encode(substr($this->rdata, 0, $this->rdlength)); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->key) > 0) { - $data = base64_decode($this->key); + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->key) > 0) { + $data = base64_decode($this->key, true); - $packet->offset += strlen($data); + $packet->offset += strlen($data); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/OPT.php b/Net/DNS2/RR/OPT.php index 1d78f89e..bdbaa26d 100644 --- a/Net/DNS2/RR/OPT.php +++ b/Net/DNS2/RR/OPT.php @@ -30,181 +30,174 @@ * / / * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ */ -class Net_DNS2_RR_OPT extends Net_DNS2_RR -{ - // option code - assigned by IANA - public $option_code; - - // the length of the option data - public $option_length; - - // the option data - public $option_data; - - // the extended response code stored in the TTL - public $extended_rcode; - - // the implementation level - public $version; - - // the DO bit used for DNSSEC - RFC3225 - public $do; - - // the extended flags - public $z; - - /** - * Constructor - builds a new Net_DNS2_RR_OPT object; normally you wouldn't call - * this directly, but OPT RR's are a little different. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create - * an empty object - * @param array $rr an array with RR parse values or null to - * create an empty object - * - * @throws Net_DNS2_Exception - */ - public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) - { - // - // this is for when we're manually building an OPT RR object; we aren't - // passing in binary data to parse, we just want a clean/empty object. - // - $this->type = 'OPT'; - $this->rdlength = 0; - - $this->option_length = 0; - $this->extended_rcode = 0; - $this->version = 0; - $this->do = 0; - $this->z = 0; - - // - // everthing else gets passed through to the parent. - // - if ((!is_null($packet)) && (!is_null($rr))) { - parent::__construct($packet, $rr); - } - } - - /** - * method to return the rdata portion of the packet as a string. There is no - * defintion for returning an OPT RR by string- this is just here to validate - * the binary parsing / building routines. - * - * @return string - */ - protected function rrToString() - { - return $this->option_code.' '.$this->option_data; - } - - /** - * parses the rdata portion from a standard DNS config line. There is no - * definition for parsing a OPT RR by string- this is just here to validate - * the binary parsing / building routines. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->option_code = array_shift($rdata); - $this->option_data = array_shift($rdata); - $this->option_length = strlen($this->option_data); - - $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); - - $this->extended_rcode = $x['extended']; - $this->version = $x['version']; - $this->do = ($x['do'] >> 7); - $this->z = $x['z']; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - // - // parse out the TTL value - // - $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); - - $this->extended_rcode = $x['extended']; - $this->version = $x['version']; - $this->do = ($x['do'] >> 7); - $this->z = $x['z']; - - // - // parse the data, if there is any - // - if ($this->rdlength > 0) { - // - // unpack the code and length - // - $x = unpack('noption_code/noption_length', $this->rdata); - - $this->option_code = $x['option_code']; - $this->option_length = $x['option_length']; - - // - // copy out the data based on the length - // - $this->option_data = substr($this->rdata, 4); - } - - return true; - } - - /** - * pre-builds the TTL value for this record; we needed to separate this out - * from the rrGet() function, as the logic in the Net_DNS2_RR packs the TTL - * value before it builds the rdata value. - */ - protected function preBuild() - { - // - // build the TTL value based on the local values - // - $ttl = unpack( - 'N', - pack('CCCC', $this->extended_rcode, $this->version, $this->do << 7, 0) - ); - - $this->ttl = $ttl[1]; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // if there is an option code, then pack that data too - // - if ($this->option_code) { - $data = pack('nn', $this->option_code, $this->option_length) - .$this->option_data; - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_OPT extends Net_DNS2_RR { + // option code - assigned by IANA + public $option_code; + + // the length of the option data + public $option_length; + + // the option data + public $option_data; + + // the extended response code stored in the TTL + public $extended_rcode; + + // the implementation level + public $version; + + // the DO bit used for DNSSEC - RFC3225 + public $do; + + // the extended flags + public $z; + + /** + * Constructor - builds a new Net_DNS2_RR_OPT object; normally you wouldn't call + * this directly, but OPT RR's are a little different. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet or null to create + * an empty object + * @param array $rr an array with RR parse values or null to + * create an empty object + * + * @throws Net_DNS2_Exception + */ + public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) { + // + // this is for when we're manually building an OPT RR object; we aren't + // passing in binary data to parse, we just want a clean/empty object. + // + $this->type = 'OPT'; + $this->rdlength = 0; + + $this->option_length = 0; + $this->extended_rcode = 0; + $this->version = 0; + $this->do = 0; + $this->z = 0; + + // + // everthing else gets passed through to the parent. + // + if ((!is_null($packet)) && (!is_null($rr))) { + parent::__construct($packet, $rr); + } + } + + /** + * method to return the rdata portion of the packet as a string. There is no + * defintion for returning an OPT RR by string- this is just here to validate + * the binary parsing / building routines. + * + * @return string + */ + protected function rrToString() { + return $this->option_code . ' ' . $this->option_data; + } + + /** + * parses the rdata portion from a standard DNS config line. There is no + * definition for parsing a OPT RR by string- this is just here to validate + * the binary parsing / building routines. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->option_code = array_shift($rdata); + $this->option_data = array_shift($rdata); + $this->option_length = strlen($this->option_data); + + $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); + + $this->extended_rcode = $x['extended']; + $this->version = $x['version']; + $this->do = ($x['do'] >> 7); + $this->z = $x['z']; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + // + // parse out the TTL value + // + $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); + + $this->extended_rcode = $x['extended']; + $this->version = $x['version']; + $this->do = ($x['do'] >> 7); + $this->z = $x['z']; + + // + // parse the data, if there is any + // + if ($this->rdlength > 0) { + // + // unpack the code and length + // + $x = unpack('noption_code/noption_length', $this->rdata); + + $this->option_code = $x['option_code']; + $this->option_length = $x['option_length']; + + // + // copy out the data based on the length + // + $this->option_data = substr($this->rdata, 4); + } + + return true; + } + + /** + * pre-builds the TTL value for this record; we needed to separate this out + * from the rrGet() function, as the logic in the Net_DNS2_RR packs the TTL + * value before it builds the rdata value. + */ + protected function preBuild() { + // + // build the TTL value based on the local values + // + $ttl = unpack( + 'N', + pack('CCCC', $this->extended_rcode, $this->version, $this->do << 7, 0) + ); + + $this->ttl = $ttl[1]; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + // + // if there is an option code, then pack that data too + // + if ($this->option_code) { + $data = pack('nn', $this->option_code, $this->option_length) + . $this->option_data; + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/PTR.php b/Net/DNS2/RR/PTR.php index 1771e8d2..16e0ef16 100644 --- a/Net/DNS2/RR/PTR.php +++ b/Net/DNS2/RR/PTR.php @@ -24,69 +24,64 @@ * / PTRDNAME / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_PTR extends Net_DNS2_RR -{ - // the hostname of the PTR entry - public $ptrdname; +class Net_DNS2_RR_PTR extends Net_DNS2_RR { + // the hostname of the PTR entry + public $ptrdname; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return rtrim($this->ptrdname, '.').'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return rtrim($this->ptrdname, '.') . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->ptrdname = rtrim(implode(' ', $rdata), '.'); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->ptrdname = rtrim(implode(' ', $rdata), '.'); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; - $this->ptrdname = Net_DNS2_Packet::expand($packet, $offset); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; + $this->ptrdname = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->ptrdname) > 0) { - return $packet->compress($this->ptrdname, $packet->offset); - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->ptrdname) > 0) { + return $packet->compress($this->ptrdname, $packet->offset); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/PX.php b/Net/DNS2/RR/PX.php index ec3a1850..0a9c5a11 100644 --- a/Net/DNS2/RR/PX.php +++ b/Net/DNS2/RR/PX.php @@ -30,92 +30,87 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ -class Net_DNS2_RR_PX extends Net_DNS2_RR -{ - // preference - public $preference; - - // the RFC822 part of the MCGAM - public $map822; - - // the X.400 part of the MCGAM - public $mapx400; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' '.$this->cleanString($this->map822).'. ' - .$this->cleanString($this->mapx400).'.'; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = $rdata[0]; - $this->map822 = $this->cleanString($rdata[1]); - $this->mapx400 = $this->cleanString($rdata[2]); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse the preference - // - $x = unpack('npreference', $this->rdata); - $this->preference = $x['preference']; - - $offset = $packet->offset + 2; - - $this->map822 = Net_DNS2_Packet::expand($packet, $offset); - $this->mapx400 = Net_DNS2_Packet::expand($packet, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->map822) > 0) { - $data = pack('n', $this->preference); - $packet->offset += 2; - - $data .= $packet->compress($this->map822, $packet->offset); - $data .= $packet->compress($this->mapx400, $packet->offset); - - return $data; - } - - return null; - } +class Net_DNS2_RR_PX extends Net_DNS2_RR { + // preference + public $preference; + + // the RFC822 part of the MCGAM + public $map822; + + // the X.400 part of the MCGAM + public $mapx400; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' . $this->cleanString($this->map822) . '. ' + . $this->cleanString($this->mapx400) . '.'; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = $rdata[0]; + $this->map822 = $this->cleanString($rdata[1]); + $this->mapx400 = $this->cleanString($rdata[2]); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse the preference + // + $x = unpack('npreference', $this->rdata); + $this->preference = $x['preference']; + + $offset = $packet->offset + 2; + + $this->map822 = Net_DNS2_Packet::expand($packet, $offset); + $this->mapx400 = Net_DNS2_Packet::expand($packet, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->map822) > 0) { + $data = pack('n', $this->preference); + $packet->offset += 2; + + $data .= $packet->compress($this->map822, $packet->offset); + $data .= $packet->compress($this->mapx400, $packet->offset); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/RP.php b/Net/DNS2/RR/RP.php index a15dc2ea..c3b41eac 100644 --- a/Net/DNS2/RR/RP.php +++ b/Net/DNS2/RR/RP.php @@ -28,76 +28,71 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_RP extends Net_DNS2_RR -{ - // mailbox for the responsible person - public $mboxdname; +class Net_DNS2_RR_RP extends Net_DNS2_RR { + // mailbox for the responsible person + public $mboxdname; - // is a domain name for which TXT RR's exists - public $txtdname; + // is a domain name for which TXT RR's exists + public $txtdname; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->mboxdname).'. '.$this->cleanString($this->txtdname).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->mboxdname) . '. ' . $this->cleanString($this->txtdname) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->mboxdname = $this->cleanString($rdata[0]); - $this->txtdname = $this->cleanString($rdata[1]); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->mboxdname = $this->cleanString($rdata[0]); + $this->txtdname = $this->cleanString($rdata[1]); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; - $this->mboxdname = Net_DNS2_Packet::expand($packet, $offset, true); - $this->txtdname = Net_DNS2_Packet::expand($packet, $offset); + $this->mboxdname = Net_DNS2_Packet::expand($packet, $offset, true); + $this->txtdname = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->mboxdname) > 0) { - return $packet->compress($this->mboxdname, $packet->offset) - .$packet->compress($this->txtdname, $packet->offset); - } + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->mboxdname) > 0) { + return $packet->compress($this->mboxdname, $packet->offset) + . $packet->compress($this->txtdname, $packet->offset); + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/RRSIG.php b/Net/DNS2/RR/RRSIG.php index f13cd897..0fbe22d0 100644 --- a/Net/DNS2/RR/RRSIG.php +++ b/Net/DNS2/RR/RRSIG.php @@ -64,190 +64,186 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_RRSIG extends Net_DNS2_RR -{ - // the RR type covered by this signature - public $typecovered; - - // the algorithm used for the signature - public $algorithm; - - // the number of labels in the name - public $labels; - - // the original TTL - public $origttl; - - // the signature expiration - public $sigexp; - - // the inception of the signature - public $sigincep; - - // the keytag used - public $keytag; - - // the signer's name - public $signname; - - // the signature - public $signature; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->typecovered.' '.$this->algorithm.' ' - .$this->labels.' '.$this->origttl.' ' - .$this->sigexp.' '.$this->sigincep.' ' - .$this->keytag.' '.$this->cleanString($this->signname).'. ' - .$this->signature; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->typecovered = strtoupper(array_shift($rdata)); - $this->algorithm = array_shift($rdata); - $this->labels = array_shift($rdata); - $this->origttl = array_shift($rdata); - $this->sigexp = array_shift($rdata); - $this->sigincep = array_shift($rdata); - $this->keytag = array_shift($rdata); - $this->signname = $this->cleanString(array_shift($rdata)); - - foreach ($rdata as $line) { - $this->signature .= $line; - } - - $this->signature = trim($this->signature); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack - // - $x = unpack( - 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', - $this->rdata - ); - - $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; - $this->algorithm = $x['algorithm']; - $this->labels = $x['labels']; - $this->origttl = Net_DNS2::expandUint32($x['origttl']); - - // - // the dates are in GM time - // - $this->sigexp = gmdate('YmdHis', $x['sigexp']); - $this->sigincep = gmdate('YmdHis', $x['sigincep']); - - // - // get the keytag - // - $this->keytag = $x['keytag']; - - // - // get teh signers name and signature - // - $offset = $packet->offset + 18; - $sigoffset = $offset; - - $this->signname = strtolower( - Net_DNS2_Packet::expand($packet, $sigoffset) - ); - $this->signature = base64_encode( - substr($this->rdata, 18 + ($sigoffset - $offset)) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->signature) > 0) { - // - // parse the values out of the dates - // - preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', - $this->sigexp, - $e - ); - preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', - $this->sigincep, - $i - ); - - // - // pack the value - // - $data = pack( - 'nCCNNNn', - Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], - $this->algorithm, - $this->labels, - $this->origttl, - gmmktime($e[4], $e[5], $e[6], $e[2], $e[3], $e[1]), - gmmktime($i[4], $i[5], $i[6], $i[2], $i[3], $i[1]), - $this->keytag - ); - - // - // the signer name is special; it's not allowed to be compressed - // (see section 3.1.7) - // - $names = explode('.', strtolower($this->signname)); - foreach ($names as $name) { - $data .= chr(strlen($name)); - $data .= $name; - } - $data .= "\0"; - - // - // add the signature - // - $data .= base64_decode($this->signature); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_RRSIG extends Net_DNS2_RR { + // the RR type covered by this signature + public $typecovered; + + // the algorithm used for the signature + public $algorithm; + + // the number of labels in the name + public $labels; + + // the original TTL + public $origttl; + + // the signature expiration + public $sigexp; + + // the inception of the signature + public $sigincep; + + // the keytag used + public $keytag; + + // the signer's name + public $signname; + + // the signature + public $signature; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->typecovered . ' ' . $this->algorithm . ' ' + . $this->labels . ' ' . $this->origttl . ' ' + . $this->sigexp . ' ' . $this->sigincep . ' ' + . $this->keytag . ' ' . $this->cleanString($this->signname) . '. ' + . $this->signature; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->typecovered = strtoupper(array_shift($rdata)); + $this->algorithm = array_shift($rdata); + $this->labels = array_shift($rdata); + $this->origttl = array_shift($rdata); + $this->sigexp = array_shift($rdata); + $this->sigincep = array_shift($rdata); + $this->keytag = array_shift($rdata); + $this->signname = $this->cleanString(array_shift($rdata)); + + foreach ($rdata as $line) { + $this->signature .= $line; + } + + $this->signature = trim($this->signature); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack + // + $x = unpack( + 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', + $this->rdata + ); + + $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; + $this->algorithm = $x['algorithm']; + $this->labels = $x['labels']; + $this->origttl = Net_DNS2::expandUint32($x['origttl']); + + // + // the dates are in GM time + // + $this->sigexp = gmdate('YmdHis', $x['sigexp']); + $this->sigincep = gmdate('YmdHis', $x['sigincep']); + + // + // get the keytag + // + $this->keytag = $x['keytag']; + + // + // get teh signers name and signature + // + $offset = $packet->offset + 18; + $sigoffset = $offset; + + $this->signname = strtolower( + Net_DNS2_Packet::expand($packet, $sigoffset) + ); + $this->signature = base64_encode( + substr($this->rdata, 18 + ($sigoffset - $offset)) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->signature) > 0) { + // + // parse the values out of the dates + // + preg_match( + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigexp, + $e + ); + preg_match( + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigincep, + $i + ); + + // + // pack the value + // + $data = pack( + 'nCCNNNn', + Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], + $this->algorithm, + $this->labels, + $this->origttl, + gmmktime($e[4], $e[5], $e[6], $e[2], $e[3], $e[1]), + gmmktime($i[4], $i[5], $i[6], $i[2], $i[3], $i[1]), + $this->keytag + ); + + // + // the signer name is special; it's not allowed to be compressed + // (see section 3.1.7) + // + $names = explode('.', strtolower($this->signname)); + + foreach ($names as $name) { + $data .= chr(strlen($name)); + $data .= $name; + } + $data .= "\0"; + + // + // add the signature + // + $data .= base64_decode($this->signature, true); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/RT.php b/Net/DNS2/RR/RT.php index 7b41eb52..1b24ef64 100644 --- a/Net/DNS2/RR/RT.php +++ b/Net/DNS2/RR/RT.php @@ -27,86 +27,81 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_RT extends Net_DNS2_RR -{ - // the preference of this route - public $preference; +class Net_DNS2_RR_RT extends Net_DNS2_RR { + // the preference of this route + public $preference; - // host which will servce as an intermediate in reaching the owner host - public $intermediatehost; + // host which will servce as an intermediate in reaching the owner host + public $intermediatehost; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->preference.' ' - .$this->cleanString($this->intermediatehost).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->preference . ' ' + . $this->cleanString($this->intermediatehost) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->preference = $rdata[0]; - $this->intermediatehost = $this->cleanString($rdata[1]); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->preference = $rdata[0]; + $this->intermediatehost = $this->cleanString($rdata[1]); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the preference - // - $x = unpack('npreference', $this->rdata); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the preference + // + $x = unpack('npreference', $this->rdata); - $this->preference = $x['preference']; - $offset = $packet->offset + 2; + $this->preference = $x['preference']; + $offset = $packet->offset + 2; - $this->intermediatehost = Net_DNS2_Packet::expand($packet, $offset); + $this->intermediatehost = Net_DNS2_Packet::expand($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->intermediatehost) > 0) { - $data = pack('n', $this->preference); - $packet->offset += 2; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->intermediatehost) > 0) { + $data = pack('n', $this->preference); + $packet->offset += 2; - $data .= $packet->compress($this->intermediatehost, $packet->offset); + $data .= $packet->compress($this->intermediatehost, $packet->offset); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/SIG.php b/Net/DNS2/RR/SIG.php index 58b2dc74..584e2a56 100644 --- a/Net/DNS2/RR/SIG.php +++ b/Net/DNS2/RR/SIG.php @@ -64,314 +64,306 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_SIG extends Net_DNS2_RR -{ - // and instance of a Net_DNS2_PrivateKey object - public $private_key; - - // the RR type covered by this signature - public $typecovered; - - // the algorithm used for the signature - public $algorithm; - - // the number of labels in the name - public $labels; - - // the original TTL - public $origttl; - - // the signature expiration - public $sigexp; - - // the inception of the signature - public $sigincep; - - // the keytag used - public $keytag; - - // the signer's name - public $signname; - - // the signature - public $signature; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->typecovered.' '.$this->algorithm.' ' - .$this->labels.' '.$this->origttl.' ' - .$this->sigexp.' '.$this->sigincep.' ' - .$this->keytag.' '.$this->cleanString($this->signname).'. ' - .$this->signature; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->typecovered = strtoupper(array_shift($rdata)); - $this->algorithm = array_shift($rdata); - $this->labels = array_shift($rdata); - $this->origttl = array_shift($rdata); - $this->sigexp = array_shift($rdata); - $this->sigincep = array_shift($rdata); - $this->keytag = array_shift($rdata); - $this->signname = $this->cleanString(array_shift($rdata)); - - foreach ($rdata as $line) { - $this->signature .= $line; - } - - $this->signature = trim($this->signature); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack - // - $x = unpack( - 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', - $this->rdata - ); - - $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; - $this->algorithm = $x['algorithm']; - $this->labels = $x['labels']; - $this->origttl = Net_DNS2::expandUint32($x['origttl']); - - // - // the dates are in GM time - // - $this->sigexp = gmdate('YmdHis', $x['sigexp']); - $this->sigincep = gmdate('YmdHis', $x['sigincep']); - - // - // get the keytag - // - $this->keytag = $x['keytag']; - - // - // get teh signers name and signature - // - $offset = $packet->offset + 18; - $sigoffset = $offset; - - $this->signname = strtolower( - Net_DNS2_Packet::expand($packet, $sigoffset) - ); - $this->signature = base64_encode( - substr($this->rdata, 18 + ($sigoffset - $offset)) - ); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - // - // parse the values out of the dates - // - preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', - $this->sigexp, - $e - ); - preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', - $this->sigincep, - $i - ); - - // - // pack the value - // - $data = pack( - 'nCCNNNn', - Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], - $this->algorithm, - $this->labels, - $this->origttl, - gmmktime($e[4], $e[5], $e[6], $e[2], $e[3], $e[1]), - gmmktime($i[4], $i[5], $i[6], $i[2], $i[3], $i[1]), - $this->keytag - ); - - // - // the signer name is special; it's not allowed to be compressed - // (see section 3.1.7) - // - $names = explode('.', strtolower($this->signname)); - foreach ($names as $name) { - $data .= chr(strlen($name)); - $data .= $name; - } - - $data .= chr('0'); - - // - // if the signature is empty, and $this->private_key is an instance of a - // private key object, and we have access to openssl, then assume this - // is a SIG(0), and generate a new signature - // - if ((0 == strlen($this->signature)) - && ($this->private_key instanceof Net_DNS2_PrivateKey) - && (true === extension_loaded('openssl')) - ) { - // - // create a new packet for the signature- - // - $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); - - // - // copy the packet data over - // - $new_packet->copy($packet); - - // - // remove the SIG object from the additional list - // - array_pop($new_packet->additional); - $new_packet->header->arcount = cacti_sizeof($new_packet->additional); - - // - // copy out the data - // - $sigdata = $data.$new_packet->get(); - - // - // based on the algorithm - // - $algorithm = 0; - - switch ($this->algorithm) { - // - // MD5 - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - $algorithm = OPENSSL_ALGO_MD5; - - break; - - // - // SHA1 - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - $algorithm = OPENSSL_ALGO_SHA1; - - break; - - // - // SHA256 (PHP 5.4.8 or higher) - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - if (true == version_compare(PHP_VERSION, '5.4.8', '<')) { - throw new Net_DNS2_Exception( - 'SHA256 support is only available in PHP >= 5.4.8', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - $algorithm = OPENSSL_ALGO_SHA256; - - break; - - // - // SHA512 (PHP 5.4.8 or higher) - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - if (true == version_compare(PHP_VERSION, '5.4.8', '<')) { - throw new Net_DNS2_Exception( - 'SHA512 support is only available in PHP >= 5.4.8', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - } - - $algorithm = OPENSSL_ALGO_SHA512; - - break; - - // - // unsupported at the moment - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: - case Net_DNS2_Lookups::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSANSEC3SHA1: - default: - throw new Net_DNS2_Exception( - 'invalid or unsupported algorithm', - Net_DNS2_Lookups::E_OPENSSL_INV_ALGO - ); - - break; - } - - // - // sign the data - // - if (false == openssl_sign($sigdata, $this->signature, $this->private_key->instance, $algorithm)) { - throw new Net_DNS2_Exception( - openssl_error_string(), - Net_DNS2_Lookups::E_OPENSSL_ERROR - ); - } - - // - // build the signature value based - // - switch ($this->algorithm) { - // - // RSA- add it directly - // - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: - case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - $this->signature = base64_encode($this->signature); - - break; - } - } - - // - // add the signature - // - $data .= base64_decode($this->signature); - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_SIG extends Net_DNS2_RR { + // and instance of a Net_DNS2_PrivateKey object + public $private_key; + + // the RR type covered by this signature + public $typecovered; + + // the algorithm used for the signature + public $algorithm; + + // the number of labels in the name + public $labels; + + // the original TTL + public $origttl; + + // the signature expiration + public $sigexp; + + // the inception of the signature + public $sigincep; + + // the keytag used + public $keytag; + + // the signer's name + public $signname; + + // the signature + public $signature; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->typecovered . ' ' . $this->algorithm . ' ' + . $this->labels . ' ' . $this->origttl . ' ' + . $this->sigexp . ' ' . $this->sigincep . ' ' + . $this->keytag . ' ' . $this->cleanString($this->signname) . '. ' + . $this->signature; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->typecovered = strtoupper(array_shift($rdata)); + $this->algorithm = array_shift($rdata); + $this->labels = array_shift($rdata); + $this->origttl = array_shift($rdata); + $this->sigexp = array_shift($rdata); + $this->sigincep = array_shift($rdata); + $this->keytag = array_shift($rdata); + $this->signname = $this->cleanString(array_shift($rdata)); + + foreach ($rdata as $line) { + $this->signature .= $line; + } + + $this->signature = trim($this->signature); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack + // + $x = unpack( + 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', + $this->rdata + ); + + $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; + $this->algorithm = $x['algorithm']; + $this->labels = $x['labels']; + $this->origttl = Net_DNS2::expandUint32($x['origttl']); + + // + // the dates are in GM time + // + $this->sigexp = gmdate('YmdHis', $x['sigexp']); + $this->sigincep = gmdate('YmdHis', $x['sigincep']); + + // + // get the keytag + // + $this->keytag = $x['keytag']; + + // + // get teh signers name and signature + // + $offset = $packet->offset + 18; + $sigoffset = $offset; + + $this->signname = strtolower( + Net_DNS2_Packet::expand($packet, $sigoffset) + ); + $this->signature = base64_encode( + substr($this->rdata, 18 + ($sigoffset - $offset)) + ); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + // + // parse the values out of the dates + // + preg_match( + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigexp, + $e + ); + preg_match( + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', + $this->sigincep, + $i + ); + + // + // pack the value + // + $data = pack( + 'nCCNNNn', + Net_DNS2_Lookups::$rr_types_by_name[$this->typecovered], + $this->algorithm, + $this->labels, + $this->origttl, + gmmktime($e[4], $e[5], $e[6], $e[2], $e[3], $e[1]), + gmmktime($i[4], $i[5], $i[6], $i[2], $i[3], $i[1]), + $this->keytag + ); + + // + // the signer name is special; it's not allowed to be compressed + // (see section 3.1.7) + // + $names = explode('.', strtolower($this->signname)); + + foreach ($names as $name) { + $data .= chr(strlen($name)); + $data .= $name; + } + + $data .= chr('0'); + + // + // if the signature is empty, and $this->private_key is an instance of a + // private key object, and we have access to openssl, then assume this + // is a SIG(0), and generate a new signature + // + if ((strlen($this->signature) == 0) + && ($this->private_key instanceof Net_DNS2_PrivateKey) + && (extension_loaded('openssl') === true) + ) { + // + // create a new packet for the signature- + // + $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); + + // + // copy the packet data over + // + $new_packet->copy($packet); + + // + // remove the SIG object from the additional list + // + array_pop($new_packet->additional); + $new_packet->header->arcount = cacti_sizeof($new_packet->additional); + + // + // copy out the data + // + $sigdata = $data . $new_packet->get(); + + // + // based on the algorithm + // + $algorithm = 0; + + switch ($this->algorithm) { + // + // MD5 + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + $algorithm = OPENSSL_ALGO_MD5; + + break; + // + // SHA1 + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + $algorithm = OPENSSL_ALGO_SHA1; + + break; + // + // SHA256 (PHP 5.4.8 or higher) + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + if (version_compare(PHP_VERSION, '5.4.8', '<') == true) { + throw new Net_DNS2_Exception( + 'SHA256 support is only available in PHP >= 5.4.8', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + $algorithm = OPENSSL_ALGO_SHA256; + + break; + // + // SHA512 (PHP 5.4.8 or higher) + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + if (version_compare(PHP_VERSION, '5.4.8', '<') == true) { + throw new Net_DNS2_Exception( + 'SHA512 support is only available in PHP >= 5.4.8', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + } + + $algorithm = OPENSSL_ALGO_SHA512; + + break; + // + // unsupported at the moment + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA: + case Net_DNS2_Lookups::DSNSEC_ALGORITHM_RSASHA1NSEC3SHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSANSEC3SHA1: + default: + throw new Net_DNS2_Exception( + 'invalid or unsupported algorithm', + Net_DNS2_Lookups::E_OPENSSL_INV_ALGO + ); + + break; + } + + // + // sign the data + // + if (openssl_sign($sigdata, $this->signature, $this->private_key->instance, $algorithm) == false) { + throw new Net_DNS2_Exception( + openssl_error_string(), + Net_DNS2_Lookups::E_OPENSSL_ERROR + ); + } + + // + // build the signature value based + // + switch ($this->algorithm) { + // + // RSA- add it directly + // + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: + case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: + $this->signature = base64_encode($this->signature); + + break; + } + } + + // + // add the signature + // + $data .= base64_decode($this->signature, true); + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/SMIMEA.php b/Net/DNS2/RR/SMIMEA.php index e4a55dd9..4faf366d 100644 --- a/Net/DNS2/RR/SMIMEA.php +++ b/Net/DNS2/RR/SMIMEA.php @@ -21,4 +21,5 @@ * The SMIMEA RR is implemented exactly like the TLSA record, so * for now we just extend the TLSA RR and use it. */ -class Net_DNS2_RR_SMIMEA extends Net_DNS2_RR_TLSA {} +class Net_DNS2_RR_SMIMEA extends Net_DNS2_RR_TLSA { +} diff --git a/Net/DNS2/RR/SOA.php b/Net/DNS2/RR/SOA.php index 664ab320..18be418a 100644 --- a/Net/DNS2/RR/SOA.php +++ b/Net/DNS2/RR/SOA.php @@ -42,130 +42,125 @@ * | | * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_SOA extends Net_DNS2_RR -{ - // The master DNS server - public $mname; - - // mailbox of the responsible person - public $rname; - - // serial number - public $serial; - - // refresh time - public $refresh; - - // retry interval - public $retry; - - // expire time - public $expire; - - // minimum TTL for any RR in this zone - public $minimum; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->mname).'. ' - .$this->cleanString($this->rname).'. ' - .$this->serial.' '.$this->refresh.' '.$this->retry.' ' - .$this->expire.' '.$this->minimum; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->mname = $this->cleanString($rdata[0]); - $this->rname = $this->cleanString($rdata[1]); - - $this->serial = $rdata[2]; - $this->refresh = $rdata[3]; - $this->retry = $rdata[4]; - $this->expire = $rdata[5]; - $this->minimum = $rdata[6]; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // parse the - // - $offset = $packet->offset; - - $this->mname = Net_DNS2_Packet::expand($packet, $offset); - $this->rname = Net_DNS2_Packet::expand($packet, $offset, true); - - // - // get the SOA values - // - $x = unpack( - '@'.$offset.'/Nserial/Nrefresh/Nretry/Nexpire/Nminimum/', - $packet->rdata - ); - - $this->serial = Net_DNS2::expandUint32($x['serial']); - $this->refresh = Net_DNS2::expandUint32($x['refresh']); - $this->retry = Net_DNS2::expandUint32($x['retry']); - $this->expire = Net_DNS2::expandUint32($x['expire']); - $this->minimum = Net_DNS2::expandUint32($x['minimum']); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->mname) > 0) { - $data = $packet->compress($this->mname, $packet->offset); - $data .= $packet->compress($this->rname, $packet->offset); - - $data .= pack( - 'N5', - $this->serial, - $this->refresh, - $this->retry, - $this->expire, - $this->minimum - ); - - $packet->offset += 20; - - return $data; - } - - return null; - } +class Net_DNS2_RR_SOA extends Net_DNS2_RR { + // The master DNS server + public $mname; + + // mailbox of the responsible person + public $rname; + + // serial number + public $serial; + + // refresh time + public $refresh; + + // retry interval + public $retry; + + // expire time + public $expire; + + // minimum TTL for any RR in this zone + public $minimum; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->mname) . '. ' + . $this->cleanString($this->rname) . '. ' + . $this->serial . ' ' . $this->refresh . ' ' . $this->retry . ' ' + . $this->expire . ' ' . $this->minimum; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->mname = $this->cleanString($rdata[0]); + $this->rname = $this->cleanString($rdata[1]); + + $this->serial = $rdata[2]; + $this->refresh = $rdata[3]; + $this->retry = $rdata[4]; + $this->expire = $rdata[5]; + $this->minimum = $rdata[6]; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // parse the + // + $offset = $packet->offset; + + $this->mname = Net_DNS2_Packet::expand($packet, $offset); + $this->rname = Net_DNS2_Packet::expand($packet, $offset, true); + + // + // get the SOA values + // + $x = unpack( + '@' . $offset . '/Nserial/Nrefresh/Nretry/Nexpire/Nminimum/', + $packet->rdata + ); + + $this->serial = Net_DNS2::expandUint32($x['serial']); + $this->refresh = Net_DNS2::expandUint32($x['refresh']); + $this->retry = Net_DNS2::expandUint32($x['retry']); + $this->expire = Net_DNS2::expandUint32($x['expire']); + $this->minimum = Net_DNS2::expandUint32($x['minimum']); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->mname) > 0) { + $data = $packet->compress($this->mname, $packet->offset); + $data .= $packet->compress($this->rname, $packet->offset); + + $data .= pack( + 'N5', + $this->serial, + $this->refresh, + $this->retry, + $this->expire, + $this->minimum + ); + + $packet->offset += 20; + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/SPF.php b/Net/DNS2/RR/SPF.php index dce2ecbb..9c4b9f82 100644 --- a/Net/DNS2/RR/SPF.php +++ b/Net/DNS2/RR/SPF.php @@ -21,4 +21,5 @@ * The SPF RR is implemented exactly like the TXT record, so * for now we just extend the TXT RR and use it. */ -class Net_DNS2_RR_SPF extends Net_DNS2_RR_TXT {} +class Net_DNS2_RR_SPF extends Net_DNS2_RR_TXT { +} diff --git a/Net/DNS2/RR/SRV.php b/Net/DNS2/RR/SRV.php index b9f78d10..387f1e67 100644 --- a/Net/DNS2/RR/SRV.php +++ b/Net/DNS2/RR/SRV.php @@ -30,97 +30,92 @@ * / TARGET / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_SRV extends Net_DNS2_RR -{ - // The priority of this target host. - public $priority; - - // a relative weight for entries with the same priority - public $weight; - - // The port on this target host of this service. - public $port; - - // The domain name of the target host - public $target; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->priority.' '.$this->weight.' ' - .$this->port.' '.$this->cleanString($this->target).'.'; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->priority = $rdata[0]; - $this->weight = $rdata[1]; - $this->port = $rdata[2]; - - $this->target = $this->cleanString($rdata[3]); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the priority, weight and port - // - $x = unpack('npriority/nweight/nport', $this->rdata); - - $this->priority = $x['priority']; - $this->weight = $x['weight']; - $this->port = $x['port']; - - $offset = $packet->offset + 6; - $this->target = Net_DNS2_Packet::expand($packet, $offset); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->target) > 0) { - $data = pack('nnn', $this->priority, $this->weight, $this->port); - $packet->offset += 6; - - $data .= $packet->compress($this->target, $packet->offset); - - return $data; - } - - return null; - } +class Net_DNS2_RR_SRV extends Net_DNS2_RR { + // The priority of this target host. + public $priority; + + // a relative weight for entries with the same priority + public $weight; + + // The port on this target host of this service. + public $port; + + // The domain name of the target host + public $target; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->priority . ' ' . $this->weight . ' ' + . $this->port . ' ' . $this->cleanString($this->target) . '.'; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->priority = $rdata[0]; + $this->weight = $rdata[1]; + $this->port = $rdata[2]; + + $this->target = $this->cleanString($rdata[3]); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the priority, weight and port + // + $x = unpack('npriority/nweight/nport', $this->rdata); + + $this->priority = $x['priority']; + $this->weight = $x['weight']; + $this->port = $x['port']; + + $offset = $packet->offset + 6; + $this->target = Net_DNS2_Packet::expand($packet, $offset); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->target) > 0) { + $data = pack('nnn', $this->priority, $this->weight, $this->port); + $packet->offset += 6; + + $data .= $packet->compress($this->target, $packet->offset); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/SSHFP.php b/Net/DNS2/RR/SSHFP.php index f4e019ad..2a9426cf 100644 --- a/Net/DNS2/RR/SSHFP.php +++ b/Net/DNS2/RR/SSHFP.php @@ -29,157 +29,152 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_SSHFP extends Net_DNS2_RR -{ - // Algorithms - public const SSHFP_ALGORITHM_RES = 0; - public const SSHFP_ALGORITHM_RSA = 1; - public const SSHFP_ALGORITHM_DSS = 2; - public const SSHFP_ALGORITHM_ECDSA = 3; - public const SSHFP_ALGORITHM_ED25519 = 4; - - // Fingerprint Types - public const SSHFP_FPTYPE_RES = 0; - public const SSHFP_FPTYPE_SHA1 = 1; - public const SSHFP_FPTYPE_SHA256 = 2; - // the algorithm used - public $algorithm; - - // The finger print type - public $fp_type; - - // the finger print data - public $fingerprint; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->algorithm.' '.$this->fp_type.' '.$this->fingerprint; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // "The use of mnemonics instead of numbers is not allowed." - // - // RFC4255 section 3.2 - // - $algorithm = array_shift($rdata); - $fp_type = array_shift($rdata); - $fingerprint = strtolower(implode('', $rdata)); - - // - // There are only two algorithm's defined - // - if ((self::SSHFP_ALGORITHM_RSA != $algorithm) - && (self::SSHFP_ALGORITHM_DSS != $algorithm) - && (self::SSHFP_ALGORITHM_ECDSA != $algorithm) - && (self::SSHFP_ALGORITHM_ED25519 != $algorithm) - ) { - return false; - } - - // - // there are only two fingerprints defined - // - if ((self::SSHFP_FPTYPE_SHA1 != $fp_type) - && (self::SSHFP_FPTYPE_SHA256 != $fp_type) - ) { - return false; - } - - $this->algorithm = $algorithm; - $this->fp_type = $fp_type; - $this->fingerprint = $fingerprint; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the algorithm and finger print type - // - $x = unpack('Calgorithm/Cfp_type', $this->rdata); - - $this->algorithm = $x['algorithm']; - $this->fp_type = $x['fp_type']; - - // - // There are only three algorithm's defined - // - if ((self::SSHFP_ALGORITHM_RSA != $this->algorithm) - && (self::SSHFP_ALGORITHM_DSS != $this->algorithm) - && (self::SSHFP_ALGORITHM_ECDSA != $this->algorithm) - && (self::SSHFP_ALGORITHM_ED25519 != $this->algorithm) - ) { - return false; - } - - // - // there are only two fingerprints defined - // - if ((self::SSHFP_FPTYPE_SHA1 != $this->fp_type) - && (self::SSHFP_FPTYPE_SHA256 != $this->fp_type) - ) { - return false; - } - - // - // parse the finger print; this assumes SHA-1 - // - $fp = unpack('H*a', substr($this->rdata, 2)); - $this->fingerprint = strtolower($fp['a']); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->fingerprint) > 0) { - $data = pack( - 'CCH*', - $this->algorithm, - $this->fp_type, - $this->fingerprint - ); - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_SSHFP extends Net_DNS2_RR { + // Algorithms + public const SSHFP_ALGORITHM_RES = 0; + public const SSHFP_ALGORITHM_RSA = 1; + public const SSHFP_ALGORITHM_DSS = 2; + public const SSHFP_ALGORITHM_ECDSA = 3; + public const SSHFP_ALGORITHM_ED25519 = 4; + + // Fingerprint Types + public const SSHFP_FPTYPE_RES = 0; + public const SSHFP_FPTYPE_SHA1 = 1; + public const SSHFP_FPTYPE_SHA256 = 2; + // the algorithm used + public $algorithm; + + // The finger print type + public $fp_type; + + // the finger print data + public $fingerprint; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->algorithm . ' ' . $this->fp_type . ' ' . $this->fingerprint; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // "The use of mnemonics instead of numbers is not allowed." + // + // RFC4255 section 3.2 + // + $algorithm = array_shift($rdata); + $fp_type = array_shift($rdata); + $fingerprint = strtolower(implode('', $rdata)); + + // + // There are only two algorithm's defined + // + if (($algorithm != self::SSHFP_ALGORITHM_RSA) + && ($algorithm != self::SSHFP_ALGORITHM_DSS) + && ($algorithm != self::SSHFP_ALGORITHM_ECDSA) + && ($algorithm != self::SSHFP_ALGORITHM_ED25519) + ) { + return false; + } + + // + // there are only two fingerprints defined + // + if (($fp_type != self::SSHFP_FPTYPE_SHA1) + && ($fp_type != self::SSHFP_FPTYPE_SHA256) + ) { + return false; + } + + $this->algorithm = $algorithm; + $this->fp_type = $fp_type; + $this->fingerprint = $fingerprint; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the algorithm and finger print type + // + $x = unpack('Calgorithm/Cfp_type', $this->rdata); + + $this->algorithm = $x['algorithm']; + $this->fp_type = $x['fp_type']; + + // + // There are only three algorithm's defined + // + if (($this->algorithm != self::SSHFP_ALGORITHM_RSA) + && ($this->algorithm != self::SSHFP_ALGORITHM_DSS) + && ($this->algorithm != self::SSHFP_ALGORITHM_ECDSA) + && ($this->algorithm != self::SSHFP_ALGORITHM_ED25519) + ) { + return false; + } + + // + // there are only two fingerprints defined + // + if (($this->fp_type != self::SSHFP_FPTYPE_SHA1) + && ($this->fp_type != self::SSHFP_FPTYPE_SHA256) + ) { + return false; + } + + // + // parse the finger print; this assumes SHA-1 + // + $fp = unpack('H*a', substr($this->rdata, 2)); + $this->fingerprint = strtolower($fp['a']); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->fingerprint) > 0) { + $data = pack( + 'CCH*', + $this->algorithm, + $this->fp_type, + $this->fingerprint + ); + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/TA.php b/Net/DNS2/RR/TA.php index 4e4a2687..6958f939 100644 --- a/Net/DNS2/RR/TA.php +++ b/Net/DNS2/RR/TA.php @@ -21,4 +21,5 @@ * The TA RR is implemented exactly like the DS record, so * for now we just extend the DS RR and use it. */ -class Net_DNS2_RR_TA extends Net_DNS2_RR_DS {} +class Net_DNS2_RR_TA extends Net_DNS2_RR_DS { +} diff --git a/Net/DNS2/RR/TALINK.php b/Net/DNS2/RR/TALINK.php index 7bbbd4a6..823bb0e8 100644 --- a/Net/DNS2/RR/TALINK.php +++ b/Net/DNS2/RR/TALINK.php @@ -26,81 +26,76 @@ * / NEXT / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_TALINK extends Net_DNS2_RR -{ - // the previous domain name - public $previous; +class Net_DNS2_RR_TALINK extends Net_DNS2_RR { + // the previous domain name + public $previous; - // the next domain name - public $next; + // the next domain name + public $next; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cleanString($this->previous).'. ' - .$this->cleanString($this->next).'.'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cleanString($this->previous) . '. ' + . $this->cleanString($this->next) . '.'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->previous = $this->cleanString($rdata[0]); - $this->next = $this->cleanString($rdata[1]); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->previous = $this->cleanString($rdata[0]); + $this->next = $this->cleanString($rdata[1]); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $offset = $packet->offset; + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $offset = $packet->offset; - $this->previous = Net_DNS2_Packet::label($packet, $offset); - $this->next = Net_DNS2_Packet::label($packet, $offset); + $this->previous = Net_DNS2_Packet::label($packet, $offset); + $this->next = Net_DNS2_Packet::label($packet, $offset); - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if ((strlen($this->previous) > 0) || (strlen($this->next) > 0)) { - $data = chr(strlen($this->previous)).$this->previous - .chr(strlen($this->next)).$this->next; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if ((strlen($this->previous) > 0) || (strlen($this->next) > 0)) { + $data = chr(strlen($this->previous)) . $this->previous + . chr(strlen($this->next)) . $this->next; - $packet->offset += strlen($data); + $packet->offset += strlen($data); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/TKEY.php b/Net/DNS2/RR/TKEY.php index fc317b3e..f7cd1ba1 100644 --- a/Net/DNS2/RR/TKEY.php +++ b/Net/DNS2/RR/TKEY.php @@ -42,201 +42,198 @@ * / OTHER DATA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_TKEY extends Net_DNS2_RR -{ - // TSIG Modes - public const TSIG_MODE_RES = 0; - public const TSIG_MODE_SERV_ASSIGN = 1; - public const TSIG_MODE_DH = 2; - public const TSIG_MODE_GSS_API = 3; - public const TSIG_MODE_RESV_ASSIGN = 4; - public const TSIG_MODE_KEY_DELE = 5; - public $algorithm; - public $inception; - public $expiration; - public $mode; - public $error; - public $key_size; - public $key_data; - public $other_size; - public $other_data; - - // map the mod id's to names so we can validate - public $tsgi_mode_id_to_name = [ - self::TSIG_MODE_RES => 'Reserved', - self::TSIG_MODE_SERV_ASSIGN => 'Server Assignment', - self::TSIG_MODE_DH => 'Diffie-Hellman', - self::TSIG_MODE_GSS_API => 'GSS-API', - self::TSIG_MODE_RESV_ASSIGN => 'Resolver Assignment', - self::TSIG_MODE_KEY_DELE => 'Key Deletion', - ]; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->cleanString($this->algorithm).'. '.$this->mode; - if ($this->key_size > 0) { - $out .= ' '.trim($this->key_data, '.').'.'; - } else { - $out .= ' .'; - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // data passed in is assumed: - // - $this->algorithm = $this->cleanString(array_shift($rdata)); - $this->mode = array_shift($rdata); - $this->key_data = trim(array_shift($rdata), '.'); - - // - // the rest of the data is set manually - // - $this->inception = time(); - $this->expiration = time() + 86400; // 1 day - $this->error = 0; - $this->key_size = strlen($this->key_data); - $this->other_size = 0; - $this->other_data = ''; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // expand the algorithm - // - $offset = $packet->offset; - $this->algorithm = Net_DNS2_Packet::expand($packet, $offset); - - // - // unpack inception, expiration, mode, error and key size - // - $x = unpack( - '@'.$offset.'/Ninception/Nexpiration/nmode/nerror/nkey_size', - $packet->rdata - ); - - $this->inception = Net_DNS2::expandUint32($x['inception']); - $this->expiration = Net_DNS2::expandUint32($x['expiration']); - $this->mode = $x['mode']; - $this->error = $x['error']; - $this->key_size = $x['key_size']; - - $offset += 14; - - // - // if key_size > 0, then copy out the key - // - if ($this->key_size > 0) { - $this->key_data = substr($packet->rdata, $offset, $this->key_size); - $offset += $this->key_size; - } - - // - // unpack the other length - // - $x = unpack('@'.$offset.'/nother_size', $packet->rdata); - - $this->other_size = $x['other_size']; - $offset += 2; - - // - // if other_size > 0, then copy out the data - // - if ($this->other_size > 0) { - $this->other_data = substr( - $packet->rdata, - $offset, - $this->other_size - ); - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->algorithm) > 0) { - // - // make sure the size values are correct - // - $this->key_size = strlen($this->key_data); - $this->other_size = strlen($this->other_data); - - // - // add the algorithm without compression - // - $data = Net_DNS2_Packet::pack($this->algorithm); - - // - // pack in the inception, expiration, mode, error and key size - // - $data .= pack( - 'NNnnn', - $this->inception, - $this->expiration, - $this->mode, - 0, - $this->key_size - ); - - // - // if the key_size > 0, then add the key - // - if ($this->key_size > 0) { - $data .= $this->key_data; - } - - // - // pack in the other size - // - $data .= pack('n', $this->other_size); - if ($this->other_size > 0) { - $data .= $this->other_data; - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_TKEY extends Net_DNS2_RR { + // TSIG Modes + public const TSIG_MODE_RES = 0; + public const TSIG_MODE_SERV_ASSIGN = 1; + public const TSIG_MODE_DH = 2; + public const TSIG_MODE_GSS_API = 3; + public const TSIG_MODE_RESV_ASSIGN = 4; + public const TSIG_MODE_KEY_DELE = 5; + public $algorithm; + public $inception; + public $expiration; + public $mode; + public $error; + public $key_size; + public $key_data; + public $other_size; + public $other_data; + + // map the mod id's to names so we can validate + public $tsgi_mode_id_to_name = [ + self::TSIG_MODE_RES => 'Reserved', + self::TSIG_MODE_SERV_ASSIGN => 'Server Assignment', + self::TSIG_MODE_DH => 'Diffie-Hellman', + self::TSIG_MODE_GSS_API => 'GSS-API', + self::TSIG_MODE_RESV_ASSIGN => 'Resolver Assignment', + self::TSIG_MODE_KEY_DELE => 'Key Deletion', + ]; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->cleanString($this->algorithm) . '. ' . $this->mode; + + if ($this->key_size > 0) { + $out .= ' ' . trim($this->key_data, '.') . '.'; + } else { + $out .= ' .'; + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // data passed in is assumed: + // + $this->algorithm = $this->cleanString(array_shift($rdata)); + $this->mode = array_shift($rdata); + $this->key_data = trim(array_shift($rdata), '.'); + + // + // the rest of the data is set manually + // + $this->inception = time(); + $this->expiration = time() + 86400; // 1 day + $this->error = 0; + $this->key_size = strlen($this->key_data); + $this->other_size = 0; + $this->other_data = ''; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // expand the algorithm + // + $offset = $packet->offset; + $this->algorithm = Net_DNS2_Packet::expand($packet, $offset); + + // + // unpack inception, expiration, mode, error and key size + // + $x = unpack( + '@' . $offset . '/Ninception/Nexpiration/nmode/nerror/nkey_size', + $packet->rdata + ); + + $this->inception = Net_DNS2::expandUint32($x['inception']); + $this->expiration = Net_DNS2::expandUint32($x['expiration']); + $this->mode = $x['mode']; + $this->error = $x['error']; + $this->key_size = $x['key_size']; + + $offset += 14; + + // + // if key_size > 0, then copy out the key + // + if ($this->key_size > 0) { + $this->key_data = substr($packet->rdata, $offset, $this->key_size); + $offset += $this->key_size; + } + + // + // unpack the other length + // + $x = unpack('@' . $offset . '/nother_size', $packet->rdata); + + $this->other_size = $x['other_size']; + $offset += 2; + + // + // if other_size > 0, then copy out the data + // + if ($this->other_size > 0) { + $this->other_data = substr( + $packet->rdata, + $offset, + $this->other_size + ); + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->algorithm) > 0) { + // + // make sure the size values are correct + // + $this->key_size = strlen($this->key_data); + $this->other_size = strlen($this->other_data); + + // + // add the algorithm without compression + // + $data = Net_DNS2_Packet::pack($this->algorithm); + + // + // pack in the inception, expiration, mode, error and key size + // + $data .= pack( + 'NNnnn', + $this->inception, + $this->expiration, + $this->mode, + 0, + $this->key_size + ); + + // + // if the key_size > 0, then add the key + // + if ($this->key_size > 0) { + $data .= $this->key_data; + } + + // + // pack in the other size + // + $data .= pack('n', $this->other_size); + + if ($this->other_size > 0) { + $data .= $this->other_data; + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/TLSA.php b/Net/DNS2/RR/TLSA.php index 9e3a6d6f..267da109 100644 --- a/Net/DNS2/RR/TLSA.php +++ b/Net/DNS2/RR/TLSA.php @@ -29,102 +29,97 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_TLSA extends Net_DNS2_RR -{ - // The Certificate Usage Field - public $cert_usage; - - // The Selector Field - public $selector; - - // The Matching Type Field - public $matching_type; - - // The Certificate Association Data Field - public $certificate; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->cert_usage.' '.$this->selector.' ' - .$this->matching_type.' '.base64_encode($this->certificate); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->cert_usage = array_shift($rdata); - $this->selector = array_shift($rdata); - $this->matching_type = array_shift($rdata); - $this->certificate = base64_decode(implode('', $rdata)); - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the format, keytag and algorithm - // - $x = unpack('Cusage/Cselector/Ctype', $this->rdata); - - $this->cert_usage = $x['usage']; - $this->selector = $x['selector']; - $this->matching_type = $x['type']; - - // - // copy the certificate - // - $this->certificate = substr($this->rdata, 3, $this->rdlength - 3); - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->certificate) > 0) { - $data = pack( - 'CCC', - $this->cert_usage, - $this->selector, - $this->matching_type - ).$this->certificate; - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_TLSA extends Net_DNS2_RR { + // The Certificate Usage Field + public $cert_usage; + + // The Selector Field + public $selector; + + // The Matching Type Field + public $matching_type; + + // The Certificate Association Data Field + public $certificate; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->cert_usage . ' ' . $this->selector . ' ' + . $this->matching_type . ' ' . base64_encode($this->certificate); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->cert_usage = array_shift($rdata); + $this->selector = array_shift($rdata); + $this->matching_type = array_shift($rdata); + $this->certificate = base64_decode(implode('', $rdata), true); + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the format, keytag and algorithm + // + $x = unpack('Cusage/Cselector/Ctype', $this->rdata); + + $this->cert_usage = $x['usage']; + $this->selector = $x['selector']; + $this->matching_type = $x['type']; + + // + // copy the certificate + // + $this->certificate = substr($this->rdata, 3, $this->rdlength - 3); + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->certificate) > 0) { + $data = pack( + 'CCC', + $this->cert_usage, + $this->selector, + $this->matching_type + ) . $this->certificate; + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/TSIG.php b/Net/DNS2/RR/TSIG.php index fffc7987..d2cd4f0f 100644 --- a/Net/DNS2/RR/TSIG.php +++ b/Net/DNS2/RR/TSIG.php @@ -40,387 +40,385 @@ * / other data / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_TSIG extends Net_DNS2_RR -{ - // TSIG Algorithm Identifiers - public const HMAC_MD5 = 'hmac-md5.sig-alg.reg.int'; // RFC 2845, required - public const GSS_TSIG = 'gss-tsig'; // unsupported, optional - public const HMAC_SHA1 = 'hmac-sha1'; // RFC 4635, required - public const HMAC_SHA224 = 'hmac-sha224'; // RFC 4635, optional - public const HMAC_SHA256 = 'hmac-sha256'; // RFC 4635, required - public const HMAC_SHA384 = 'hmac-sha384'; // RFC 4635, optional - public const HMAC_SHA512 = 'hmac-sha512'; // RFC 4635, optional - - // the map of hash values to names - public static $hash_algorithms = [ - self::HMAC_MD5 => 'md5', - self::HMAC_SHA1 => 'sha1', - self::HMAC_SHA224 => 'sha224', - self::HMAC_SHA256 => 'sha256', - self::HMAC_SHA384 => 'sha384', - self::HMAC_SHA512 => 'sha512', - ]; - - // algorithm used; only supports HMAC-MD5 - public $algorithm; - - // The time it was signed - public $time_signed; - - // fudge- allowed offset from the time signed - public $fudge; - - // size of the digest - public $mac_size; - - // the digest data - public $mac; - - // the original id of the request - public $original_id; - - // additional error code - public $error; - - /* - * length of the "other" data, should only ever be 0 when there is - * no error, or 6 when there is the error RCODE_BADTIME - */ - public $other_length; - - /* - * the other data; should only ever be a timestamp when there is the - * error RCODE_BADTIME - */ - public $other_data; - - // the key to use for signing - passed in, not included in the rdata - public $key; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $out = $this->cleanString($this->algorithm).'. ' - .$this->time_signed.' ' - .$this->fudge.' '.$this->mac_size.' ' - .base64_encode($this->mac).' '.$this->original_id.' ' - .$this->error.' '.$this->other_length; - - if ($this->other_length > 0) { - $out .= ' '.$this->other_data; - } - - return $out; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - // - // the only value passed in is the key- - // - // this assumes it's passed in base64 encoded. - // - $this->key = preg_replace('/\s+/', '', array_shift($rdata)); - - // - // the rest of the data is set to default - // - $this->algorithm = self::HMAC_MD5; - $this->time_signed = time(); - $this->fudge = 300; - $this->mac_size = 0; - $this->mac = ''; - $this->original_id = 0; - $this->error = 0; - $this->other_length = 0; - $this->other_data = ''; - - // - // per RFC 2845 section 2.3 - // - $this->class = 'ANY'; - $this->ttl = 0; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // expand the algorithm - // - $newoffset = $packet->offset; - $this->algorithm = Net_DNS2_Packet::expand($packet, $newoffset); - $offset = $newoffset - $packet->offset; - - // - // unpack time, fudge and mac_size - // - $x = unpack( - '@'.$offset.'/ntime_high/Ntime_low/nfudge/nmac_size', - $this->rdata - ); - - $this->time_signed = Net_DNS2::expandUint32($x['time_low']); - $this->fudge = $x['fudge']; - $this->mac_size = $x['mac_size']; - - $offset += 10; - - // - // copy out the mac - // - if ($this->mac_size > 0) { - $this->mac = substr($this->rdata, $offset, $this->mac_size); - $offset += $this->mac_size; - } - - // - // unpack the original id, error, and other_length values - // - $x = unpack( - '@'.$offset.'/noriginal_id/nerror/nother_length', - $this->rdata - ); - - $this->original_id = $x['original_id']; - $this->error = $x['error']; - $this->other_length = $x['other_length']; - - // - // the only time there is actually any "other data", is when there's - // a BADTIME error code. - // - // The other length should be 6, and the other data field includes the - // servers current time - per RFC 2845 section 4.5.2 - // - if (Net_DNS2_Lookups::RCODE_BADTIME == $this->error) { - if (6 != $this->other_length) { - return false; - } - - // - // other data is a 48bit timestamp - // - $x = unpack( - 'nhigh/nlow', - substr($this->rdata, $offset + 6, $this->other_length) - ); - $this->other_data = $x['low']; - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->key) > 0) { - // - // create a new packet for the signature- - // - $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); - - // - // copy the packet data over - // - $new_packet->copy($packet); - - // - // remove the TSIG object from the additional list - // - array_pop($new_packet->additional); - $new_packet->header->arcount = cacti_sizeof($new_packet->additional); - - // - // copy out the data - // - $sig_data = $new_packet->get(); - - // - // add the name without compressing - // - $sig_data .= Net_DNS2_Packet::pack($this->name); - - // - // add the class and TTL - // - $sig_data .= pack( - 'nN', - Net_DNS2_Lookups::$classes_by_name[$this->class], - $this->ttl - ); - - // - // add the algorithm name without compression - // - $sig_data .= Net_DNS2_Packet::pack(strtolower($this->algorithm)); - - // - // add the rest of the values - // - $sig_data .= pack( - 'nNnnn', - 0, - $this->time_signed, - $this->fudge, - $this->error, - $this->other_length - ); - if ($this->other_length > 0) { - $sig_data .= pack('nN', 0, $this->other_data); - } - - // - // sign the data - // - $this->mac = $this->_signHMAC( - $sig_data, - base64_decode($this->key), - $this->algorithm - ); - $this->mac_size = strlen($this->mac); - - // - // compress the algorithm - // - $data = Net_DNS2_Packet::pack(strtolower($this->algorithm)); - - // - // pack the time, fudge and mac size - // - $data .= pack( - 'nNnn', - 0, - $this->time_signed, - $this->fudge, - $this->mac_size - ); - $data .= $this->mac; - - // - // check the error and other_length - // - if (Net_DNS2_Lookups::RCODE_BADTIME == $this->error) { - $this->other_length = strlen($this->other_data); - if (6 != $this->other_length) { - return null; - } - } else { - $this->other_length = 0; - $this->other_data = ''; - } - - // - // pack the id, error and other_length - // - $data .= pack( - 'nnn', - $packet->header->id, - $this->error, - $this->other_length - ); - if ($this->other_length > 0) { - $data .= pack('nN', 0, $this->other_data); - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } - - /** - * signs the given data with the given key, and returns the result. - * - * @param string $data the data to sign - * @param string $key key to use for signing - * @param string $algorithm the algorithm to use; defaults to MD5 - * - * @return string the signed digest - * - * @throws Net_DNS2_Exception - */ - private function _signHMAC($data, $key = null, $algorithm = self::HMAC_MD5) - { - // - // use the hash extension; this is included by default in >= 5.1.2 which - // is our dependent version anyway- so it's easy to switch to it. - // - if (extension_loaded('hash')) { - if (!isset(self::$hash_algorithms[$algorithm])) { - throw new Net_DNS2_Exception( - 'invalid or unsupported algorithm', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - return hash_hmac(self::$hash_algorithms[$algorithm], $data, $key, true); - } - - // - // if the hash extension isn't loaded, and they selected something other - // than MD5, throw an exception - // - if (self::HMAC_MD5 != $algorithm) { - throw new Net_DNS2_Exception( - 'only HMAC-MD5 supported. please install the php-extension ' - .'"hash" in order to use the sha-family', - Net_DNS2_Lookups::E_PARSE_ERROR - ); - } - - // - // otherwise, do it ourselves - // - if (is_null($key)) { - return pack('H*', md5($data)); - } - - $key = str_pad($key, 64, chr(0x00)); - if (strlen($key) > 64) { - $key = pack('H*', md5($key)); - } - - $k_ipad = $key ^ str_repeat(chr(0x36), 64); - $k_opad = $key ^ str_repeat(chr(0x5C), 64); - - return $this->_signHMAC( - $k_opad.pack('H*', md5($k_ipad.$data)), - null, - $algorithm - ); - } +class Net_DNS2_RR_TSIG extends Net_DNS2_RR { + // TSIG Algorithm Identifiers + public const HMAC_MD5 = 'hmac-md5.sig-alg.reg.int'; // RFC 2845, required + public const GSS_TSIG = 'gss-tsig'; // unsupported, optional + public const HMAC_SHA1 = 'hmac-sha1'; // RFC 4635, required + public const HMAC_SHA224 = 'hmac-sha224'; // RFC 4635, optional + public const HMAC_SHA256 = 'hmac-sha256'; // RFC 4635, required + public const HMAC_SHA384 = 'hmac-sha384'; // RFC 4635, optional + public const HMAC_SHA512 = 'hmac-sha512'; // RFC 4635, optional + + // the map of hash values to names + public static $hash_algorithms = [ + self::HMAC_MD5 => 'md5', + self::HMAC_SHA1 => 'sha1', + self::HMAC_SHA224 => 'sha224', + self::HMAC_SHA256 => 'sha256', + self::HMAC_SHA384 => 'sha384', + self::HMAC_SHA512 => 'sha512', + ]; + + // algorithm used; only supports HMAC-MD5 + public $algorithm; + + // The time it was signed + public $time_signed; + + // fudge- allowed offset from the time signed + public $fudge; + + // size of the digest + public $mac_size; + + // the digest data + public $mac; + + // the original id of the request + public $original_id; + + // additional error code + public $error; + + /* + * length of the "other" data, should only ever be 0 when there is + * no error, or 6 when there is the error RCODE_BADTIME + */ + public $other_length; + + /* + * the other data; should only ever be a timestamp when there is the + * error RCODE_BADTIME + */ + public $other_data; + + // the key to use for signing - passed in, not included in the rdata + public $key; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $out = $this->cleanString($this->algorithm) . '. ' + . $this->time_signed . ' ' + . $this->fudge . ' ' . $this->mac_size . ' ' + . base64_encode($this->mac) . ' ' . $this->original_id . ' ' + . $this->error . ' ' . $this->other_length; + + if ($this->other_length > 0) { + $out .= ' ' . $this->other_data; + } + + return $out; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + // + // the only value passed in is the key- + // + // this assumes it's passed in base64 encoded. + // + $this->key = preg_replace('/\s+/', '', array_shift($rdata)); + + // + // the rest of the data is set to default + // + $this->algorithm = self::HMAC_MD5; + $this->time_signed = time(); + $this->fudge = 300; + $this->mac_size = 0; + $this->mac = ''; + $this->original_id = 0; + $this->error = 0; + $this->other_length = 0; + $this->other_data = ''; + + // + // per RFC 2845 section 2.3 + // + $this->class = 'ANY'; + $this->ttl = 0; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // expand the algorithm + // + $newoffset = $packet->offset; + $this->algorithm = Net_DNS2_Packet::expand($packet, $newoffset); + $offset = $newoffset - $packet->offset; + + // + // unpack time, fudge and mac_size + // + $x = unpack( + '@' . $offset . '/ntime_high/Ntime_low/nfudge/nmac_size', + $this->rdata + ); + + $this->time_signed = Net_DNS2::expandUint32($x['time_low']); + $this->fudge = $x['fudge']; + $this->mac_size = $x['mac_size']; + + $offset += 10; + + // + // copy out the mac + // + if ($this->mac_size > 0) { + $this->mac = substr($this->rdata, $offset, $this->mac_size); + $offset += $this->mac_size; + } + + // + // unpack the original id, error, and other_length values + // + $x = unpack( + '@' . $offset . '/noriginal_id/nerror/nother_length', + $this->rdata + ); + + $this->original_id = $x['original_id']; + $this->error = $x['error']; + $this->other_length = $x['other_length']; + + // + // the only time there is actually any "other data", is when there's + // a BADTIME error code. + // + // The other length should be 6, and the other data field includes the + // servers current time - per RFC 2845 section 4.5.2 + // + if ($this->error == Net_DNS2_Lookups::RCODE_BADTIME) { + if ($this->other_length != 6) { + return false; + } + + // + // other data is a 48bit timestamp + // + $x = unpack( + 'nhigh/nlow', + substr($this->rdata, $offset + 6, $this->other_length) + ); + $this->other_data = $x['low']; + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->key) > 0) { + // + // create a new packet for the signature- + // + $new_packet = new Net_DNS2_Packet_Request('example.com', 'SOA', 'IN'); + + // + // copy the packet data over + // + $new_packet->copy($packet); + + // + // remove the TSIG object from the additional list + // + array_pop($new_packet->additional); + $new_packet->header->arcount = cacti_sizeof($new_packet->additional); + + // + // copy out the data + // + $sig_data = $new_packet->get(); + + // + // add the name without compressing + // + $sig_data .= Net_DNS2_Packet::pack($this->name); + + // + // add the class and TTL + // + $sig_data .= pack( + 'nN', + Net_DNS2_Lookups::$classes_by_name[$this->class], + $this->ttl + ); + + // + // add the algorithm name without compression + // + $sig_data .= Net_DNS2_Packet::pack(strtolower($this->algorithm)); + + // + // add the rest of the values + // + $sig_data .= pack( + 'nNnnn', + 0, + $this->time_signed, + $this->fudge, + $this->error, + $this->other_length + ); + + if ($this->other_length > 0) { + $sig_data .= pack('nN', 0, $this->other_data); + } + + // + // sign the data + // + $this->mac = $this->_signHMAC( + $sig_data, + base64_decode($this->key, true), + $this->algorithm + ); + $this->mac_size = strlen($this->mac); + + // + // compress the algorithm + // + $data = Net_DNS2_Packet::pack(strtolower($this->algorithm)); + + // + // pack the time, fudge and mac size + // + $data .= pack( + 'nNnn', + 0, + $this->time_signed, + $this->fudge, + $this->mac_size + ); + $data .= $this->mac; + + // + // check the error and other_length + // + if ($this->error == Net_DNS2_Lookups::RCODE_BADTIME) { + $this->other_length = strlen($this->other_data); + + if ($this->other_length != 6) { + return null; + } + } else { + $this->other_length = 0; + $this->other_data = ''; + } + + // + // pack the id, error and other_length + // + $data .= pack( + 'nnn', + $packet->header->id, + $this->error, + $this->other_length + ); + + if ($this->other_length > 0) { + $data .= pack('nN', 0, $this->other_data); + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } + + /** + * signs the given data with the given key, and returns the result. + * + * @param string $data the data to sign + * @param string $key key to use for signing + * @param string $algorithm the algorithm to use; defaults to MD5 + * + * @return string the signed digest + * + * @throws Net_DNS2_Exception + */ + private function _signHMAC($data, $key = null, $algorithm = self::HMAC_MD5) { + // + // use the hash extension; this is included by default in >= 5.1.2 which + // is our dependent version anyway- so it's easy to switch to it. + // + if (extension_loaded('hash')) { + if (!isset(self::$hash_algorithms[$algorithm])) { + throw new Net_DNS2_Exception( + 'invalid or unsupported algorithm', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + return hash_hmac(self::$hash_algorithms[$algorithm], $data, $key, true); + } + + // + // if the hash extension isn't loaded, and they selected something other + // than MD5, throw an exception + // + if ($algorithm != self::HMAC_MD5) { + throw new Net_DNS2_Exception( + 'only HMAC-MD5 supported. please install the php-extension ' + . '"hash" in order to use the sha-family', + Net_DNS2_Lookups::E_PARSE_ERROR + ); + } + + // + // otherwise, do it ourselves + // + if (is_null($key)) { + return pack('H*', md5($data)); + } + + $key = str_pad($key, 64, chr(0x00)); + + if (strlen($key) > 64) { + $key = pack('H*', md5($key)); + } + + $k_ipad = $key ^ str_repeat(chr(0x36), 64); + $k_opad = $key ^ str_repeat(chr(0x5C), 64); + + return $this->_signHMAC( + $k_opad . pack('H*', md5($k_ipad . $data)), + null, + $algorithm + ); + } } diff --git a/Net/DNS2/RR/TXT.php b/Net/DNS2/RR/TXT.php index e9d40b45..adfe2072 100644 --- a/Net/DNS2/RR/TXT.php +++ b/Net/DNS2/RR/TXT.php @@ -24,90 +24,86 @@ * / TXT-DATA / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_TXT extends Net_DNS2_RR -{ - // an array of the text strings - public $text = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - if (0 == cacti_sizeof($this->text)) { - return '""'; - } - - $data = ''; - - foreach ($this->text as $t) { - $data .= $this->formatString($t).' '; - } - - return trim($data); - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (cacti_sizeof($data) > 0) { - $this->text = $data; - } - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $length = $packet->offset + $this->rdlength; - $offset = $packet->offset; - - while ($length > $offset) { - $this->text[] = Net_DNS2_Packet::label($packet, $offset); - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - $data = null; - - foreach ($this->text as $t) { - $data .= chr(strlen($t)).$t; - } - - $packet->offset += strlen($data); - - return $data; - } +class Net_DNS2_RR_TXT extends Net_DNS2_RR { + // an array of the text strings + public $text = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + if (cacti_sizeof($this->text) == 0) { + return '""'; + } + + $data = ''; + + foreach ($this->text as $t) { + $data .= $this->formatString($t) . ' '; + } + + return trim($data); + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $data = $this->buildString($rdata); + + if (cacti_sizeof($data) > 0) { + $this->text = $data; + } + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $length = $packet->offset + $this->rdlength; + $offset = $packet->offset; + + while ($length > $offset) { + $this->text[] = Net_DNS2_Packet::label($packet, $offset); + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + $data = null; + + foreach ($this->text as $t) { + $data .= chr(strlen($t)) . $t; + } + + $packet->offset += strlen($data); + + return $data; + } } diff --git a/Net/DNS2/RR/TYPE65534.php b/Net/DNS2/RR/TYPE65534.php index 8bcf8d53..f9ebfe49 100644 --- a/Net/DNS2/RR/TYPE65534.php +++ b/Net/DNS2/RR/TYPE65534.php @@ -24,72 +24,67 @@ * in the Bind ARM, chapter 4, "Private-type records. * Basically they store signing process state. */ -class Net_DNS2_RR_TYPE65534 extends Net_DNS2_RR -{ - // The Private data field - public $private_data; +class Net_DNS2_RR_TYPE65534 extends Net_DNS2_RR { + // The Private data field + public $private_data; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return base64_encode($this->private_data); - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return base64_encode($this->private_data); + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->private_data = base64_decode(implode('', $rdata)); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->private_data = base64_decode(implode('', $rdata), true); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $this->private_data = $this->rdata; + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $this->private_data = $this->rdata; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->private_data) > 0) { - $data = $this->private_data; + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->private_data) > 0) { + $data = $this->private_data; - $packet->offset += strlen($data); + $packet->offset += strlen($data); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/URI.php b/Net/DNS2/RR/URI.php index 125081b6..36d4dcec 100644 --- a/Net/DNS2/RR/URI.php +++ b/Net/DNS2/RR/URI.php @@ -29,90 +29,85 @@ * / / * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -class Net_DNS2_RR_URI extends Net_DNS2_RR -{ - // The priority of this target host. - public $priority; +class Net_DNS2_RR_URI extends Net_DNS2_RR { + // The priority of this target host. + public $priority; - // a relative weight for entries with the same priority - public $weight; + // a relative weight for entries with the same priority + public $weight; - // The domain name of the target host - public $target; + // The domain name of the target host + public $target; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - // - // presentation format has double quotes (") around the target. - // - return $this->priority.' '.$this->weight.' "'.$this->target.'"'; - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + // + // presentation format has double quotes (") around the target. + // + return $this->priority . ' ' . $this->weight . ' "' . $this->target . '"'; + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->priority = $rdata[0]; - $this->weight = $rdata[1]; - $this->target = trim(strtolower(trim($rdata[2])), '"'); + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->priority = $rdata[0]; + $this->weight = $rdata[1]; + $this->target = trim(strtolower(trim($rdata[2])), '"'); - return true; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // unpack the priority and weight - // - $x = unpack('npriority/nweight/a*target', $this->rdata); + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // unpack the priority and weight + // + $x = unpack('npriority/nweight/a*target', $this->rdata); - $this->priority = $x['priority']; - $this->weight = $x['weight']; - $this->target = $x['target']; + $this->priority = $x['priority']; + $this->weight = $x['weight']; + $this->target = $x['target']; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->target) > 0) { - $data = pack('nna*', $this->priority, $this->weight, $this->target); + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->target) > 0) { + $data = pack('nna*', $this->priority, $this->weight, $this->target); - $packet->offset += strlen($data); + $packet->offset += strlen($data); - return $data; - } + return $data; + } - return null; - } + return null; + } } diff --git a/Net/DNS2/RR/WKS.php b/Net/DNS2/RR/WKS.php index 403c1274..a280b1c7 100644 --- a/Net/DNS2/RR/WKS.php +++ b/Net/DNS2/RR/WKS.php @@ -30,138 +30,136 @@ * / / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_WKS extends Net_DNS2_RR -{ - // The IP address of the service - public $address; - - // The protocol of the service - public $protocol; - - // bitmap - public $bitmap = []; - - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - $data = $this->address.' '.$this->protocol; - - foreach ($this->bitmap as $port) { - $data .= ' '.$port; - } - - return $data; - } - - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $this->address = strtolower(trim(array_shift($rdata), '.')); - $this->protocol = array_shift($rdata); - $this->bitmap = $rdata; - - return true; - } - - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - // - // get the address and protocol value - // - $x = unpack('Naddress/Cprotocol', $this->rdata); - - $this->address = long2ip($x['address']); - $this->protocol = $x['protocol']; - - // - // unpack the port list bitmap - // - $port = 0; - foreach (unpack('@5/C*', $this->rdata) as $set) { - $s = sprintf('%08b', $set); - - for ($i = 0; $i < 8; $i++, $port++) { - if ('1' == $s[$i]) { - $this->bitmap[] = $port; - } - } - } - - return true; - } - - return false; - } - - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->address) > 0) { - $data = pack('NC', ip2long($this->address), $this->protocol); - - $ports = []; - - $n = 0; - foreach ($this->bitmap as $port) { - $ports[$port] = 1; - - if ($port > $n) { - $n = $port; - } - } - for ($i = 0; $i < ceil($n / 8) * 8; ++$i) { - if (!isset($ports[$i])) { - $ports[$i] = 0; - } - } - - ksort($ports); - - $string = ''; - $n = 0; - - foreach ($ports as $s) { - $string .= $s; - ++$n; - - if (8 == $n) { - $data .= chr(bindec($string)); - $string = ''; - $n = 0; - } - } - - $packet->offset += strlen($data); - - return $data; - } - - return null; - } +class Net_DNS2_RR_WKS extends Net_DNS2_RR { + // The IP address of the service + public $address; + + // The protocol of the service + public $protocol; + + // bitmap + public $bitmap = []; + + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + $data = $this->address . ' ' . $this->protocol; + + foreach ($this->bitmap as $port) { + $data .= ' ' . $port; + } + + return $data; + } + + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $this->address = strtolower(trim(array_shift($rdata), '.')); + $this->protocol = array_shift($rdata); + $this->bitmap = $rdata; + + return true; + } + + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + // + // get the address and protocol value + // + $x = unpack('Naddress/Cprotocol', $this->rdata); + + $this->address = long2ip($x['address']); + $this->protocol = $x['protocol']; + + // + // unpack the port list bitmap + // + $port = 0; + + foreach (unpack('@5/C*', $this->rdata) as $set) { + $s = sprintf('%08b', $set); + + for ($i = 0; $i < 8; $i++, $port++) { + if ($s[$i] == '1') { + $this->bitmap[] = $port; + } + } + } + + return true; + } + + return false; + } + + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->address) > 0) { + $data = pack('NC', ip2long($this->address), $this->protocol); + + $ports = []; + + $n = 0; + + foreach ($this->bitmap as $port) { + $ports[$port] = 1; + + if ($port > $n) { + $n = $port; + } + } + + for ($i = 0; $i < ceil($n / 8) * 8; ++$i) { + if (!isset($ports[$i])) { + $ports[$i] = 0; + } + } + + ksort($ports); + + $string = ''; + $n = 0; + + foreach ($ports as $s) { + $string .= $s; + ++$n; + + if ($n == 8) { + $data .= chr(bindec($string)); + $string = ''; + $n = 0; + } + } + + $packet->offset += strlen($data); + + return $data; + } + + return null; + } } diff --git a/Net/DNS2/RR/X25.php b/Net/DNS2/RR/X25.php index fbe2d67a..9ce89278 100644 --- a/Net/DNS2/RR/X25.php +++ b/Net/DNS2/RR/X25.php @@ -24,77 +24,73 @@ * / PSDN-address / * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ -class Net_DNS2_RR_X25 extends Net_DNS2_RR -{ - // The PSDN address - public $psdnaddress; +class Net_DNS2_RR_X25 extends Net_DNS2_RR { + // The PSDN address + public $psdnaddress; - /** - * method to return the rdata portion of the packet as a string. - * - * @return string - */ - protected function rrToString() - { - return $this->formatString($this->psdnaddress); - } + /** + * method to return the rdata portion of the packet as a string. + * + * @return string + */ + protected function rrToString() { + return $this->formatString($this->psdnaddress); + } - /** - * parses the rdata portion from a standard DNS config line. - * - * @param array $rdata a string split line of values for the rdata - * - * @return bool - */ - protected function rrFromString(array $rdata) - { - $data = $this->buildString($rdata); - if (1 == cacti_sizeof($data)) { - $this->psdnaddress = $data[0]; + /** + * parses the rdata portion from a standard DNS config line. + * + * @param array $rdata a string split line of values for the rdata + * + * @return bool + */ + protected function rrFromString(array $rdata) { + $data = $this->buildString($rdata); - return true; - } + if (cacti_sizeof($data) == 1) { + $this->psdnaddress = $data[0]; - return false; - } + return true; + } - /** - * parses the rdata of the Net_DNS2_Packet object. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from - * - * @return bool - */ - protected function rrSet(Net_DNS2_Packet &$packet) - { - if ($this->rdlength > 0) { - $this->psdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); + return false; + } - return true; - } + /** + * parses the rdata of the Net_DNS2_Packet object. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from + * + * @return bool + */ + protected function rrSet(Net_DNS2_Packet &$packet) { + if ($this->rdlength > 0) { + $this->psdnaddress = Net_DNS2_Packet::label($packet, $packet->offset); - return false; - } + return true; + } - /** - * returns the rdata portion of the DNS packet. - * - * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for - * compressed names - * - * @return mixed either returns a binary packed - * string or null on failure - */ - protected function rrGet(Net_DNS2_Packet &$packet) - { - if (strlen($this->psdnaddress) > 0) { - $data = chr(strlen($this->psdnaddress)).$this->psdnaddress; + return false; + } - $packet->offset += strlen($data); + /** + * returns the rdata portion of the DNS packet. + * + * @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for + * compressed names + * + * @return mixed either returns a binary packed + * string or null on failure + */ + protected function rrGet(Net_DNS2_Packet &$packet) { + if (strlen($this->psdnaddress) > 0) { + $data = chr(strlen($this->psdnaddress)) . $this->psdnaddress; - return $data; - } + $packet->offset += strlen($data); - return null; - } + return $data; + } + + return null; + } } diff --git a/Net/DNS2/Resolver.php b/Net/DNS2/Resolver.php index 1fa1e685..20bdca8d 100644 --- a/Net/DNS2/Resolver.php +++ b/Net/DNS2/Resolver.php @@ -20,252 +20,249 @@ /** * This is the main resolver class, providing DNS query functions. */ -class Net_DNS2_Resolver extends Net_DNS2 -{ - /** - * Constructor - creates a new Net_DNS2_Resolver object. - * - * @param mixed $options either an array with options or null - */ - public function __construct(?array $options = null) - { - parent::__construct($options); - } +class Net_DNS2_Resolver extends Net_DNS2 { + /** + * Constructor - creates a new Net_DNS2_Resolver object. + * + * @param mixed $options either an array with options or null + */ + public function __construct(?array $options = null) { + parent::__construct($options); + } - /** - * does a basic DNS lookup query. - * - * @param string $name the DNS name to loookup - * @param string $type the name of the RR type to lookup - * @param string $class the name of the RR class to lookup - * - * @return Net_DNS2_Packet_Response object - * - * @throws Net_DNS2_Exception - */ - public function query($name, $type = 'A', $class = 'IN') - { - // - // make sure we have some name servers set - // - $this->checkServers(Net_DNS2::RESOLV_CONF); + /** + * does a basic DNS lookup query. + * + * @param string $name the DNS name to loookup + * @param string $type the name of the RR type to lookup + * @param string $class the name of the RR class to lookup + * + * @return Net_DNS2_Packet_Response object + * + * @throws Net_DNS2_Exception + */ + public function query($name, $type = 'A', $class = 'IN') { + // + // make sure we have some name servers set + // + $this->checkServers(Net_DNS2::RESOLV_CONF); - // - // we don't support incremental zone transfers; so if it's requested, a full - // zone transfer can be returned - // - if ('IXFR' == $type) { - $type = 'AXFR'; - } + // + // we don't support incremental zone transfers; so if it's requested, a full + // zone transfer can be returned + // + if ($type == 'IXFR') { + $type = 'AXFR'; + } - // - // if the name *looks* too short, then append the domain from the config - // - if ((false === strpos($name, '.')) && ('PTR' != $type)) { - $name .= '.'.strtolower($this->domain); - } + // + // if the name *looks* too short, then append the domain from the config + // + if ((strpos($name, '.') === false) && ($type != 'PTR')) { + $name .= '.' . strtolower($this->domain); + } - // - // create a new packet based on the input - // - $packet = new Net_DNS2_Packet_Request($name, $type, $class); + // + // create a new packet based on the input + // + $packet = new Net_DNS2_Packet_Request($name, $type, $class); - // - // check for an authentication method; either TSIG or SIG - // - if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $packet->additional[] = $this->auth_signature; - $packet->header->arcount = cacti_sizeof($packet->additional); - } + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $packet->additional[] = $this->auth_signature; + $packet->header->arcount = cacti_sizeof($packet->additional); + } - // - // check for the DNSSEC flag, and if it's true, then add an OPT - // RR to the additional section, and set the DO flag to 1. - // - if (true == $this->dnssec) { - // - // create a new OPT RR - // - $opt = new Net_DNS2_RR_OPT(); + // + // check for the DNSSEC flag, and if it's true, then add an OPT + // RR to the additional section, and set the DO flag to 1. + // + if ($this->dnssec == true) { + // + // create a new OPT RR + // + $opt = new Net_DNS2_RR_OPT(); - // - // set the DO flag, and the other values - // - $opt->do = 1; - $opt->class = $this->dnssec_payload_size; + // + // set the DO flag, and the other values + // + $opt->do = 1; + $opt->class = $this->dnssec_payload_size; - // - // add the RR to the additional section. - // - $packet->additional[] = $opt; - $packet->header->arcount = cacti_sizeof($packet->additional); - } + // + // add the RR to the additional section. + // + $packet->additional[] = $opt; + $packet->header->arcount = cacti_sizeof($packet->additional); + } - // - // set the DNSSEC AD or CD bits - // - if (true == $this->dnssec_ad_flag) { - $packet->header->ad = 1; - } - if (true == $this->dnssec_cd_flag) { - $packet->header->cd = 1; - } + // + // set the DNSSEC AD or CD bits + // + if ($this->dnssec_ad_flag == true) { + $packet->header->ad = 1; + } - // - // if caching is turned on, then check then hash the question, and - // do a cache lookup. - // - // don't use the cache for zone transfers - // - $packet_hash = ''; + if ($this->dnssec_cd_flag == true) { + $packet->header->cd = 1; + } - if ((true == $this->use_cache) && (true == $this->cacheable($type))) { - // - // open the cache - // - $this->cache->open( - $this->cache_file, - $this->cache_size, - $this->cache_serializer - ); + // + // if caching is turned on, then check then hash the question, and + // do a cache lookup. + // + // don't use the cache for zone transfers + // + $packet_hash = ''; - // - // build the key and check for it in the cache. - // - $packet_hash = md5( - $packet->question[0]->qname.'|'.$packet->question[0]->qtype - ); + if (($this->use_cache == true) && ($this->cacheable($type) == true)) { + // + // open the cache + // + $this->cache->open( + $this->cache_file, + $this->cache_size, + $this->cache_serializer + ); - if ($this->cache->has($packet_hash)) { - return $this->cache->get($packet_hash); - } - } + // + // build the key and check for it in the cache. + // + $packet_hash = md5( + $packet->question[0]->qname . '|' . $packet->question[0]->qtype + ); - // - // set the RD (recursion desired) bit to 1 / 0 depending on the config - // setting. - // - if (false == $this->recurse) { - $packet->header->rd = 0; - } else { - $packet->header->rd = 1; - } + if ($this->cache->has($packet_hash)) { + return $this->cache->get($packet_hash); + } + } - // - // send the packet and get back the response - // - // *always* use TCP for zone transfers- does this cause any problems? - // - $response = $this->sendPacket( - $packet, - ('AXFR' == $type) ? true : $this->use_tcp - ); + // + // set the RD (recursion desired) bit to 1 / 0 depending on the config + // setting. + // + if ($this->recurse == false) { + $packet->header->rd = 0; + } else { + $packet->header->rd = 1; + } - // - // if strict mode is enabled, then make sure that the name that was - // looked up is *actually* in the response object. - // - // only do this is strict_query_mode is turned on, AND we've received - // some answers; no point doing any else if there were no answers. - // - if ((true == $this->strict_query_mode) - && ($response->header->ancount > 0) - ) { - $found = false; + // + // send the packet and get back the response + // + // *always* use TCP for zone transfers- does this cause any problems? + // + $response = $this->sendPacket( + $packet, + ($type == 'AXFR') ? true : $this->use_tcp + ); - // - // look for the requested name/type/class - // - foreach ($response->answer as $index => $object) { - if ((0 == strcasecmp(trim($object->name, '.'), trim($packet->question[0]->qname, '.'))) - && ($object->type == $packet->question[0]->qtype) - && ($object->class == $packet->question[0]->qclass) - ) { - $found = true; + // + // if strict mode is enabled, then make sure that the name that was + // looked up is *actually* in the response object. + // + // only do this is strict_query_mode is turned on, AND we've received + // some answers; no point doing any else if there were no answers. + // + if (($this->strict_query_mode == true) + && ($response->header->ancount > 0) + ) { + $found = false; - break; - } - } + // + // look for the requested name/type/class + // + foreach ($response->answer as $index => $object) { + if ((strcasecmp(trim($object->name, '.'), trim($packet->question[0]->qname, '.')) == 0) + && ($object->type == $packet->question[0]->qtype) + && ($object->class == $packet->question[0]->qclass) + ) { + $found = true; - // - // if it's not found, then unset the answer section; it's not correct to - // throw an exception here; if the hostname didn't exist, then - // sendPacket() would have already thrown an NXDOMAIN error- so the host - // *exists*, but just not the request type/class. - // - // the correct response in this case, is an empty answer section; the - // authority section may still have usual information, like a SOA record. - // - if (false == $found) { - $response->answer = []; - $response->header->ancount = 0; - } - } + break; + } + } - // - // cache the response object - // - if ((true == $this->use_cache) && (true == $this->cacheable($type))) { - $this->cache->put($packet_hash, $response); - } + // + // if it's not found, then unset the answer section; it's not correct to + // throw an exception here; if the hostname didn't exist, then + // sendPacket() would have already thrown an NXDOMAIN error- so the host + // *exists*, but just not the request type/class. + // + // the correct response in this case, is an empty answer section; the + // authority section may still have usual information, like a SOA record. + // + if ($found == false) { + $response->answer = []; + $response->header->ancount = 0; + } + } - return $response; - } + // + // cache the response object + // + if (($this->use_cache == true) && ($this->cacheable($type) == true)) { + $this->cache->put($packet_hash, $response); + } - /** - * does an inverse query for the given RR; most DNS servers do not implement - * inverse queries, but they should be able to return "not implemented". - * - * @param Net_DNS2_RR $rr the RR object to lookup - * - * @return Net_DNS2_RR object - * - * @throws Net_DNS2_Exception - */ - public function iquery(Net_DNS2_RR $rr) - { - // - // make sure we have some name servers set - // - $this->checkServers(Net_DNS2::RESOLV_CONF); + return $response; + } - // - // create an empty packet - // - $packet = new Net_DNS2_Packet_Request($rr->name, 'A', 'IN'); + /** + * does an inverse query for the given RR; most DNS servers do not implement + * inverse queries, but they should be able to return "not implemented". + * + * @param Net_DNS2_RR $rr the RR object to lookup + * + * @return Net_DNS2_RR object + * + * @throws Net_DNS2_Exception + */ + public function iquery(Net_DNS2_RR $rr) { + // + // make sure we have some name servers set + // + $this->checkServers(Net_DNS2::RESOLV_CONF); - // - // unset the question - // - $packet->question = []; - $packet->header->qdcount = 0; + // + // create an empty packet + // + $packet = new Net_DNS2_Packet_Request($rr->name, 'A', 'IN'); - // - // set the opcode to IQUERY - // - $packet->header->opcode = Net_DNS2_Lookups::OPCODE_IQUERY; + // + // unset the question + // + $packet->question = []; + $packet->header->qdcount = 0; - // - // add the given RR as the answer - // - $packet->answer[] = $rr; - $packet->header->ancount = 1; + // + // set the opcode to IQUERY + // + $packet->header->opcode = Net_DNS2_Lookups::OPCODE_IQUERY; - // - // check for an authentication method; either TSIG or SIG - // - if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $packet->additional[] = $this->auth_signature; - $packet->header->arcount = cacti_sizeof($packet->additional); - } + // + // add the given RR as the answer + // + $packet->answer[] = $rr; + $packet->header->ancount = 1; - // - // send the packet and get back the response - // - return $this->sendPacket($packet, $this->use_tcp); - } + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $packet->additional[] = $this->auth_signature; + $packet->header->arcount = cacti_sizeof($packet->additional); + } + + // + // send the packet and get back the response + // + return $this->sendPacket($packet, $this->use_tcp); + } } diff --git a/Net/DNS2/Socket.php b/Net/DNS2/Socket.php index fa8b4997..81aa3e8b 100644 --- a/Net/DNS2/Socket.php +++ b/Net/DNS2/Socket.php @@ -18,392 +18,394 @@ */ // check to see if the socket defines exist; if they don't, then define them -if (false == defined('SOCK_STREAM')) { - define('SOCK_STREAM', 1); +if (defined('SOCK_STREAM') == false) { + define('SOCK_STREAM', 1); } -if (false == defined('SOCK_DGRAM')) { - define('SOCK_DGRAM', 2); + +if (defined('SOCK_DGRAM') == false) { + define('SOCK_DGRAM', 2); } /** * Socket handling class using the PHP Streams. */ -class Net_DNS2_Socket -{ - // type of sockets - public const SOCK_STREAM = SOCK_STREAM; - public const SOCK_DGRAM = SOCK_DGRAM; - - // the last error message on the object - public $last_error; - - // date the socket connection was created, and the date it was last used - public $date_created; - public $date_last_used; - private $sock; - private $type; - private $host; - private $port; - private $timeout; - private $context; - - // the local IP and port we'll send the request from - private $local_host; - private $local_port; - - /** - * constructor - set the port details. - * - * @param int $type the socket type - * @param string $host the IP address of the DNS server to connect to - * @param int $port the port of the DNS server to connect to - * @param int $timeout the timeout value to use for socket functions - */ - public function __construct($type, $host, $port, $timeout) - { - $this->type = $type; - $this->host = $host; - $this->port = $port; - $this->timeout = $timeout; - $this->date_created = microtime(true); - } - - /** - * destructor. - */ - public function __destruct() - { - $this->close(); - } - - /** - * sets the local address/port for the socket to bind to. - * - * @param string $address the local IP address to bind to - * @param mixed $port the local port to bind to, or 0 to let the socket - * function select a port - * - * @return bool - */ - public function bindAddress($address, $port = 0) - { - $this->local_host = $address; - $this->local_port = $port; - - return true; - } - - /** - * opens a socket connection to the DNS server. - * - * @return bool - */ - public function open() - { - // - // create a list of options for the context - // - $opts = ['socket' => []]; - - // - // bind to a local IP/port if it's set - // - if (strlen($this->local_host) > 0) { - $opts['socket']['bindto'] = $this->local_host; - if ($this->local_port > 0) { - $opts['socket']['bindto'] .= ':'.$this->local_port; - } - } - - // - // create the context - // - $this->context = @stream_context_create($opts); - - // - // create socket - // - - switch ($this->type) { - case Net_DNS2_Socket::SOCK_STREAM: - if (true == Net_DNS2::isIPv4($this->host)) { - $this->sock = @stream_socket_client( - 'tcp://'.$this->host.':'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->context - ); - } elseif (true == Net_DNS2::isIPv6($this->host)) { - $this->sock = @stream_socket_client( - 'tcp://['.$this->host.']:'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->context - ); - } else { - $this->last_error = 'invalid address type: '.$this->host; - - return false; - } - - break; - - case Net_DNS2_Socket::SOCK_DGRAM: - if (true == Net_DNS2::isIPv4($this->host)) { - $this->sock = @stream_socket_client( - 'udp://'.$this->host.':'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->context - ); - } elseif (true == Net_DNS2::isIPv6($this->host)) { - $this->sock = @stream_socket_client( - 'udp://['.$this->host.']:'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->context - ); - } else { - $this->last_error = 'invalid address type: '.$this->host; - - return false; - } - - break; - - default: - $this->last_error = 'Invalid socket type: '.$this->type; - - return false; - } - - if (false === $this->sock) { - $this->last_error = $errstr; - - return false; - } - - // - // set it to non-blocking and set the timeout - // - @stream_set_blocking($this->sock, 0); - @stream_set_timeout($this->sock, $this->timeout); - - return true; - } - - /** - * closes a socket connection to the DNS server. - * - * @return bool - */ - public function close() - { - if (true === is_resource($this->sock)) { - @fclose($this->sock); - } - - return true; - } - - /** - * writes the given string to the DNS server socket. - * - * @param string $data a binary packed DNS packet - * - * @return bool - */ - public function write($data) - { - $length = strlen($data); - if (0 == $length) { - $this->last_error = 'empty data on write()'; - - return false; - } - - $read = null; - $write = [$this->sock]; - $except = null; - - // - // increment the date last used timestamp - // - $this->date_last_used = microtime(true); - - // - // select on write - // - $result = stream_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = 'failed on write select()'; - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on write select()'; - - return false; - } - - // - // if it's a TCP socket, then we need to packet and send the length of the - // data as the first 16bit of data. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - $s = chr($length >> 8).chr($length); - - if (false === @fwrite($this->sock, $s)) { - $this->last_error = 'failed to fwrite() 16bit length'; - - return false; - } - } - - // - // write the data to the socket - // - $size = @fwrite($this->sock, $data); - if ((false === $size) || ($size != $length)) { - $this->last_error = 'failed to fwrite() packet'; - - return false; - } - - return true; - } - - /** - * reads a response from a DNS server. - * - * @param int &$size the size of the DNS packet read is passed back - * @param int $max_size the max data size returned - * - * @return mixed returns the data on success and false on error - */ - public function read(&$size, $max_size) - { - $read = [$this->sock]; - $write = null; - $except = null; - - // - // increment the date last used timestamp - // - $this->date_last_used = microtime(true); - - // - // make sure our socket is non-blocking - // - @stream_set_blocking($this->sock, 0); - - // - // select on read - // - $result = stream_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = 'error on read select()'; - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on read select()'; - - return false; - } - - $data = ''; - $length = $max_size; - - // - // if it's a TCP socket, then the first two bytes is the length of the DNS - // packet- we need to read that off first, then use that value for the - // packet read. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - if (($data = fread($this->sock, 2)) === false) { - $this->last_error = 'failed on fread() for data length'; - - return false; - } - if (0 == strlen($data)) { - $this->last_error = 'failed on fread() for data length'; - - return false; - } - - $length = ord($data[0]) << 8 | ord($data[1]); - if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - return false; - } - } - - // - // at this point, we know that there is data on the socket to be read, - // because we've already extracted the length from the first two bytes. - // - // so the easiest thing to do, is just turn off socket blocking, and - // wait for the data. - // - @stream_set_blocking($this->sock, 1); - - // - // read the data from the socket - // - $data = ''; - - // - // the streams socket is weird for TCP sockets; it doesn't seem to always - // return all the data properly; but the looping code I added broke UDP - // packets- my fault- - // - // the sockets library works much better. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - $chunk = ''; - $chunk_size = $length; - - // - // loop so we make sure we read all the data - // - while (1) { - $chunk = fread($this->sock, $chunk_size); - if (false === $chunk) { - $this->last_error = 'failed on fread() for data'; - - return false; - } - - $data .= $chunk; - $chunk_size -= strlen($chunk); - - if (strlen($data) >= $length) { - break; - } - } - } else { - // - // if it's UDP, it's a single fixed-size frame, and the streams library - // doesn't seem to have a problem reading it. - // - $data = fread($this->sock, $length); - if (false === $length) { - $this->last_error = 'failed on fread() for data'; - - return false; - } - } - - $size = strlen($data); - - return $data; - } +class Net_DNS2_Socket { + // type of sockets + public const SOCK_STREAM = SOCK_STREAM; + public const SOCK_DGRAM = SOCK_DGRAM; + + // the last error message on the object + public $last_error; + + // date the socket connection was created, and the date it was last used + public $date_created; + public $date_last_used; + private $sock; + private $type; + private $host; + private $port; + private $timeout; + private $context; + + // the local IP and port we'll send the request from + private $local_host; + private $local_port; + + /** + * constructor - set the port details. + * + * @param int $type the socket type + * @param string $host the IP address of the DNS server to connect to + * @param int $port the port of the DNS server to connect to + * @param int $timeout the timeout value to use for socket functions + */ + public function __construct($type, $host, $port, $timeout) { + $this->type = $type; + $this->host = $host; + $this->port = $port; + $this->timeout = $timeout; + $this->date_created = microtime(true); + } + + /** + * destructor. + */ + public function __destruct() { + $this->close(); + } + + /** + * sets the local address/port for the socket to bind to. + * + * @param string $address the local IP address to bind to + * @param mixed $port the local port to bind to, or 0 to let the socket + * function select a port + * + * @return bool + */ + public function bindAddress($address, $port = 0) { + $this->local_host = $address; + $this->local_port = $port; + + return true; + } + + /** + * opens a socket connection to the DNS server. + * + * @return bool + */ + public function open() { + // + // create a list of options for the context + // + $opts = ['socket' => []]; + + // + // bind to a local IP/port if it's set + // + if (strlen($this->local_host) > 0) { + $opts['socket']['bindto'] = $this->local_host; + + if ($this->local_port > 0) { + $opts['socket']['bindto'] .= ':' . $this->local_port; + } + } + + // + // create the context + // + $this->context = @stream_context_create($opts); + + // + // create socket + // + + switch ($this->type) { + case Net_DNS2_Socket::SOCK_STREAM: + if (Net_DNS2::isIPv4($this->host) == true) { + $this->sock = @stream_socket_client( + 'tcp://' . $this->host . ':' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } elseif (Net_DNS2::isIPv6($this->host) == true) { + $this->sock = @stream_socket_client( + 'tcp://[' . $this->host . ']:' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } else { + $this->last_error = 'invalid address type: ' . $this->host; + + return false; + } + + break; + case Net_DNS2_Socket::SOCK_DGRAM: + if (Net_DNS2::isIPv4($this->host) == true) { + $this->sock = @stream_socket_client( + 'udp://' . $this->host . ':' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } elseif (Net_DNS2::isIPv6($this->host) == true) { + $this->sock = @stream_socket_client( + 'udp://[' . $this->host . ']:' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->context + ); + } else { + $this->last_error = 'invalid address type: ' . $this->host; + + return false; + } + + break; + default: + $this->last_error = 'Invalid socket type: ' . $this->type; + + return false; + } + + if ($this->sock === false) { + $this->last_error = $errstr; + + return false; + } + + // + // set it to non-blocking and set the timeout + // + @stream_set_blocking($this->sock, 0); + @stream_set_timeout($this->sock, $this->timeout); + + return true; + } + + /** + * closes a socket connection to the DNS server. + * + * @return bool + */ + public function close() { + if (is_resource($this->sock) === true) { + @fclose($this->sock); + } + + return true; + } + + /** + * writes the given string to the DNS server socket. + * + * @param string $data a binary packed DNS packet + * + * @return bool + */ + public function write($data) { + $length = strlen($data); + + if ($length == 0) { + $this->last_error = 'empty data on write()'; + + return false; + } + + $read = null; + $write = [$this->sock]; + $except = null; + + // + // increment the date last used timestamp + // + $this->date_last_used = microtime(true); + + // + // select on write + // + $result = stream_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = 'failed on write select()'; + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on write select()'; + + return false; + } + + // + // if it's a TCP socket, then we need to packet and send the length of the + // data as the first 16bit of data. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + $s = chr($length >> 8) . chr($length); + + if (@fwrite($this->sock, $s) === false) { + $this->last_error = 'failed to fwrite() 16bit length'; + + return false; + } + } + + // + // write the data to the socket + // + $size = @fwrite($this->sock, $data); + + if (($size === false) || ($size != $length)) { + $this->last_error = 'failed to fwrite() packet'; + + return false; + } + + return true; + } + + /** + * reads a response from a DNS server. + * + * @param int &$size the size of the DNS packet read is passed back + * @param int $max_size the max data size returned + * + * @return mixed returns the data on success and false on error + */ + public function read(&$size, $max_size) { + $read = [$this->sock]; + $write = null; + $except = null; + + // + // increment the date last used timestamp + // + $this->date_last_used = microtime(true); + + // + // make sure our socket is non-blocking + // + @stream_set_blocking($this->sock, 0); + + // + // select on read + // + $result = stream_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = 'error on read select()'; + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on read select()'; + + return false; + } + + $data = ''; + $length = $max_size; + + // + // if it's a TCP socket, then the first two bytes is the length of the DNS + // packet- we need to read that off first, then use that value for the + // packet read. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + if (($data = fread($this->sock, 2)) === false) { + $this->last_error = 'failed on fread() for data length'; + + return false; + } + + if (strlen($data) == 0) { + $this->last_error = 'failed on fread() for data length'; + + return false; + } + + $length = ord($data[0]) << 8 | ord($data[1]); + + if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { + return false; + } + } + + // + // at this point, we know that there is data on the socket to be read, + // because we've already extracted the length from the first two bytes. + // + // so the easiest thing to do, is just turn off socket blocking, and + // wait for the data. + // + @stream_set_blocking($this->sock, 1); + + // + // read the data from the socket + // + $data = ''; + + // + // the streams socket is weird for TCP sockets; it doesn't seem to always + // return all the data properly; but the looping code I added broke UDP + // packets- my fault- + // + // the sockets library works much better. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + $chunk = ''; + $chunk_size = $length; + + // + // loop so we make sure we read all the data + // + while (1) { + $chunk = fread($this->sock, $chunk_size); + + if ($chunk === false) { + $this->last_error = 'failed on fread() for data'; + + return false; + } + + $data .= $chunk; + $chunk_size -= strlen($chunk); + + if (strlen($data) >= $length) { + break; + } + } + } else { + // + // if it's UDP, it's a single fixed-size frame, and the streams library + // doesn't seem to have a problem reading it. + // + $data = fread($this->sock, $length); + + if ($length === false) { + $this->last_error = 'failed on fread() for data'; + + return false; + } + } + + $size = strlen($data); + + return $data; + } } diff --git a/Net/DNS2/Socket/Sockets.php b/Net/DNS2/Socket/Sockets.php index 8977472e..e695e4c4 100644 --- a/Net/DNS2/Socket/Sockets.php +++ b/Net/DNS2/Socket/Sockets.php @@ -66,280 +66,287 @@ * @see http://pear.php.net/package/Net_DNS2 * @see Net_DNS2_Socket */ -class Net_DNS2_Socket_Sockets extends Net_DNS2_Socket -{ - /** - * opens a socket connection to the DNS server. - * - * @return bool - */ - public function open() - { - // - // create the socket - // - if (true == Net_DNS2::isIPv4($this->host)) { - $this->sock = @socket_create( - AF_INET, - $this->type, - (Net_DNS2_Socket::SOCK_STREAM == $this->type) ? SOL_TCP : SOL_UDP - ); - } elseif (true == Net_DNS2::isIPv6($this->host)) { - $this->sock = @socket_create( - AF_INET6, - $this->type, - (Net_DNS2_Socket::SOCK_STREAM == $this->type) ? SOL_TCP : SOL_UDP - ); - } else { - $this->last_error = 'invalid address type: '.$this->host; - - return false; - } - - if (false === $this->sock) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - @socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1); - - // - // bind to a local IP/port if it's set - // - if (strlen($this->local_host) > 0) { - $result = @socket_bind( - $this->sock, - $this->local_host, - ($this->local_port > 0) ? $this->local_port : null - ); - if (false === $result) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - } - - // - // mark the socket as non-blocking - // - if (false === @socket_set_nonblock($this->sock)) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - // - // connect to the socket; don't check for status here, we'll check it on the - // socket_select() call so we can handle timeouts properly - // - @socket_connect($this->sock, $this->host, $this->port); - - $read = null; - $write = [$this->sock]; - $except = null; - - // - // select on write to check if the call to connect worked - // - $result = @socket_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on write select for connect()'; - - return false; - } - - return true; - } - - /** - * closes a socket connection to the DNS server. - * - * @return bool - */ - public function close() - { - if (true === is_resource($this->sock)) { - @socket_close($this->sock); - } - - return true; - } - - /** - * writes the given string to the DNS server socket. - * - * @param string $data a binary packed DNS packet - * - * @return bool - */ - public function write($data) - { - $length = strlen($data); - if (0 == $length) { - $this->last_error = 'empty data on write()'; - - return false; - } - - $read = null; - $write = [$this->sock]; - $except = null; - - // - // select on write - // - $result = @socket_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on write select()'; - - return false; - } - - // - // if it's a TCP socket, then we need to packet and send the length of the - // data as the first 16bit of data. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - $s = chr($length >> 8).chr($length); - - if (false === @socket_write($this->sock, $s)) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - } - - // - // write the data to the socket - // - $size = @socket_write($this->sock, $data); - if ((false === $size) || ($size != $length)) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - return true; - } - - /** - * reads a response from a DNS server. - * - * @param int &$size the size of the DNS packet read is passed back - * @param mixed $max_size - * - * @return mixed returns the data on success and false on error - */ - public function read(&$size, $max_size) - { - $read = [$this->sock]; - $write = null; - $except = null; - - // - // make sure our socket is non-blocking - // - if (false === @socket_set_nonblock($this->sock)) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - // - // select on read - // - $result = @socket_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on read select()'; - - return false; - } - - $data = ''; - $length = $max_size; - - // - // if it's a TCP socket, then the first two bytes is the length of the DNS - // packet- we need to read that off first, then use that value for the - // packet read. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - if (($size = @socket_recv($this->sock, $data, 2, 0)) === false) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - $length = ord($data[0]) << 8 | ord($data[1]); - if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - return false; - } - } - - // - // at this point, we know that there is data on the socket to be read, - // because we've already extracted the length from the first two bytes. - // - // so the easiest thing to do, is just turn off socket blocking, and - // wait for the data. - // - if (false === @socket_set_block($this->sock)) { - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - // - // read the data from the socket - // - // loop while reading since some OS's (specifically Win < 2003) don't support - // MSG_WAITALL properly, so they may return with less data than is available. - // - // According to M$, XP and below don't support MSG_WAITALL at all; and there - // also seems to be some issue in 2003 and 2008 where the MSG_WAITALL is - // defined as 0, but if you actually pass 8 (which is the correct defined - // value), it works as it's supposed to- so in these cases, it's just the - // define that's incorrect- this is likely a PHP issue. - // - $data = ''; - $size = 0; - - while (1) { - $chunk_size = @socket_recv($this->sock, $chunk, $length, MSG_WAITALL); - if (false === $chunk_size) { - $size = $chunk_size; - $this->last_error = socket_strerror(socket_last_error()); - - return false; - } - - $data .= $chunk; - $size += $chunk_size; - - $length -= $chunk_size; - if (($length <= 0) || (Net_DNS2_Socket::SOCK_DGRAM == $this->type)) { - break; - } - } - - return $data; - } +class Net_DNS2_Socket_Sockets extends Net_DNS2_Socket { + /** + * opens a socket connection to the DNS server. + * + * @return bool + */ + public function open() { + // + // create the socket + // + if (Net_DNS2::isIPv4($this->host) == true) { + $this->sock = @socket_create( + AF_INET, + $this->type, + ($this->type == Net_DNS2_Socket::SOCK_STREAM) ? SOL_TCP : SOL_UDP + ); + } elseif (Net_DNS2::isIPv6($this->host) == true) { + $this->sock = @socket_create( + AF_INET6, + $this->type, + ($this->type == Net_DNS2_Socket::SOCK_STREAM) ? SOL_TCP : SOL_UDP + ); + } else { + $this->last_error = 'invalid address type: ' . $this->host; + + return false; + } + + if ($this->sock === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + @socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1); + + // + // bind to a local IP/port if it's set + // + if (strlen($this->local_host) > 0) { + $result = @socket_bind( + $this->sock, + $this->local_host, + ($this->local_port > 0) ? $this->local_port : null + ); + + if ($result === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + } + + // + // mark the socket as non-blocking + // + if (@socket_set_nonblock($this->sock) === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + // + // connect to the socket; don't check for status here, we'll check it on the + // socket_select() call so we can handle timeouts properly + // + @socket_connect($this->sock, $this->host, $this->port); + + $read = null; + $write = [$this->sock]; + $except = null; + + // + // select on write to check if the call to connect worked + // + $result = @socket_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on write select for connect()'; + + return false; + } + + return true; + } + + /** + * closes a socket connection to the DNS server. + * + * @return bool + */ + public function close() { + if (is_resource($this->sock) === true) { + @socket_close($this->sock); + } + + return true; + } + + /** + * writes the given string to the DNS server socket. + * + * @param string $data a binary packed DNS packet + * + * @return bool + */ + public function write($data) { + $length = strlen($data); + + if ($length == 0) { + $this->last_error = 'empty data on write()'; + + return false; + } + + $read = null; + $write = [$this->sock]; + $except = null; + + // + // select on write + // + $result = @socket_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on write select()'; + + return false; + } + + // + // if it's a TCP socket, then we need to packet and send the length of the + // data as the first 16bit of data. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + $s = chr($length >> 8) . chr($length); + + if (@socket_write($this->sock, $s) === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + } + + // + // write the data to the socket + // + $size = @socket_write($this->sock, $data); + + if (($size === false) || ($size != $length)) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + return true; + } + + /** + * reads a response from a DNS server. + * + * @param int &$size the size of the DNS packet read is passed back + * @param mixed $max_size + * + * @return mixed returns the data on success and false on error + */ + public function read(&$size, $max_size) { + $read = [$this->sock]; + $write = null; + $except = null; + + // + // make sure our socket is non-blocking + // + if (@socket_set_nonblock($this->sock) === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + // + // select on read + // + $result = @socket_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on read select()'; + + return false; + } + + $data = ''; + $length = $max_size; + + // + // if it's a TCP socket, then the first two bytes is the length of the DNS + // packet- we need to read that off first, then use that value for the + // packet read. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + if (($size = @socket_recv($this->sock, $data, 2, 0)) === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + $length = ord($data[0]) << 8 | ord($data[1]); + + if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { + return false; + } + } + + // + // at this point, we know that there is data on the socket to be read, + // because we've already extracted the length from the first two bytes. + // + // so the easiest thing to do, is just turn off socket blocking, and + // wait for the data. + // + if (@socket_set_block($this->sock) === false) { + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + // + // read the data from the socket + // + // loop while reading since some OS's (specifically Win < 2003) don't support + // MSG_WAITALL properly, so they may return with less data than is available. + // + // According to M$, XP and below don't support MSG_WAITALL at all; and there + // also seems to be some issue in 2003 and 2008 where the MSG_WAITALL is + // defined as 0, but if you actually pass 8 (which is the correct defined + // value), it works as it's supposed to- so in these cases, it's just the + // define that's incorrect- this is likely a PHP issue. + // + $data = ''; + $size = 0; + + while (1) { + $chunk_size = @socket_recv($this->sock, $chunk, $length, MSG_WAITALL); + + if ($chunk_size === false) { + $size = $chunk_size; + $this->last_error = socket_strerror(socket_last_error()); + + return false; + } + + $data .= $chunk; + $size += $chunk_size; + + $length -= $chunk_size; + + if (($length <= 0) || ($this->type == Net_DNS2_Socket::SOCK_DGRAM)) { + break; + } + } + + return $data; + } } /* diff --git a/Net/DNS2/Socket/Streams.php b/Net/DNS2/Socket/Streams.php index a43850fe..87f6d342 100644 --- a/Net/DNS2/Socket/Streams.php +++ b/Net/DNS2/Socket/Streams.php @@ -66,308 +66,311 @@ * @see http://pear.php.net/package/Net_DNS2 * @see Net_DNS2_Socket */ -class Net_DNS2_Socket_Streams extends Net_DNS2_Socket -{ - private $_context; - - /** - * opens a socket connection to the DNS server. - * - * @return bool - */ - public function open() - { - // - // create a list of options for the context - // - $opts = ['socket' => []]; - - // - // bind to a local IP/port if it's set - // - if (strlen($this->local_host) > 0) { - $opts['socket']['bindto'] = $this->local_host; - if ($this->local_port > 0) { - $opts['socket']['bindto'] .= ':'.$this->local_port; - } - } - - // - // create the context - // - $this->_context = @stream_context_create($opts); - - // - // create socket - // - - switch ($this->type) { - case Net_DNS2_Socket::SOCK_STREAM: - if (true == Net_DNS2::isIPv4($this->host)) { - $this->sock = @stream_socket_client( - 'tcp://'.$this->host.':'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->_context - ); - } elseif (true == Net_DNS2::isIPv6($this->host)) { - $this->sock = @stream_socket_client( - 'tcp://['.$this->host.']:'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->_context - ); - } else { - $this->last_error = 'invalid address type: '.$this->host; - - return false; - } - - break; - - case Net_DNS2_Socket::SOCK_DGRAM: - if (true == Net_DNS2::isIPv4($this->host)) { - $this->sock = @stream_socket_client( - 'udp://'.$this->host.':'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->_context - ); - } elseif (true == Net_DNS2::isIPv6($this->host)) { - $this->sock = @stream_socket_client( - 'udp://['.$this->host.']:'.$this->port, - $errno, - $errstr, - $this->timeout, - STREAM_CLIENT_CONNECT, - $this->_context - ); - } else { - $this->last_error = 'invalid address type: '.$this->host; - - return false; - } - - break; - - default: - $this->last_error = 'Invalid socket type: '.$this->type; - - return false; - } - - if (false === $this->sock) { - $this->last_error = $errstr; - - return false; - } - - // - // set it to non-blocking and set the timeout - // - @stream_set_blocking($this->sock, 0); - @stream_set_timeout($this->sock, $this->timeout); - - return true; - } - - /** - * closes a socket connection to the DNS server. - * - * @return bool - */ - public function close() - { - if (true === is_resource($this->sock)) { - @fclose($this->sock); - } - - return true; - } - - /** - * writes the given string to the DNS server socket. - * - * @param string $data a binary packed DNS packet - * - * @return bool - */ - public function write($data) - { - $length = strlen($data); - if (0 == $length) { - $this->last_error = 'empty data on write()'; - - return false; - } - - $read = null; - $write = [$this->sock]; - $except = null; - - // - // select on write - // - $result = stream_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = 'failed on write select()'; - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on write select()'; - - return false; - } - - // - // if it's a TCP socket, then we need to packet and send the length of the - // data as the first 16bit of data. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - $s = chr($length >> 8).chr($length); - - if (false === @fwrite($this->sock, $s)) { - $this->last_error = 'failed to fwrite() 16bit length'; - - return false; - } - } - - // - // write the data to the socket - // - $size = @fwrite($this->sock, $data); - if ((false === $size) || ($size != $length)) { - $this->last_error = 'failed to fwrite() packet'; - - return false; - } - - return true; - } - - /** - * reads a response from a DNS server. - * - * @param int &$size the size of the DNS packet read is passed back - * @param mixed $max_size - * - * @return mixed returns the data on success and false on error - */ - public function read(&$size, $max_size) - { - $read = [$this->sock]; - $write = null; - $except = null; - - // - // make sure our socket is non-blocking - // - @stream_set_blocking($this->sock, 0); - - // - // select on read - // - $result = stream_select($read, $write, $except, $this->timeout); - if (false === $result) { - $this->last_error = 'error on read select()'; - - return false; - } - if (0 == $result) { - $this->last_error = 'timeout on read select()'; - - return false; - } - - $data = ''; - $length = $max_size; - - // - // if it's a TCP socket, then the first two bytes is the length of the DNS - // packet- we need to read that off first, then use that value for the - // packet read. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - if (($data = fread($this->sock, 2)) === false) { - $this->last_error = 'failed on fread() for data length'; - - return false; - } - - $length = ord($data[0]) << 8 | ord($data[1]); - if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { - return false; - } - } - - // - // at this point, we know that there is data on the socket to be read, - // because we've already extracted the length from the first two bytes. - // - // so the easiest thing to do, is just turn off socket blocking, and - // wait for the data. - // - @stream_set_blocking($this->sock, 1); - - // - // read the data from the socket - // - $data = ''; - - // - // the streams socket is weird for TCP sockets; it doesn't seem to always - // return all the data properly; but the looping code I added broke UDP - // packets- my fault- - // - // the sockets library works much better. - // - if (Net_DNS2_Socket::SOCK_STREAM == $this->type) { - $chunk = ''; - $chunk_size = $length; - - // - // loop so we make sure we read all the data - // - while (1) { - $chunk = fread($this->sock, $chunk_size); - if (false === $chunk) { - $this->last_error = 'failed on fread() for data'; - - return false; - } - - $data .= $chunk; - $chunk_size -= strlen($chunk); - - if (strlen($data) >= $length) { - break; - } - } - } else { - // - // if it's UDP, it's a single fixed-size frame, and the streams library - // doesn't seem to have a problem reading it. - // - $data = fread($this->sock, $length); - if (false === $length) { - $this->last_error = 'failed on fread() for data'; - - return false; - } - } - - $size = strlen($data); - - return $data; - } +class Net_DNS2_Socket_Streams extends Net_DNS2_Socket { + private $_context; + + /** + * opens a socket connection to the DNS server. + * + * @return bool + */ + public function open() { + // + // create a list of options for the context + // + $opts = ['socket' => []]; + + // + // bind to a local IP/port if it's set + // + if (strlen($this->local_host) > 0) { + $opts['socket']['bindto'] = $this->local_host; + + if ($this->local_port > 0) { + $opts['socket']['bindto'] .= ':' . $this->local_port; + } + } + + // + // create the context + // + $this->_context = @stream_context_create($opts); + + // + // create socket + // + + switch ($this->type) { + case Net_DNS2_Socket::SOCK_STREAM: + if (Net_DNS2::isIPv4($this->host) == true) { + $this->sock = @stream_socket_client( + 'tcp://' . $this->host . ':' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } elseif (Net_DNS2::isIPv6($this->host) == true) { + $this->sock = @stream_socket_client( + 'tcp://[' . $this->host . ']:' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } else { + $this->last_error = 'invalid address type: ' . $this->host; + + return false; + } + + break; + case Net_DNS2_Socket::SOCK_DGRAM: + if (Net_DNS2::isIPv4($this->host) == true) { + $this->sock = @stream_socket_client( + 'udp://' . $this->host . ':' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } elseif (Net_DNS2::isIPv6($this->host) == true) { + $this->sock = @stream_socket_client( + 'udp://[' . $this->host . ']:' . $this->port, + $errno, + $errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->_context + ); + } else { + $this->last_error = 'invalid address type: ' . $this->host; + + return false; + } + + break; + default: + $this->last_error = 'Invalid socket type: ' . $this->type; + + return false; + } + + if ($this->sock === false) { + $this->last_error = $errstr; + + return false; + } + + // + // set it to non-blocking and set the timeout + // + @stream_set_blocking($this->sock, 0); + @stream_set_timeout($this->sock, $this->timeout); + + return true; + } + + /** + * closes a socket connection to the DNS server. + * + * @return bool + */ + public function close() { + if (is_resource($this->sock) === true) { + @fclose($this->sock); + } + + return true; + } + + /** + * writes the given string to the DNS server socket. + * + * @param string $data a binary packed DNS packet + * + * @return bool + */ + public function write($data) { + $length = strlen($data); + + if ($length == 0) { + $this->last_error = 'empty data on write()'; + + return false; + } + + $read = null; + $write = [$this->sock]; + $except = null; + + // + // select on write + // + $result = stream_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = 'failed on write select()'; + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on write select()'; + + return false; + } + + // + // if it's a TCP socket, then we need to packet and send the length of the + // data as the first 16bit of data. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + $s = chr($length >> 8) . chr($length); + + if (@fwrite($this->sock, $s) === false) { + $this->last_error = 'failed to fwrite() 16bit length'; + + return false; + } + } + + // + // write the data to the socket + // + $size = @fwrite($this->sock, $data); + + if (($size === false) || ($size != $length)) { + $this->last_error = 'failed to fwrite() packet'; + + return false; + } + + return true; + } + + /** + * reads a response from a DNS server. + * + * @param int &$size the size of the DNS packet read is passed back + * @param mixed $max_size + * + * @return mixed returns the data on success and false on error + */ + public function read(&$size, $max_size) { + $read = [$this->sock]; + $write = null; + $except = null; + + // + // make sure our socket is non-blocking + // + @stream_set_blocking($this->sock, 0); + + // + // select on read + // + $result = stream_select($read, $write, $except, $this->timeout); + + if ($result === false) { + $this->last_error = 'error on read select()'; + + return false; + } + + if ($result == 0) { + $this->last_error = 'timeout on read select()'; + + return false; + } + + $data = ''; + $length = $max_size; + + // + // if it's a TCP socket, then the first two bytes is the length of the DNS + // packet- we need to read that off first, then use that value for the + // packet read. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + if (($data = fread($this->sock, 2)) === false) { + $this->last_error = 'failed on fread() for data length'; + + return false; + } + + $length = ord($data[0]) << 8 | ord($data[1]); + + if ($length < Net_DNS2_Lookups::DNS_HEADER_SIZE) { + return false; + } + } + + // + // at this point, we know that there is data on the socket to be read, + // because we've already extracted the length from the first two bytes. + // + // so the easiest thing to do, is just turn off socket blocking, and + // wait for the data. + // + @stream_set_blocking($this->sock, 1); + + // + // read the data from the socket + // + $data = ''; + + // + // the streams socket is weird for TCP sockets; it doesn't seem to always + // return all the data properly; but the looping code I added broke UDP + // packets- my fault- + // + // the sockets library works much better. + // + if ($this->type == Net_DNS2_Socket::SOCK_STREAM) { + $chunk = ''; + $chunk_size = $length; + + // + // loop so we make sure we read all the data + // + while (1) { + $chunk = fread($this->sock, $chunk_size); + + if ($chunk === false) { + $this->last_error = 'failed on fread() for data'; + + return false; + } + + $data .= $chunk; + $chunk_size -= strlen($chunk); + + if (strlen($data) >= $length) { + break; + } + } + } else { + // + // if it's UDP, it's a single fixed-size frame, and the streams library + // doesn't seem to have a problem reading it. + // + $data = fread($this->sock, $length); + + if ($length === false) { + $this->last_error = 'failed on fread() for data'; + + return false; + } + } + + $size = strlen($data); + + return $data; + } } /* diff --git a/Net/DNS2/Updater.php b/Net/DNS2/Updater.php index 0e9eba55..756fb889 100644 --- a/Net/DNS2/Updater.php +++ b/Net/DNS2/Updater.php @@ -29,557 +29,545 @@ * Generally, query (recursive) lookups are done against caching server, while * update requests are done against authoritative servers. */ -class Net_DNS2_Updater extends Net_DNS2 -{ - // a Net_DNS2_Packet_Request object used for the update request - private $_packet; - - /** - * Constructor - builds a new Net_DNS2_Updater objected used for doing - * dynamic DNS updates. - * - * @param string $zone the domain name to use for DNS updates - * @param mixed $options an array of config options or null - * - * @throws Net_DNS2_Exception - */ - public function __construct($zone, ?array $options = null) - { - parent::__construct($options); - - // - // create the packet - // - $this->_packet = new Net_DNS2_Packet_Request( - strtolower(trim($zone, " \n\r\t.")), - 'SOA', - 'IN' - ); - - // - // make sure the opcode on the packet is set to UPDATE - // - $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_UPDATE; - } - - /** - * add a signature to the request for authentication. - * - * @param string $keyname the key name to use for the TSIG RR - * @param string $signature the key to sign the request - * - * @return bool - * - * @see Net_DNS2::signTSIG() - * @deprecated function deprecated in 1.1.0 - */ - public function signature($keyname, $signature) - { - return $this->signTSIG($keyname, $signature); - } - - /** - * 2.5.1 - Add To An RRset. - * - * RRs are added to the Update Section whose NAME, TYPE, TTL, RDLENGTH - * and RDATA are those being added, and CLASS is the same as the zone - * class. Any duplicate RRs will be silently ignored by the primary - * master. - * - * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be added to the zone - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function add(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.5.4 - Delete An RR From An RRset. - * - * RRs to be deleted are added to the Update Section. The NAME, TYPE, - * RDLENGTH and RDATA must match the RR being deleted. TTL must be - * specified as zero (0) and will otherwise be ignored by the primary - * master. CLASS must be specified as NONE to distinguish this from an - * RR addition. If no such RRs exist, then this Update RR will be - * silently ignored by the primary master. - * - * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be deleted from the zone - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function delete(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - - $rr->ttl = 0; - $rr->class = 'NONE'; - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.5.2 - Delete An RRset. - * - * One RR is added to the Update Section whose NAME and TYPE are those - * of the RRset to be deleted. TTL must be specified as zero (0) and is - * otherwise not used by the primary master. CLASS must be specified as - * ANY. RDLENGTH must be zero (0) and RDATA must therefore be empty. - * If no such RRset exists, then this Update RR will be silently ignored - * by the primary master - * - * @param string $name the RR name to be removed from the zone - * @param string $type the RR type to be removed from the zone - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function deleteAny($name, $type) - { - $this->_checkName($name); - - $class = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - if (!isset($class)) { - throw new Net_DNS2_Exception( - 'unknown or un-supported resource record type: '.$type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - $rr = new $class(); - - $rr->name = $name; - $rr->ttl = 0; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.5.3 - Delete All RRsets From A Name. - * - * One RR is added to the Update Section whose NAME is that of the name - * to be cleansed of RRsets. TYPE must be specified as ANY. TTL must - * be specified as zero (0) and is otherwise not used by the primary - * master. CLASS must be specified as ANY. RDLENGTH must be zero (0) - * and RDATA must therefore be empty. If no such RRsets exist, then - * this Update RR will be silently ignored by the primary master. - * - * @param string $name the RR name to be removed from the zone - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function deleteAll($name) - { - $this->_checkName($name); - - // - // the Net_DNS2_RR_ANY class is just an empty stub class used for these - // cases only - // - $rr = new Net_DNS2_RR_ANY(); - - $rr->name = $name; - $rr->ttl = 0; - $rr->type = 'ANY'; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "update" section - // - if (!in_array($rr, $this->_packet->authority)) { - $this->_packet->authority[] = $rr; - } - - return true; - } - - /** - * 2.4.1 - RRset Exists (Value Independent). - * - * At least one RR with a specified NAME and TYPE (in the zone and class - * specified in the Zone Section) must exist. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME and TYPE are equal to that of the zone RRset whose - * existence is required. RDLENGTH is zero and RDATA is therefore - * empty. CLASS must be specified as ANY to differentiate this - * condition from that of an actual RR whose RDLENGTH is naturally zero - * (0) (e.g., NULL). TTL is specified as zero (0). - * - * @param string $name the RR name for the prerequisite - * @param string $type the RR type for the prerequisite - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function checkExists($name, $type) - { - $this->_checkName($name); - - $class = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - if (!isset($class)) { - throw new Net_DNS2_Exception( - 'unknown or un-supported resource record type: '.$type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - $rr = new $class(); - - $rr->name = $name; - $rr->ttl = 0; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.2 - RRset Exists (Value Dependent). - * - * A set of RRs with a specified NAME and TYPE exists and has the same - * members with the same RDATAs as the RRset specified here in this - * section. While RRset ordering is undefined and therefore not - * significant to this comparison, the sets be identical in their - * extent. - * - * For this prerequisite, a requester adds to the section an entire - * RRset whose preexistence is required. NAME and TYPE are that of the - * RRset being denoted. CLASS is that of the zone. TTL must be - * specified as zero (0) and is ignored when comparing RRsets for - * identity. - * - * @param Net_DNS2_RR $rr the RR object to be used as a prerequisite - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function checkValueExists(Net_DNS2_RR $rr) - { - $this->_checkName($rr->name); - - $rr->ttl = 0; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.3 - RRset Does Not Exist. - * - * No RRs with a specified NAME and TYPE (in the zone and class denoted - * by the Zone Section) can exist. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME and TYPE are equal to that of the RRset whose nonexistence - * is required. The RDLENGTH of this record is zero (0), and RDATA - * field is therefore empty. CLASS must be specified as NONE in order - * to distinguish this condition from a valid RR whose RDLENGTH is - * naturally zero (0) (for example, the NULL RR). TTL must be specified - * as zero (0). - * - * @param string $name the RR name for the prerequisite - * @param string $type the RR type for the prerequisite - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function checkNotExists($name, $type) - { - $this->_checkName($name); - - $class = Net_DNS2_Lookups::$rr_types_id_to_class[ - Net_DNS2_Lookups::$rr_types_by_name[$type] - ]; - if (!isset($class)) { - throw new Net_DNS2_Exception( - 'unknown or un-supported resource record type: '.$type, - Net_DNS2_Lookups::E_RR_INVALID - ); - } - - $rr = new $class(); - - $rr->name = $name; - $rr->ttl = 0; - $rr->class = 'NONE'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.4 - Name Is In Use. - * - * Name is in use. At least one RR with a specified NAME (in the zone - * and class specified by the Zone Section) must exist. Note that this - * prerequisite is NOT satisfied by empty nonterminals. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME is equal to that of the name whose ownership of an RR is - * required. RDLENGTH is zero and RDATA is therefore empty. CLASS must - * be specified as ANY to differentiate this condition from that of an - * actual RR whose RDLENGTH is naturally zero (0) (e.g., NULL). TYPE - * must be specified as ANY to differentiate this case from that of an - * RRset existence test. TTL is specified as zero (0). - * - * @param string $name the RR name for the prerequisite - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function checkNameInUse($name) - { - $this->_checkName($name); - - // - // the Net_DNS2_RR_ANY class is just an empty stub class used for these - // cases only - // - $rr = new Net_DNS2_RR_ANY(); - - $rr->name = $name; - $rr->ttl = 0; - $rr->type = 'ANY'; - $rr->class = 'ANY'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * 2.4.5 - Name Is Not In Use. - * - * Name is not in use. No RR of any type is owned by a specified NAME. - * Note that this prerequisite IS satisfied by empty nonterminals. - * - * For this prerequisite, a requester adds to the section a single RR - * whose NAME is equal to that of the name whose nonownership of any RRs - * is required. RDLENGTH is zero and RDATA is therefore empty. CLASS - * must be specified as NONE. TYPE must be specified as ANY. TTL must - * be specified as zero (0). - * - * @param string $name the RR name for the prerequisite - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function checkNameNotInUse($name) - { - $this->_checkName($name); - - // - // the Net_DNS2_RR_ANY class is just an empty stub class used for these - // cases only - // - $rr = new Net_DNS2_RR_ANY(); - - $rr->name = $name; - $rr->ttl = 0; - $rr->type = 'ANY'; - $rr->class = 'NONE'; - $rr->rdlength = -1; - $rr->rdata = ''; - - // - // add the RR to the "prerequisite" section - // - if (!in_array($rr, $this->_packet->answer)) { - $this->_packet->answer[] = $rr; - } - - return true; - } - - /** - * returns the current internal packet object. - * - * @return Net_DNS2_Packet_Request - */ - public function packet() - { - // - // take a copy - // - $p = $this->_packet; - - // - // check for an authentication method; either TSIG or SIG - // - if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $p->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $p->header->qdcount = cacti_sizeof($p->question); - $p->header->ancount = cacti_sizeof($p->answer); - $p->header->nscount = cacti_sizeof($p->authority); - $p->header->arcount = cacti_sizeof($p->additional); - - return $p; - } - - /** - * executes the update request with the object information. - * - * @param Net_DNS2_Packet_Response &$response ref to the response object - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - public function update(&$response = null) - { - // - // make sure we have some name servers set - // - $this->checkServers(Net_DNS2::RESOLV_CONF); - - // - // check for an authentication method; either TSIG or SIG - // - if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) - || ($this->auth_signature instanceof Net_DNS2_RR_SIG) - ) { - $this->_packet->additional[] = $this->auth_signature; - } - - // - // update the counts - // - $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); - $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); - $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); - $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); - - // - // make sure we have some data to send - // - if ((0 == $this->_packet->header->qdcount) - || (0 == $this->_packet->header->nscount) - ) { - throw new Net_DNS2_Exception( - 'empty headers- nothing to send!', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - // - // send the packet and get back the response - // - $response = $this->sendPacket($this->_packet, $this->use_tcp); - - // - // clear the internal packet so if we make another request, we don't have - // old data being sent. - // - $this->_packet->reset(); - - // - // for updates, we just need to know it worked- we don't actually need to - // return the response object - // - return true; - } - - /** - * checks that the given name matches the name for the zone we're updating. - * - * @param string $name the name to be checked - * - * @return bool - * - * @throws Net_DNS2_Exception - */ - private function _checkName($name) - { - if (!preg_match('/'.$this->_packet->question[0]->qname.'$/', $name)) { - throw new Net_DNS2_Exception( - 'name provided ('.$name.') does not match zone name (' - .$this->_packet->question[0]->qname.')', - Net_DNS2_Lookups::E_PACKET_INVALID - ); - } - - return true; - } +class Net_DNS2_Updater extends Net_DNS2 { + // a Net_DNS2_Packet_Request object used for the update request + private $_packet; + + /** + * Constructor - builds a new Net_DNS2_Updater objected used for doing + * dynamic DNS updates. + * + * @param string $zone the domain name to use for DNS updates + * @param mixed $options an array of config options or null + * + * @throws Net_DNS2_Exception + */ + public function __construct($zone, ?array $options = null) { + parent::__construct($options); + + // + // create the packet + // + $this->_packet = new Net_DNS2_Packet_Request( + strtolower(trim($zone, " \n\r\t.")), + 'SOA', + 'IN' + ); + + // + // make sure the opcode on the packet is set to UPDATE + // + $this->_packet->header->opcode = Net_DNS2_Lookups::OPCODE_UPDATE; + } + + /** + * add a signature to the request for authentication. + * + * @param string $keyname the key name to use for the TSIG RR + * @param string $signature the key to sign the request + * + * @return bool + * + * @see Net_DNS2::signTSIG() + * @deprecated function deprecated in 1.1.0 + */ + public function signature($keyname, $signature) { + return $this->signTSIG($keyname, $signature); + } + + /** + * 2.5.1 - Add To An RRset. + * + * RRs are added to the Update Section whose NAME, TYPE, TTL, RDLENGTH + * and RDATA are those being added, and CLASS is the same as the zone + * class. Any duplicate RRs will be silently ignored by the primary + * master. + * + * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be added to the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function add(Net_DNS2_RR $rr) { + $this->_checkName($rr->name); + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority, true)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.5.4 - Delete An RR From An RRset. + * + * RRs to be deleted are added to the Update Section. The NAME, TYPE, + * RDLENGTH and RDATA must match the RR being deleted. TTL must be + * specified as zero (0) and will otherwise be ignored by the primary + * master. CLASS must be specified as NONE to distinguish this from an + * RR addition. If no such RRs exist, then this Update RR will be + * silently ignored by the primary master. + * + * @param Net_DNS2_RR $rr the Net_DNS2_RR object to be deleted from the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function delete(Net_DNS2_RR $rr) { + $this->_checkName($rr->name); + + $rr->ttl = 0; + $rr->class = 'NONE'; + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority, true)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.5.2 - Delete An RRset. + * + * One RR is added to the Update Section whose NAME and TYPE are those + * of the RRset to be deleted. TTL must be specified as zero (0) and is + * otherwise not used by the primary master. CLASS must be specified as + * ANY. RDLENGTH must be zero (0) and RDATA must therefore be empty. + * If no such RRset exists, then this Update RR will be silently ignored + * by the primary master + * + * @param string $name the RR name to be removed from the zone + * @param string $type the RR type to be removed from the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function deleteAny($name, $type) { + $this->_checkName($name); + + $class = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + + if (!isset($class)) { + throw new Net_DNS2_Exception( + 'unknown or un-supported resource record type: ' . $type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + $rr = new $class(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority, true)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.5.3 - Delete All RRsets From A Name. + * + * One RR is added to the Update Section whose NAME is that of the name + * to be cleansed of RRsets. TYPE must be specified as ANY. TTL must + * be specified as zero (0) and is otherwise not used by the primary + * master. CLASS must be specified as ANY. RDLENGTH must be zero (0) + * and RDATA must therefore be empty. If no such RRsets exist, then + * this Update RR will be silently ignored by the primary master. + * + * @param string $name the RR name to be removed from the zone + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function deleteAll($name) { + $this->_checkName($name); + + // + // the Net_DNS2_RR_ANY class is just an empty stub class used for these + // cases only + // + $rr = new Net_DNS2_RR_ANY(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->type = 'ANY'; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "update" section + // + if (!in_array($rr, $this->_packet->authority, true)) { + $this->_packet->authority[] = $rr; + } + + return true; + } + + /** + * 2.4.1 - RRset Exists (Value Independent). + * + * At least one RR with a specified NAME and TYPE (in the zone and class + * specified in the Zone Section) must exist. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME and TYPE are equal to that of the zone RRset whose + * existence is required. RDLENGTH is zero and RDATA is therefore + * empty. CLASS must be specified as ANY to differentiate this + * condition from that of an actual RR whose RDLENGTH is naturally zero + * (0) (e.g., NULL). TTL is specified as zero (0). + * + * @param string $name the RR name for the prerequisite + * @param string $type the RR type for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkExists($name, $type) { + $this->_checkName($name); + + $class = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + + if (!isset($class)) { + throw new Net_DNS2_Exception( + 'unknown or un-supported resource record type: ' . $type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + $rr = new $class(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer, true)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.2 - RRset Exists (Value Dependent). + * + * A set of RRs with a specified NAME and TYPE exists and has the same + * members with the same RDATAs as the RRset specified here in this + * section. While RRset ordering is undefined and therefore not + * significant to this comparison, the sets be identical in their + * extent. + * + * For this prerequisite, a requester adds to the section an entire + * RRset whose preexistence is required. NAME and TYPE are that of the + * RRset being denoted. CLASS is that of the zone. TTL must be + * specified as zero (0) and is ignored when comparing RRsets for + * identity. + * + * @param Net_DNS2_RR $rr the RR object to be used as a prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkValueExists(Net_DNS2_RR $rr) { + $this->_checkName($rr->name); + + $rr->ttl = 0; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer, true)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.3 - RRset Does Not Exist. + * + * No RRs with a specified NAME and TYPE (in the zone and class denoted + * by the Zone Section) can exist. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME and TYPE are equal to that of the RRset whose nonexistence + * is required. The RDLENGTH of this record is zero (0), and RDATA + * field is therefore empty. CLASS must be specified as NONE in order + * to distinguish this condition from a valid RR whose RDLENGTH is + * naturally zero (0) (for example, the NULL RR). TTL must be specified + * as zero (0). + * + * @param string $name the RR name for the prerequisite + * @param string $type the RR type for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkNotExists($name, $type) { + $this->_checkName($name); + + $class = Net_DNS2_Lookups::$rr_types_id_to_class[ + Net_DNS2_Lookups::$rr_types_by_name[$type] + ]; + + if (!isset($class)) { + throw new Net_DNS2_Exception( + 'unknown or un-supported resource record type: ' . $type, + Net_DNS2_Lookups::E_RR_INVALID + ); + } + + $rr = new $class(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->class = 'NONE'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer, true)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.4 - Name Is In Use. + * + * Name is in use. At least one RR with a specified NAME (in the zone + * and class specified by the Zone Section) must exist. Note that this + * prerequisite is NOT satisfied by empty nonterminals. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME is equal to that of the name whose ownership of an RR is + * required. RDLENGTH is zero and RDATA is therefore empty. CLASS must + * be specified as ANY to differentiate this condition from that of an + * actual RR whose RDLENGTH is naturally zero (0) (e.g., NULL). TYPE + * must be specified as ANY to differentiate this case from that of an + * RRset existence test. TTL is specified as zero (0). + * + * @param string $name the RR name for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkNameInUse($name) { + $this->_checkName($name); + + // + // the Net_DNS2_RR_ANY class is just an empty stub class used for these + // cases only + // + $rr = new Net_DNS2_RR_ANY(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->type = 'ANY'; + $rr->class = 'ANY'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer, true)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * 2.4.5 - Name Is Not In Use. + * + * Name is not in use. No RR of any type is owned by a specified NAME. + * Note that this prerequisite IS satisfied by empty nonterminals. + * + * For this prerequisite, a requester adds to the section a single RR + * whose NAME is equal to that of the name whose nonownership of any RRs + * is required. RDLENGTH is zero and RDATA is therefore empty. CLASS + * must be specified as NONE. TYPE must be specified as ANY. TTL must + * be specified as zero (0). + * + * @param string $name the RR name for the prerequisite + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function checkNameNotInUse($name) { + $this->_checkName($name); + + // + // the Net_DNS2_RR_ANY class is just an empty stub class used for these + // cases only + // + $rr = new Net_DNS2_RR_ANY(); + + $rr->name = $name; + $rr->ttl = 0; + $rr->type = 'ANY'; + $rr->class = 'NONE'; + $rr->rdlength = -1; + $rr->rdata = ''; + + // + // add the RR to the "prerequisite" section + // + if (!in_array($rr, $this->_packet->answer, true)) { + $this->_packet->answer[] = $rr; + } + + return true; + } + + /** + * returns the current internal packet object. + * + * @return Net_DNS2_Packet_Request + */ + public function packet() { + // + // take a copy + // + $p = $this->_packet; + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $p->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $p->header->qdcount = cacti_sizeof($p->question); + $p->header->ancount = cacti_sizeof($p->answer); + $p->header->nscount = cacti_sizeof($p->authority); + $p->header->arcount = cacti_sizeof($p->additional); + + return $p; + } + + /** + * executes the update request with the object information. + * + * @param Net_DNS2_Packet_Response &$response ref to the response object + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + public function update(&$response = null) { + // + // make sure we have some name servers set + // + $this->checkServers(Net_DNS2::RESOLV_CONF); + + // + // check for an authentication method; either TSIG or SIG + // + if (($this->auth_signature instanceof Net_DNS2_RR_TSIG) + || ($this->auth_signature instanceof Net_DNS2_RR_SIG) + ) { + $this->_packet->additional[] = $this->auth_signature; + } + + // + // update the counts + // + $this->_packet->header->qdcount = cacti_sizeof($this->_packet->question); + $this->_packet->header->ancount = cacti_sizeof($this->_packet->answer); + $this->_packet->header->nscount = cacti_sizeof($this->_packet->authority); + $this->_packet->header->arcount = cacti_sizeof($this->_packet->additional); + + // + // make sure we have some data to send + // + if (($this->_packet->header->qdcount == 0) + || ($this->_packet->header->nscount == 0) + ) { + throw new Net_DNS2_Exception( + 'empty headers- nothing to send!', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + // + // send the packet and get back the response + // + $response = $this->sendPacket($this->_packet, $this->use_tcp); + + // + // clear the internal packet so if we make another request, we don't have + // old data being sent. + // + $this->_packet->reset(); + + // + // for updates, we just need to know it worked- we don't actually need to + // return the response object + // + return true; + } + + /** + * checks that the given name matches the name for the zone we're updating. + * + * @param string $name the name to be checked + * + * @return bool + * + * @throws Net_DNS2_Exception + */ + private function _checkName($name) { + if (!preg_match('/' . $this->_packet->question[0]->qname . '$/', $name)) { + throw new Net_DNS2_Exception( + 'name provided (' . $name . ') does not match zone name (' + . $this->_packet->question[0]->qname . ')', + Net_DNS2_Lookups::E_PACKET_INVALID + ); + } + + return true; + } } diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..67c7e6bd --- /dev/null +++ b/composer.json @@ -0,0 +1,16 @@ +{ + "name": "cacti/plugin-mactrack", + "description": "MacTrack plugin for Cacti - tooling helpers", + "type": "library", + "require": {}, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0", + "jakub-onderka/php-parallel-lint": "^1.0" + }, + "scripts": { + "phpcsfixer": "vendor/bin/php-cs-fixer fix", + "lint": "vendor/bin/parallel-lint --exclude include/vendor ./cacti/plugins/mactrack" + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/includes/database.php b/includes/database.php index 1dfe4350..1e5f6c4e 100644 --- a/includes/database.php +++ b/includes/database.php @@ -23,1508 +23,1509 @@ +-------------------------------------------------------------------------+ */ -function mactrack_database_upgrade() -{ - global $database_default; +function mactrack_database_upgrade() { + global $database_default; - if (mactrack_db_key_exists('mac_track_devices', 'device_id_UNIQUE')) { - db_execute('ALTER TABLE `mac_track_devices` DROP KEY device_id_UNIQUE'); - } + if (mactrack_db_key_exists('mac_track_devices', 'device_id_UNIQUE')) { + db_execute('ALTER TABLE `mac_track_devices` DROP KEY device_id_UNIQUE'); + } - if (mactrack_db_key_exists('mac_track_device_types', 'device_type_id_UNIQUE')) { - db_execute('ALTER TABLE `mac_track_device_types` DROP KEY `device_type_id_UNIQUE`'); - } + if (mactrack_db_key_exists('mac_track_device_types', 'device_type_id_UNIQUE')) { + db_execute('ALTER TABLE `mac_track_device_types` DROP KEY `device_type_id_UNIQUE`'); + } - if (mactrack_db_key_exists('mac_track_devices', 'device_id')) { - db_execute('ALTER TABLE `mac_track_devices` + if (mactrack_db_key_exists('mac_track_devices', 'device_id')) { + db_execute('ALTER TABLE `mac_track_devices` DROP PRIMARY KEY, ADD PRIMARY KEY (device_id), DROP INDEX device_id, ADD UNIQUE INDEX hostname_snmp_port (hostname, snmp_port)'); - } + } - if (mactrack_db_key_exists('mac_track_device_types', 'device_type_id')) { - db_execute('ALTER TABLE `mac_track_device_types` + if (mactrack_db_key_exists('mac_track_device_types', 'device_type_id')) { + db_execute('ALTER TABLE `mac_track_device_types` DROP PRIMARY KEY, ADD PRIMARY KEY (device_type_id), DROP INDEX device_type_id, ADD UNIQUE INDEX snmp_info (`sysDescr_match`,`sysObjectID_match`,`device_type`)'); - } - - mactrack_add_column( - 'mac_track_interfaces', - 'ifHighSpeed', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifHighSpeed` int(10) unsigned NOT NULL default '0' AFTER `ifSpeed`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifDuplex', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifDuplex` int(10) unsigned NOT NULL default '0' AFTER `ifHighSpeed`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInDiscards', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifInDiscards` int(10) unsigned NOT NULL default '0' AFTER `ifOutErrors`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInErrors', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifInErrors` int(10) unsigned NOT NULL default '0' AFTER `int_ifInDiscards`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInUnknownProtos', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifInUnknownProtos` int(10) unsigned NOT NULL default '0' AFTER `int_ifInErrors`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifOutDiscards', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifOutDiscards` int(10) unsigned NOT NULL default '0' AFTER `int_ifInUnknownProtos`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifOutErrors', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifOutErrors` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutDiscards`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'host_id', - "ALTER TABLE `mac_track_devices` ADD COLUMN `host_id` int(10) unsigned NOT NULL default '0' AFTER `device_id`" - ); - - mactrack_add_column( - 'mac_track_macwatch', - 'date_last_notif', - "ALTER TABLE `mac_track_macwatch` ADD COLUMN `date_last_notif` TIMESTAMP DEFAULT '0000-00-00 00:00:00' AFTER `date_last_seen`" - ); - - mactrack_execute_sql('Add length to Device Types Match Fields', "ALTER TABLE `mac_track_device_types` MODIFY COLUMN `sysDescr_match` VARCHAR(100) NOT NULL default '', MODIFY COLUMN `sysObjectID_match` VARCHAR(100) NOT NULL default ''"); - - mactrack_execute_sql('Correct a Scanning Function Bug', "DELETE FROM mac_track_scanning_functions WHERE scanning_function='Not Applicable - Hub/Switch'"); - - mactrack_add_column( - 'mac_track_devices', - 'host_id', - "ALTER TABLE `mac_track_devices` ADD COLUMN `host_id` INTEGER UNSIGNED NOT NULL default '0' AFTER `device_id`" - ); - - mactrack_add_index( - 'mac_track_devices', - 'host_id', - 'ALTER TABLE `mac_track_devices` ADD INDEX `host_id`(`host_id`)' - ); - - mactrack_add_index( - 'mac_track_ports', - 'scan_date', - 'ALTER TABLE `mac_track_ports` ADD INDEX `scan_date` USING BTREE(`scan_date`)' - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'sysUptime', - "ALTER TABLE mac_track_interfaces ADD COLUMN `sysUptime` int(10) unsigned NOT NULL default '0' AFTER `device_id`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifInOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInOctets` int(10) unsigned NOT NULL default '0' AFTER `vlan_trunk_status`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifOutOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutOctets` int(10) unsigned NOT NULL default '0' AFTER `ifInOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifHCInOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifHCInOctets` bigint(20) unsigned NOT NULL default '0' AFTER `ifOutOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifHCOutOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifHCOutOctets` bigint(20) unsigned NOT NULL default '0' AFTER `ifHCInOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifInUcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifHCOutOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifOutUcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifInUcastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifInMulticastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifOutUcastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifOutMulticastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifInMulticastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifInBroadcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifOutMulticastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifOutBroadcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifInBroadcastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'inBound', - "ALTER TABLE mac_track_interfaces ADD COLUMN `inBound` double NOT NULL default '0' AFTER `ifOutErrors`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'outBound', - "ALTER TABLE mac_track_interfaces ADD COLUMN `outBound` double NOT NULL default '0' AFTER `inBound`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInOctets` int(10) unsigned NOT NULL default '0' AFTER `outBound`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifOutOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutOctets` int(10) unsigned NOT NULL default '0' AFTER `int_ifInOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifHCInOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifHCInOctets` bigint(20) unsigned NOT NULL default '0' AFTER `int_ifOutOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifHCOutOctets', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifHCOutOctets` bigint(20) unsigned NOT NULL default '0' AFTER `int_ifHCInOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInUcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifHCOutOctets`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifOutUcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInUcastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInMulticastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutUcastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifOutMulticastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInMulticastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifInBroadcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutMulticastPkts`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'int_ifOutBroadcastPkts', - "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInBroadcastPkts`" - ); - - if (!mactrack_db_key_exists('mac_track_ports', 'site_id_device_id')) { - db_execute('ALTER TABLE `mac_track_ports` ADD INDEX `site_id_device_id`(`site_id`, `device_id`);'); - } - - // new for 2.1.2 - // SNMP V3 - mactrack_add_column( - 'mac_track_devices', - 'term_type', - "ALTER TABLE `mac_track_devices` ADD COLUMN `term_type` tinyint(11) NOT NULL default '1' AFTER `scan_type`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'user_name', - 'ALTER TABLE `mac_track_devices` ADD COLUMN `user_name` varchar(40) default NULL AFTER `term_type`' - ); - - mactrack_add_column( - 'mac_track_devices', - 'user_password', - 'ALTER TABLE `mac_track_devices` ADD COLUMN `user_password` varchar(40) default NULL AFTER `user_name`' - ); - - mactrack_add_column( - 'mac_track_devices', - 'private_key_path', - "ALTER TABLE `mac_track_devices` ADD COLUMN `private_key_path` varchar(128) default '' AFTER `user_password`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_options', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_options` int(10) unsigned NOT NULL default '0' AFTER `private_key_path`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_username', - 'ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_username` varchar(50) default NULL AFTER `snmp_status`' - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_password', - 'ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_password` varchar(50) default NULL AFTER `snmp_username`' - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_auth_protocol', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_auth_protocol` char(5) default '' AFTER `snmp_password`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_priv_passphrase', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_priv_passphrase` varchar(200) default '' AFTER `snmp_auth_protocol`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_priv_protocol', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_priv_protocol` char(6) default '' AFTER `snmp_priv_passphrase`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_context', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_context` varchar(64) default '' AFTER `snmp_priv_protocol`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'max_oids', - "ALTER TABLE `mac_track_devices` ADD COLUMN `max_oids` int(12) unsigned default '10' AFTER `snmp_context`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'snmp_engine_id', - "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'term_type', - "ALTER TABLE `mac_track_devices` ADD COLUMN `term_type` tinyint(11) NOT NULL default '1' AFTER `scan_type`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'private_key_path', - "ALTER TABLE `mac_track_devices` ADD COLUMN `private_key_path` varchar(128) default '' AFTER `user_password`" - ); - - if (!db_table_exists('mac_track_snmp')) { - $data = []; - $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'name', 'type' => 'varchar(100)', 'NULL' => false]; - $data['primary'] = 'id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Group of SNMP Option Sets'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); - } - - if (!db_table_exists('mac_track_snmp_items')) { - $data = []; - $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; - $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; - $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; - $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; - $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; - $data['primary'] = 'id`,`snmp_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Set of SNMP Options'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); - } - - mactrack_add_column( - 'mac_track_snmp_items', - 'snmp_engine_id', - "ALTER TABLE `mac_track_snmp_items` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`" - ); - - if (!db_table_exists('mac_track_interface_graphs')) { - $data = []; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1']; - $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; - $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); - } - - mactrack_add_column( - 'mac_track_interfaces', - 'ifMauAutoNegAdminStatus', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegAdminStatus` integer UNSIGNED NOT NULL default '0' AFTER `ifDuplex`" - ); - - mactrack_add_column( - 'mac_track_interfaces', - 'ifMauAutoNegRemoteSignaling', - "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegRemoteSignaling` integer UNSIGNED NOT NULL default '0' AFTER `ifMauAutoNegAdminStatus`" - ); - - mactrack_add_column( - 'mac_track_device_types', - 'dot1x_scanning_function', - "ALTER TABLE `mac_track_device_types` ADD COLUMN `dot1x_scanning_function` varchar(100) default '' AFTER `ip_scanning_function`" - ); - - mactrack_add_column( - 'mac_track_device_types', - 'serial_number_oid', - "ALTER TABLE `mac_track_device_types` ADD COLUMN `serial_number_oid` varchar(100) default '' AFTER `dot1x_scanning_function`" - ); - - mactrack_add_column( - 'mac_track_sites', - 'customer_contact', - "ALTER TABLE `mac_track_sites` ADD COLUMN `customer_contact` varchar(150) default '' AFTER `site_name`" - ); - - mactrack_add_column( - 'mac_track_sites', - 'netops_contact', - "ALTER TABLE `mac_track_sites` ADD COLUMN `netops_contact` varchar(150) default '' AFTER `customer_contact`" - ); - - mactrack_add_column( - 'mac_track_sites', - 'facilities_contact', - "ALTER TABLE `mac_track_sites` ADD COLUMN `facilities_contact` varchar(150) default '' AFTER `netops_contact`" - ); - - mactrack_add_column( - 'mac_track_sites', - 'site_info', - 'ALTER TABLE `mac_track_sites` ADD COLUMN `site_info` text AFTER `facilities_contact`' - ); - - mactrack_add_column( - 'mac_track_sites', - 'skip_vlans', - "ALTER TABLE `mac_track_sites` ADD COLUMN `skip_vlans` text DEFAULT ''" - ); - - mactrack_add_column( - 'mac_track_sites', - 'scan_vlans', - "ALTER TABLE `mac_track_sites` ADD COLUMN `scan_vlans` text DEFAULT ''" - ); - - mactrack_add_column( - 'mac_track_devices', - 'device_name', - "ALTER TABLE `mac_track_devices` ADD COLUMN `device_name` varchar(100) default '' AFTER `host_id`" - ); - - mactrack_add_column( - 'mac_track_devices', - 'notes', - 'ALTER TABLE `mac_track_devices` ADD COLUMN `notes` text AFTER `hostname`' - ); - - mactrack_add_column( - 'mac_track_devices', - 'scan_trunk_port', - "ALTER TABLE `mac_track_devices` ADD COLUMN `scan_trunk_port` text DEFAULT ''" - ); - - mactrack_add_column( - 'mac_track_scanning_functions', - 'type', - "ALTER TABLE `mac_track_scanning_functions` ADD COLUMN `type` int(10) unsigned NOT NULL default '0' AFTER `scanning_function`" - ); - - mactrack_add_column( - 'mac_track_temp_ports', - 'device_name', - "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" - ); - - mactrack_add_column( - 'mac_track_temp_ports', - 'vendor_mac', - 'ALTER TABLE `mac_track_temp_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`' - ); - - mactrack_add_column( - 'mac_track_temp_ports', - 'authorized', - "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `updated`" - ); - - mactrack_add_column( - 'mac_track_ports', - 'device_name', - "ALTER TABLE `mac_track_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" - ); - - mactrack_add_column( - 'mac_track_ports', - 'vendor_mac', - 'ALTER TABLE `mac_track_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`' - ); - - mactrack_add_column( - 'mac_track_ports', - 'authorized', - "ALTER TABLE `mac_track_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `scan_date`" - ); - - mactrack_add_column( - 'mac_track_ips', - 'device_name', - "ALTER TABLE `mac_track_ips` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" - ); - - $columns = array_rekey( - db_fetch_assoc('SHOW COLUMNS FROM mac_track_ips'), - 'Field', - 'Type' - ); - - if (false !== strpos($columns['port_number'], 'int(10)')) { - db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - - db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); - } elseif (false !== strpos($columns['port_number'], 'varchar(20)')) { - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - } else { - db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN first_scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN last_rundate TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_max_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_current_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_processes MODIFY COLUMN start_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_scan_dates MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - - db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); - } - - if (!db_table_exists('mac_track_arp')) { - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'mac_address`, `ip_address'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Table for VRF ARP translation'; - api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); - } + } + + mactrack_add_column( + 'mac_track_interfaces', + 'ifHighSpeed', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifHighSpeed` int(10) unsigned NOT NULL default '0' AFTER `ifSpeed`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifDuplex', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifDuplex` int(10) unsigned NOT NULL default '0' AFTER `ifHighSpeed`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInDiscards', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifInDiscards` int(10) unsigned NOT NULL default '0' AFTER `ifOutErrors`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInErrors', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifInErrors` int(10) unsigned NOT NULL default '0' AFTER `int_ifInDiscards`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInUnknownProtos', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifInUnknownProtos` int(10) unsigned NOT NULL default '0' AFTER `int_ifInErrors`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifOutDiscards', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifOutDiscards` int(10) unsigned NOT NULL default '0' AFTER `int_ifInUnknownProtos`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifOutErrors', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `int_ifOutErrors` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutDiscards`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'host_id', + "ALTER TABLE `mac_track_devices` ADD COLUMN `host_id` int(10) unsigned NOT NULL default '0' AFTER `device_id`" + ); + + mactrack_add_column( + 'mac_track_macwatch', + 'date_last_notif', + "ALTER TABLE `mac_track_macwatch` ADD COLUMN `date_last_notif` TIMESTAMP DEFAULT '0000-00-00 00:00:00' AFTER `date_last_seen`" + ); + + mactrack_execute_sql('Add length to Device Types Match Fields', "ALTER TABLE `mac_track_device_types` MODIFY COLUMN `sysDescr_match` VARCHAR(100) NOT NULL default '', MODIFY COLUMN `sysObjectID_match` VARCHAR(100) NOT NULL default ''"); + + mactrack_execute_sql('Correct a Scanning Function Bug', "DELETE FROM mac_track_scanning_functions WHERE scanning_function='Not Applicable - Hub/Switch'"); + + mactrack_add_column( + 'mac_track_devices', + 'host_id', + "ALTER TABLE `mac_track_devices` ADD COLUMN `host_id` INTEGER UNSIGNED NOT NULL default '0' AFTER `device_id`" + ); + + mactrack_add_index( + 'mac_track_devices', + 'host_id', + 'ALTER TABLE `mac_track_devices` ADD INDEX `host_id`(`host_id`)' + ); + + mactrack_add_index( + 'mac_track_ports', + 'scan_date', + 'ALTER TABLE `mac_track_ports` ADD INDEX `scan_date` USING BTREE(`scan_date`)' + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'sysUptime', + "ALTER TABLE mac_track_interfaces ADD COLUMN `sysUptime` int(10) unsigned NOT NULL default '0' AFTER `device_id`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifInOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInOctets` int(10) unsigned NOT NULL default '0' AFTER `vlan_trunk_status`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifOutOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutOctets` int(10) unsigned NOT NULL default '0' AFTER `ifInOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifHCInOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifHCInOctets` bigint(20) unsigned NOT NULL default '0' AFTER `ifOutOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifHCOutOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifHCOutOctets` bigint(20) unsigned NOT NULL default '0' AFTER `ifHCInOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifInUcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifHCOutOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifOutUcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifInUcastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifInMulticastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifOutUcastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifOutMulticastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifInMulticastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifInBroadcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifInBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifOutMulticastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifOutBroadcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `ifOutBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `ifInBroadcastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'inBound', + "ALTER TABLE mac_track_interfaces ADD COLUMN `inBound` double NOT NULL default '0' AFTER `ifOutErrors`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'outBound', + "ALTER TABLE mac_track_interfaces ADD COLUMN `outBound` double NOT NULL default '0' AFTER `inBound`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInOctets` int(10) unsigned NOT NULL default '0' AFTER `outBound`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifOutOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutOctets` int(10) unsigned NOT NULL default '0' AFTER `int_ifInOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifHCInOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifHCInOctets` bigint(20) unsigned NOT NULL default '0' AFTER `int_ifOutOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifHCOutOctets', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifHCOutOctets` bigint(20) unsigned NOT NULL default '0' AFTER `int_ifHCInOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInUcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifHCOutOctets`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifOutUcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutUcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInUcastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInMulticastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutUcastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifOutMulticastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutMulticastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInMulticastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifInBroadcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifInBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifOutMulticastPkts`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'int_ifOutBroadcastPkts', + "ALTER TABLE mac_track_interfaces ADD COLUMN `int_ifOutBroadcastPkts` int(10) unsigned NOT NULL default '0' AFTER `int_ifInBroadcastPkts`" + ); + + if (!mactrack_db_key_exists('mac_track_ports', 'site_id_device_id')) { + db_execute('ALTER TABLE `mac_track_ports` ADD INDEX `site_id_device_id`(`site_id`, `device_id`);'); + } + + // new for 2.1.2 + // SNMP V3 + mactrack_add_column( + 'mac_track_devices', + 'term_type', + "ALTER TABLE `mac_track_devices` ADD COLUMN `term_type` tinyint(11) NOT NULL default '1' AFTER `scan_type`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'user_name', + 'ALTER TABLE `mac_track_devices` ADD COLUMN `user_name` varchar(40) default NULL AFTER `term_type`' + ); + + mactrack_add_column( + 'mac_track_devices', + 'user_password', + 'ALTER TABLE `mac_track_devices` ADD COLUMN `user_password` varchar(40) default NULL AFTER `user_name`' + ); + + mactrack_add_column( + 'mac_track_devices', + 'private_key_path', + "ALTER TABLE `mac_track_devices` ADD COLUMN `private_key_path` varchar(128) default '' AFTER `user_password`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_options', + "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_options` int(10) unsigned NOT NULL default '0' AFTER `private_key_path`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_username', + 'ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_username` varchar(50) default NULL AFTER `snmp_status`' + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_password', + 'ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_password` varchar(50) default NULL AFTER `snmp_username`' + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_auth_protocol', + "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_auth_protocol` char(5) default '' AFTER `snmp_password`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_priv_passphrase', + "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_priv_passphrase` varchar(200) default '' AFTER `snmp_auth_protocol`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_priv_protocol', + "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_priv_protocol` char(6) default '' AFTER `snmp_priv_passphrase`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_context', + "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_context` varchar(64) default '' AFTER `snmp_priv_protocol`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'max_oids', + "ALTER TABLE `mac_track_devices` ADD COLUMN `max_oids` int(12) unsigned default '10' AFTER `snmp_context`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'snmp_engine_id', + "ALTER TABLE `mac_track_devices` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'term_type', + "ALTER TABLE `mac_track_devices` ADD COLUMN `term_type` tinyint(11) NOT NULL default '1' AFTER `scan_type`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'private_key_path', + "ALTER TABLE `mac_track_devices` ADD COLUMN `private_key_path` varchar(128) default '' AFTER `user_password`" + ); + + if (!db_table_exists('mac_track_snmp')) { + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(100)', 'NULL' => false]; + $data['primary'] = 'id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Group of SNMP Option Sets'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); + } + + if (!db_table_exists('mac_track_snmp_items')) { + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; + $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; + $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; + $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; + $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; + $data['primary'] = 'id`,`snmp_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Set of SNMP Options'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); + } + + mactrack_add_column( + 'mac_track_snmp_items', + 'snmp_engine_id', + "ALTER TABLE `mac_track_snmp_items` ADD COLUMN `snmp_engine_id` varchar(64) default '' AFTER `snmp_context`" + ); + + if (!db_table_exists('mac_track_interface_graphs')) { + $data = []; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1']; + $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; + $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); + } + + mactrack_add_column( + 'mac_track_interfaces', + 'ifMauAutoNegAdminStatus', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegAdminStatus` integer UNSIGNED NOT NULL default '0' AFTER `ifDuplex`" + ); + + mactrack_add_column( + 'mac_track_interfaces', + 'ifMauAutoNegRemoteSignaling', + "ALTER TABLE `mac_track_interfaces` ADD COLUMN `ifMauAutoNegRemoteSignaling` integer UNSIGNED NOT NULL default '0' AFTER `ifMauAutoNegAdminStatus`" + ); + + mactrack_add_column( + 'mac_track_device_types', + 'dot1x_scanning_function', + "ALTER TABLE `mac_track_device_types` ADD COLUMN `dot1x_scanning_function` varchar(100) default '' AFTER `ip_scanning_function`" + ); + + mactrack_add_column( + 'mac_track_device_types', + 'serial_number_oid', + "ALTER TABLE `mac_track_device_types` ADD COLUMN `serial_number_oid` varchar(100) default '' AFTER `dot1x_scanning_function`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'customer_contact', + "ALTER TABLE `mac_track_sites` ADD COLUMN `customer_contact` varchar(150) default '' AFTER `site_name`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'netops_contact', + "ALTER TABLE `mac_track_sites` ADD COLUMN `netops_contact` varchar(150) default '' AFTER `customer_contact`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'facilities_contact', + "ALTER TABLE `mac_track_sites` ADD COLUMN `facilities_contact` varchar(150) default '' AFTER `netops_contact`" + ); + + mactrack_add_column( + 'mac_track_sites', + 'site_info', + 'ALTER TABLE `mac_track_sites` ADD COLUMN `site_info` text AFTER `facilities_contact`' + ); + + mactrack_add_column( + 'mac_track_sites', + 'skip_vlans', + "ALTER TABLE `mac_track_sites` ADD COLUMN `skip_vlans` text DEFAULT ''" + ); + + mactrack_add_column( + 'mac_track_sites', + 'scan_vlans', + "ALTER TABLE `mac_track_sites` ADD COLUMN `scan_vlans` text DEFAULT ''" + ); + + mactrack_add_column( + 'mac_track_devices', + 'device_name', + "ALTER TABLE `mac_track_devices` ADD COLUMN `device_name` varchar(100) default '' AFTER `host_id`" + ); + + mactrack_add_column( + 'mac_track_devices', + 'notes', + 'ALTER TABLE `mac_track_devices` ADD COLUMN `notes` text AFTER `hostname`' + ); + + mactrack_add_column( + 'mac_track_devices', + 'scan_trunk_port', + "ALTER TABLE `mac_track_devices` ADD COLUMN `scan_trunk_port` text DEFAULT ''" + ); + + mactrack_add_column( + 'mac_track_scanning_functions', + 'type', + "ALTER TABLE `mac_track_scanning_functions` ADD COLUMN `type` int(10) unsigned NOT NULL default '0' AFTER `scanning_function`" + ); + + mactrack_add_column( + 'mac_track_temp_ports', + 'device_name', + "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" + ); + + mactrack_add_column( + 'mac_track_temp_ports', + 'vendor_mac', + 'ALTER TABLE `mac_track_temp_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`' + ); + + mactrack_add_column( + 'mac_track_temp_ports', + 'authorized', + "ALTER TABLE `mac_track_temp_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `updated`" + ); + + mactrack_add_column( + 'mac_track_ports', + 'device_name', + "ALTER TABLE `mac_track_ports` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" + ); + + mactrack_add_column( + 'mac_track_ports', + 'vendor_mac', + 'ALTER TABLE `mac_track_ports` ADD COLUMN `vendor_mac` varchar(8) default NULL AFTER `mac_address`' + ); + + mactrack_add_column( + 'mac_track_ports', + 'authorized', + "ALTER TABLE `mac_track_ports` ADD COLUMN `authorized` tinyint(3) unsigned NOT NULL default '0' AFTER `scan_date`" + ); + + mactrack_add_column( + 'mac_track_ips', + 'device_name', + "ALTER TABLE `mac_track_ips` ADD COLUMN `device_name` varchar(100) NOT NULL default '' AFTER `hostname`" + ); + + $columns = array_rekey( + db_fetch_assoc('SHOW COLUMNS FROM mac_track_ips'), + 'Field', + 'Type' + ); + + if (strpos($columns['port_number'], 'int(10)') !== false) { + db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + + db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(20) NOT NULL default ''"); + } elseif (strpos($columns['port_number'], 'varchar(20)') !== false) { + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + } else { + db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN first_scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN last_rundate TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_max_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ip_ranges MODIFY COLUMN ips_current_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_processes MODIFY COLUMN start_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_scan_dates MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + + db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN scan_date TIMESTAMP NOT NULL DEFAULT '0000-00-00'"); + } + + if (!db_table_exists('mac_track_arp')) { + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'mac_address`, `ip_address'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Table for VRF ARP translation'; + api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); + } - $tables = db_fetch_assoc("SELECT DISTINCT TABLE_NAME + $tables = db_fetch_assoc("SELECT DISTINCT TABLE_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME LIKE 'mac_track%'"); - if (cacti_sizeof($tables)) { - foreach ($tables as $table) { - $columns = db_fetch_assoc("SELECT * + if (cacti_sizeof($tables)) { + foreach ($tables as $table) { + $columns = db_fetch_assoc("SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=SCHEMA() - AND TABLE_NAME='".$table['TABLE_NAME']."' + AND TABLE_NAME='" . $table['TABLE_NAME'] . "' AND DATA_TYPE LIKE '%char%' AND COLUMN_DEFAULT IS NULL"); - if (cacti_sizeof($columns)) { - $alter = 'ALTER TABLE `'.$table['TABLE_NAME'].'` '; + if (cacti_sizeof($columns)) { + $alter = 'ALTER TABLE `' . $table['TABLE_NAME'] . '` '; - $i = 0; - foreach ($columns as $column) { - $alter .= (0 == $i ? '' : ', ').' MODIFY COLUMN `'.$column['COLUMN_NAME'].'` '.$column['COLUMN_TYPE'].('NO' == $column['IS_NULLABLE'] ? ' NOT NULL' : '').' DEFAULT ""'; - ++$i; - } + $i = 0; - db_execute($alter); - } - } - } + foreach ($columns as $column) { + $alter .= ($i == 0 ? '' : ', ') . ' MODIFY COLUMN `' . $column['COLUMN_NAME'] . '` ' . $column['COLUMN_TYPE'] . ($column['IS_NULLABLE'] == 'NO' ? ' NOT NULL' : '') . ' DEFAULT ""'; + ++$i; + } - // new for 4.6 - mactrack_add_column( - 'mac_track_device_types', - 'disabled', - "ALTER TABLE `mac_track_device_types` ADD COLUMN `disabled` varchar(2) default '' AFTER `highPort`" - ); + db_execute($alter); + } + } + } - // add few device types examples if does not exist - $count = db_fetch_cell("SELECT COUNT(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); + // new for 4.6 + mactrack_add_column( + 'mac_track_device_types', + 'disabled', + "ALTER TABLE `mac_track_device_types` ADD COLUMN `disabled` varchar(2) default '' AFTER `highPort`" + ); - if (0 == $count) { - db_execute("INSERT INTO mac_track_device_types + // add few device types examples if does not exist + $count = db_fetch_cell("SELECT COUNT(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); + + if ($count == 0) { + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5130-default','H3C','2','','.1.3.6.1.4.1.25506.11.1.18*','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6300-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.109','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6200-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.300','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 1920-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.164','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5140-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.297','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2530 8p-default','HPE','2','','.1.3.6.1.4.1.11.2.3.7.11.141','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2930 8p-default','Aruba','2','','.1.3.6.1.4.1.11.2.3.7.11.181.16','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2600 Router-default','Cisco','3','*C2600*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960S Switch-default','Cisco','2','*C2960S*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3550 Switch-default','Cisco','2','*C3550*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3750 Switch-default','Cisco','2','*C3750*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*cat4000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2900 Router-default','Cisco','3','*C2900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ASR Router-default','Cisco','3','*ASR1000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('6513 Switch/Router-default','Cisco','2','*s72033_rp*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CE500 Switch-default','Cisco','1','*CE500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2950 Switch-default','Cisco','2','*C2950*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2800 Router-default','Cisco','3','*C2800*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('BladeCenter2 10G-default','Cisco','2','*CBS31X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('DellBladeCenter-default','Dell','2','*Ethernet Switch*','','get_dell_dot1q_switch_ports','get_CTAlias_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG224-default','Cisco','3','*vg224*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C870 Router-default','Cisco','3','*C870*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Cisco ASA-default','Cisco','3','*Adaptive Security Appliance*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3x50 Switch-default','Cisco','2','*CAT3K*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3900 Router-default','Cisco','3','*C3900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Blade Center 10/100-default','Cisco','2','*CIGESM-I6K2L2Q4-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT4500-default','Cisco','2','*cat4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3560 Switch-default','Cisco','2','*C3560*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ProCurve Switch-default','HP','2','*ProCurve Switch*','','get_procurve_ngi_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT3K_CAA-UNIVERSALK9-M-default','Cisco','2','*CAT3K_CAA-UNIVERSALK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('IBM Flex System Fabric-default','IBM','2','*IBM Flex System Fabric*','','get_generic_dot1q_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960X Switch-default','Cisco','2','*C2960X*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Lite-default','Cisco','2','*C2960-LANLITEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Base-default','Cisco','2','*C2960-LANBASEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG3X0-default','Cisco','3','*VG3X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('93xx + 94xx Switch-default','Cisco','2','*CAT9K_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('43xx Router-default','Cisco','3','*ISR Software*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus Generic-default','Cisco','2','*nxos*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 7K-default','Cisco','2','*n7000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','.1.3.6.1.4.1.9.12.3.1.3.932',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 5K-default','Cisco','2','*n5000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('92xx Switch-default','Cisco','1','*CAT9K_LITE_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - } + } + + db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); + db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN scan_trunk_port text NULL default ''"); - db_execute("ALTER TABLE mac_track_ips MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_temp_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_dot1x MODIFY COLUMN port_number varchar(30) NOT NULL default ''"); - db_execute("ALTER TABLE mac_track_devices MODIFY COLUMN scan_trunk_port text NULL default ''"); + // Change old realm names + if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Viewer'")) { + db_fetch_cell("UPDATE plugin_realms set display='Mactrack Viewer' WHERE plugin = 'mactrack' and display='Device Tracking Viewer'"); + } - // Change old realm names - if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Viewer'")) { - db_fetch_cell("UPDATE plugin_realms set display='Mactrack Viewer' WHERE plugin = 'mactrack' and display='Device Tracking Viewer'"); - } - if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Administrator'")) { - db_fetch_cell("UPDATE plugin_realms set display='Mactrack Administrator' WHERE plugin = 'mactrack' and display='Device Tracking Administrator'"); - } + if (db_fetch_cell("SELECT count(*) FROM plugin_realms WHERE plugin = 'mactrack' and display='Device Tracking Administrator'")) { + db_fetch_cell("UPDATE plugin_realms set display='Mactrack Administrator' WHERE plugin = 'mactrack' and display='Device Tracking Administrator'"); + } - // 4.9 - $keys = db_fetch_assoc('SHOW INDEXES FROM mac_track_aggregated_ports WHERE KEY_NAME="port_number"'); + // 4.9 + $keys = db_fetch_assoc('SHOW INDEXES FROM mac_track_aggregated_ports WHERE KEY_NAME="port_number"'); - if (7 != $keys) { - db_execute('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number'); + if ($keys != 7) { + db_execute('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number'); - db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute('ALTER TABLE mac_track_aggregated_ports ADD INDEX `port_number` (`port_number`, `mac_address`, `ip_address`, `device_id`, `site_id`, `vlan_id`, `authorized`)'); + db_execute('ALTER TABLE mac_track_aggregated_ports ADD INDEX `port_number` (`port_number`, `mac_address`, `ip_address`, `device_id`, `site_id`, `vlan_id`, `authorized`)'); - db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, ':', '')"); - db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, '-', '')"); + db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, ':', '')"); + db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); - } + db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); + } - // default site must exist - if (!db_fetch_cell('SELECT count(*) FROM mac_track_sites')) { - db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); - } + // default site must exist + if (!db_fetch_cell('SELECT count(*) FROM mac_track_sites')) { + db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); + } } -function mactrack_setup_database() -{ - $data = []; - $data['columns'][] = ['name' => 'row_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; - $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true]; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'date_last', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP']; - $data['columns'][] = ['name' => 'first_scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'count_rec', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'active_last', 'unsigned' => true, 'type' => 'tinyint(1)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['primary'] = 'row_id'; - $data['unique_keys'][] = ['name' => 'port_number', 'columns' => 'port_number`,`mac_address`,`ip_address`,`device_id`,`site_id`,`vlan_id`,`authorized']; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; - $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; - $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; - $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; - $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; - $data['keys'][] = ['name' => 'port_name', 'columns' => 'port_name']; - $data['keys'][] = ['name' => 'dns_hostname', 'columns' => 'dns_hostname']; - $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; - $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; - $data['keys'][] = ['name' => 'site_id_device_id', 'columns' => 'site_id`,`device_id']; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Database for aggregated date for Tracking Device MACs'; - api_plugin_db_table_create('mactrack', 'mac_track_aggregated_ports', $data); - - $data = []; - $data['columns'][] = ['name' => 'mac_prefix', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; - $data['primary'] = 'mac_prefix'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_approved_macs', $data); - - $data = []; - $data['columns'][] = ['name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'device_type', 'type' => 'varchar(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'sysDescr_match', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'sysObjectID_match', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ip_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'dot1x_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'serial_number_oid', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'lowPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'highPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'disabled', 'type' => 'varchar(2)', 'NULL' => false, 'default' => '']; - $data['primary'] = 'device_type_id'; - $data['unique_keys'][] = ['name' => 'snmp_info', 'columns' => 'sysDescr_match`,`sysObjectID_match`,`device_type']; - $data['keys'][] = ['name' => 'device_type', 'columns' => 'device_type']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_device_types', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'host_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; - $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'notes', 'type' => 'text', 'NULL' => true]; - $data['columns'][] = ['name' => 'disabled', 'type' => 'char(2)', 'NULL' => true]; - $data['columns'][] = ['name' => 'ignorePorts', 'type' => 'varchar(255)', 'NULL' => true]; - $data['columns'][] = ['name' => 'ips_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'vlans_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ports_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ports_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ports_trunk', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'macs_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'scan_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1']; - $data['columns'][] = ['name' => 'term_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1']; - $data['columns'][] = ['name' => 'user_name', 'type' => 'varchar(40)', 'NULL' => true]; - $data['columns'][] = ['name' => 'user_password', 'type' => 'varchar(40)', 'NULL' => true]; - $data['columns'][] = ['name' => 'private_key_path', 'type' => 'varchar(128)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_options', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'snmp_readstrings', 'type' => 'varchar(255)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; - $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; - $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; - $data['columns'][] = ['name' => 'snmp_sysName', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_sysLocation', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_sysContact', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_sysObjectID', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_sysDescr', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_sysUptime', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; - $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; - $data['columns'][] = ['name' => 'last_runmessage', 'type' => 'varchar(100)', 'NULL' => true]; - $data['columns'][] = ['name' => 'last_rundate', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'last_runduration', 'type' => 'decimal(10,5)', 'NULL' => false, 'default' => '0.00000']; - $data['columns'][] = ['name' => 'scan_trunk_port', 'type' => 'text', 'NULL' => true, 'default' => '']; - $data['primary'] = 'device_id'; - $data['unique_keys'][] = ['name' => 'hostname_snmp_port_site_id', 'columns' => 'hostname`,`snmp_port`,`site_id']; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; - $data['keys'][] = ['name' => 'snmp_sysDescr', 'columns' => 'snmp_sysDescr']; - $data['keys'][] = ['name' => 'snmp_sysObjectID', 'columns' => 'snmp_sysObjectID']; - $data['keys'][] = ['name' => 'device_type_id', 'columns' => 'device_type_id']; - $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Devices to be scanned for MAC addresses'; - api_plugin_db_table_create('mactrack', 'mac_track_devices', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'username', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'domain', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; - $data['keys'][] = ['name' => 'ip', 'columns' => 'ip_address']; - $data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number']; - $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['keys'][] = ['name' => 'username', 'columns' => 'username']; - $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; - $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_dot1x', $data); - - $data = []; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1']; - $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; - $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'sysUptime', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ifAlias', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ifDescr', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ifType', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifMtu', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifHighSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifDuplex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifMauAutoNegAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifMauAutoNegRemoteSignaling', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifPhysAddress', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ifAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOperStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifLastChange', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'linkPort', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vlan_trunk', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; - $data['columns'][] = ['name' => 'vlan_trunk_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifInDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifInErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifInUnknownProtos', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOutDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; - $data['columns'][] = ['name' => 'ifOutErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; - $data['columns'][] = ['name' => 'inBound', 'type' => 'double', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'outBound', 'type' => 'double', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInDiscards', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInErrors', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifInUnknownProtos', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutDiscards', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_ifOutErrors', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'last_up_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'last_down_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'stateChanges', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_discards_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'int_errors_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['primary'] = 'site_id`,`device_id`,`ifIndex'; - $data['keys'][] = ['name' => 'ifDescr', 'columns' => 'ifDescr']; - $data['keys'][] = ['name' => 'ifType', 'columns' => 'ifType']; - $data['keys'][] = ['name' => 'ifSpeed', 'columns' => 'ifSpeed']; - $data['keys'][] = ['name' => 'ifMTU', 'columns' => 'ifMtu']; - $data['keys'][] = ['name' => 'ifAdminStatus', 'columns' => 'ifAdminStatus']; - $data['keys'][] = ['name' => 'ifOperStatus', 'columns' => 'ifOperStatus']; - $data['keys'][] = ['name' => 'ifInDiscards', 'columns' => 'ifInUnknownProtos']; - $data['keys'][] = ['name' => 'ifInErrors', 'columns' => 'ifInUnknownProtos']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_interfaces', $data); - - $data = []; - $data['columns'][] = ['name' => 'ip_range', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ips_max', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ips_current', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'ips_max_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'ips_current_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'ip_range`,`site_id'; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_ip_ranges', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; - $data['keys'][] = ['name' => 'ip', 'columns' => 'ip_address']; - $data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number']; - $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; - $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_ips', $data); - - $data = []; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'added_date', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP']; - $data['columns'][] = ['name' => 'added_by', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['primary'] = 'mac_address'; - $data['keys'][] = ['name' => 'mac_id', 'columns' => 'mac_id']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_macauth', $data); - - $data = []; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'name', 'type' => 'varchar(45)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'ticket_number', 'type' => 'varchar(45)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'notify_schedule', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; - $data['columns'][] = ['name' => 'email_addresses', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'discovered', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; - $data['columns'][] = ['name' => 'date_first_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'date_last_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'date_last_notif', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'mac_address'; - $data['keys'][] = ['name' => 'mac_id', 'columns' => 'mac_id']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_macwatch', $data); - - $data = []; - $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor_address', 'type' => 'text', 'NULL' => false]; - $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1']; - $data['primary'] = 'vendor_mac'; - $data['keys'][] = ['name' => 'vendor_name', 'columns' => 'vendor_name']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_oui_database', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; - $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true, 'default' => '']; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; - $data['keys'][] = ['name' => 'description', 'columns' => 'device_name']; - $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; - $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; - $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; - $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; - $data['keys'][] = ['name' => 'port_name', 'columns' => 'port_name']; - $data['keys'][] = ['name' => 'dns_hostname', 'columns' => 'dns_hostname']; - $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; - $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Database for Tracking Device MACs'; - api_plugin_db_table_create('mactrack', 'mac_track_ports', $data); - - $data = []; - $data['columns'][] = ['name' => 'device_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'process_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true]; - $data['columns'][] = ['name' => 'status', 'type' => 'varchar(20)', 'NULL' => false, 'default' => 'Queued']; - $data['columns'][] = ['name' => 'start_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'device_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_processes', $data); - - $data = []; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'scan_date'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_scan_dates', $data); - - $data = []; - $data['columns'][] = ['name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false]; - $data['columns'][] = ['name' => 'type', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'description', 'type' => 'varchar(200)', 'NULL' => false]; - $data['primary'] = 'scanning_function'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Registered Scanning Functions'; - api_plugin_db_table_create('mactrack', 'mac_track_scanning_functions', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'site_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'customer_contact', 'type' => 'varchar(150)', 'NULL' => true]; - $data['columns'][] = ['name' => 'netops_contact', 'type' => 'varchar(150)', 'NULL' => true]; - $data['columns'][] = ['name' => 'facilities_contact', 'type' => 'varchar(150)', 'NULL' => true]; - $data['columns'][] = ['name' => 'site_info', 'type' => 'text', 'NULL' => true]; - $data['columns'][] = ['name' => 'total_devices', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'total_device_errors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'total_macs', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'total_ips', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'total_user_ports', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'total_oper_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'total_trunk_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'skip_vlans', 'type' => 'text', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'scan_vlans', 'type' => 'text', 'NULL' => false, 'default' => '']; - $data['primary'] = 'site_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_sites', $data); - - // default site must exist - db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); - - $data = []; - $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['primary'] = 'id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Group of SNMP Option Sets'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); - - $data = []; - $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; - $data['columns'][] = ['name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; - $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; - $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; - $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; - $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; - $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; - $data['primary'] = 'id`,`snmp_id'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Set of SNMP Options'; - api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; - $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true]; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; - $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['columns'][] = ['name' => 'updated', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; - $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; - $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; - $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; - $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; - $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; - $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; - $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; - $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; - $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; - $data['keys'][] = ['name' => 'updated', 'columns' => 'updated']; - $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; - $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Database for Storing Temporary Results for Tracking Device MACS'; - api_plugin_db_table_create('mactrack', 'mac_track_temp_ports', $data); - - $data = []; - $data['columns'][] = ['name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1']; - $data['primary'] = 'vlan_id`,`site_id`,`device_id'; - $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; - $data['type'] = 'InnoDB'; - $data['comment'] = ''; - api_plugin_db_table_create('mactrack', 'mac_track_vlans', $data); - - $data = []; - $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; - $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => '']; - $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; - $data['columns'][] = ['name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; - $data['primary'] = 'mac_address`, `ip_address'; - $data['type'] = 'InnoDB'; - $data['comment'] = 'Table for VRF ARP translation'; - api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); - - // add few device types examples if does not exist - $count = db_fetch_cell("SELECT count(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); - if (0 == $count) { - db_execute("INSERT INTO mac_track_device_types +function mactrack_setup_database() { + $data = []; + $data['columns'][] = ['name' => 'row_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'date_last', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP']; + $data['columns'][] = ['name' => 'first_scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'count_rec', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'active_last', 'unsigned' => true, 'type' => 'tinyint(1)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'row_id'; + $data['unique_keys'][] = ['name' => 'port_number', 'columns' => 'port_number`,`mac_address`,`ip_address`,`device_id`,`site_id`,`vlan_id`,`authorized']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_name', 'columns' => 'port_name']; + $data['keys'][] = ['name' => 'dns_hostname', 'columns' => 'dns_hostname']; + $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; + $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; + $data['keys'][] = ['name' => 'site_id_device_id', 'columns' => 'site_id`,`device_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Database for aggregated date for Tracking Device MACs'; + api_plugin_db_table_create('mactrack', 'mac_track_aggregated_ports', $data); + + $data = []; + $data['columns'][] = ['name' => 'mac_prefix', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'mac_prefix'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_approved_macs', $data); + + $data = []; + $data['columns'][] = ['name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_type', 'type' => 'varchar(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sysDescr_match', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'sysObjectID_match', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ip_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dot1x_scanning_function', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'serial_number_oid', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'lowPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'highPort', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'disabled', 'type' => 'varchar(2)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'device_type_id'; + $data['unique_keys'][] = ['name' => 'snmp_info', 'columns' => 'sysDescr_match`,`sysObjectID_match`,`device_type']; + $data['keys'][] = ['name' => 'device_type', 'columns' => 'device_type']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_device_types', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'host_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'device_type_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'notes', 'type' => 'text', 'NULL' => true]; + $data['columns'][] = ['name' => 'disabled', 'type' => 'char(2)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ignorePorts', 'type' => 'varchar(255)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ips_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'vlans_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ports_total', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ports_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ports_trunk', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'macs_active', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'scan_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1']; + $data['columns'][] = ['name' => 'term_type', 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '1']; + $data['columns'][] = ['name' => 'user_name', 'type' => 'varchar(40)', 'NULL' => true]; + $data['columns'][] = ['name' => 'user_password', 'type' => 'varchar(40)', 'NULL' => true]; + $data['columns'][] = ['name' => 'private_key_path', 'type' => 'varchar(128)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_options', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_readstrings', 'type' => 'varchar(255)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; + $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; + $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; + $data['columns'][] = ['name' => 'snmp_sysName', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysLocation', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysContact', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysObjectID', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysDescr', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_sysUptime', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; + $data['columns'][] = ['name' => 'last_runmessage', 'type' => 'varchar(100)', 'NULL' => true]; + $data['columns'][] = ['name' => 'last_rundate', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'last_runduration', 'type' => 'decimal(10,5)', 'NULL' => false, 'default' => '0.00000']; + $data['columns'][] = ['name' => 'scan_trunk_port', 'type' => 'text', 'NULL' => true, 'default' => '']; + $data['primary'] = 'device_id'; + $data['unique_keys'][] = ['name' => 'hostname_snmp_port_site_id', 'columns' => 'hostname`,`snmp_port`,`site_id']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; + $data['keys'][] = ['name' => 'snmp_sysDescr', 'columns' => 'snmp_sysDescr']; + $data['keys'][] = ['name' => 'snmp_sysObjectID', 'columns' => 'snmp_sysObjectID']; + $data['keys'][] = ['name' => 'device_type_id', 'columns' => 'device_type_id']; + $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Devices to be scanned for MAC addresses'; + api_plugin_db_table_create('mactrack', 'mac_track_devices', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'username', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'domain', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; + $data['keys'][] = ['name' => 'ip', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'username', 'columns' => 'username']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_dot1x', $data); + + $data = []; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'host_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'local_graph_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'snmp_query_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'graph_template_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'field_name', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'field_value', 'type' => 'varchar(25)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'present', 'type' => 'tinyint(4)', 'NULL' => true, 'default' => '1']; + $data['primary'] = 'local_graph_id`,`device_id`,`ifIndex`,`host_id'; + $data['keys'][] = ['name' => 'host_id', 'columns' => 'host_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_interface_graphs', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sysUptime', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifIndex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifName', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifAlias', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifDescr', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifType', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifMtu', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifHighSpeed', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifDuplex', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifMauAutoNegAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifMauAutoNegRemoteSignaling', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifPhysAddress', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ifAdminStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOperStatus', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifLastChange', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'linkPort', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_trunk', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; + $data['columns'][] = ['name' => 'vlan_trunk_status', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifInUnknownProtos', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutDiscards', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; + $data['columns'][] = ['name' => 'ifOutErrors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true, 'default' => '0']; + $data['columns'][] = ['name' => 'inBound', 'type' => 'double', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'outBound', 'type' => 'double', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutOctets', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifHCInOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifHCOutOctets', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutNUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutMulticastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutBroadcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutUcastPkts', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInDiscards', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInErrors', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifInUnknownProtos', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutDiscards', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_ifOutErrors', 'unsigned' => true, 'type' => 'float', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'last_up_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'last_down_time', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'stateChanges', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_discards_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'int_errors_present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'site_id`,`device_id`,`ifIndex'; + $data['keys'][] = ['name' => 'ifDescr', 'columns' => 'ifDescr']; + $data['keys'][] = ['name' => 'ifType', 'columns' => 'ifType']; + $data['keys'][] = ['name' => 'ifSpeed', 'columns' => 'ifSpeed']; + $data['keys'][] = ['name' => 'ifMTU', 'columns' => 'ifMtu']; + $data['keys'][] = ['name' => 'ifAdminStatus', 'columns' => 'ifAdminStatus']; + $data['keys'][] = ['name' => 'ifOperStatus', 'columns' => 'ifOperStatus']; + $data['keys'][] = ['name' => 'ifInDiscards', 'columns' => 'ifInUnknownProtos']; + $data['keys'][] = ['name' => 'ifInErrors', 'columns' => 'ifInUnknownProtos']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_interfaces', $data); + + $data = []; + $data['columns'][] = ['name' => 'ip_range', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ips_max', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ips_current', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'ips_max_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'ips_current_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'ip_range`,`site_id'; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_ip_ranges', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'scan_date`,`ip_address`,`mac_address`,`site_id'; + $data['keys'][] = ['name' => 'ip', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_ips', $data); + + $data = []; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'added_date', 'type' => 'timestamp', 'NULL' => false, 'default' => 'CURRENT_TIMESTAMP', 'on_update' => 'CURRENT_TIMESTAMP']; + $data['columns'][] = ['name' => 'added_by', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'mac_address'; + $data['keys'][] = ['name' => 'mac_id', 'columns' => 'mac_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_macauth', $data); + + $data = []; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(45)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'ticket_number', 'type' => 'varchar(45)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'notify_schedule', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; + $data['columns'][] = ['name' => 'email_addresses', 'type' => 'varchar(255)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'discovered', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false]; + $data['columns'][] = ['name' => 'date_first_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'date_last_seen', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'date_last_notif', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'mac_address'; + $data['keys'][] = ['name' => 'mac_id', 'columns' => 'mac_id']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_macwatch', $data); + + $data = []; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_address', 'type' => 'text', 'NULL' => false]; + $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1']; + $data['primary'] = 'vendor_mac'; + $data['keys'][] = ['name' => 'vendor_name', 'columns' => 'vendor_name']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_oui_database', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true, 'default' => '']; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'scan_date', 'columns' => 'scan_date']; + $data['keys'][] = ['name' => 'description', 'columns' => 'device_name']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'port_name', 'columns' => 'port_name']; + $data['keys'][] = ['name' => 'dns_hostname', 'columns' => 'dns_hostname']; + $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; + $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Database for Tracking Device MACs'; + api_plugin_db_table_create('mactrack', 'mac_track_ports', $data); + + $data = []; + $data['columns'][] = ['name' => 'device_id', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'process_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => true]; + $data['columns'][] = ['name' => 'status', 'type' => 'varchar(20)', 'NULL' => false, 'default' => 'Queued']; + $data['columns'][] = ['name' => 'start_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'device_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_processes', $data); + + $data = []; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'scan_date'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_scan_dates', $data); + + $data = []; + $data['columns'][] = ['name' => 'scanning_function', 'type' => 'varchar(100)', 'NULL' => false]; + $data['columns'][] = ['name' => 'type', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'description', 'type' => 'varchar(200)', 'NULL' => false]; + $data['primary'] = 'scanning_function'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Registered Scanning Functions'; + api_plugin_db_table_create('mactrack', 'mac_track_scanning_functions', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'site_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'customer_contact', 'type' => 'varchar(150)', 'NULL' => true]; + $data['columns'][] = ['name' => 'netops_contact', 'type' => 'varchar(150)', 'NULL' => true]; + $data['columns'][] = ['name' => 'facilities_contact', 'type' => 'varchar(150)', 'NULL' => true]; + $data['columns'][] = ['name' => 'site_info', 'type' => 'text', 'NULL' => true]; + $data['columns'][] = ['name' => 'total_devices', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_device_errors', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_macs', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_ips', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_user_ports', 'type' => 'int(11)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_oper_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'total_trunk_ports', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'skip_vlans', 'type' => 'text', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_vlans', 'type' => 'text', 'NULL' => false, 'default' => '']; + $data['primary'] = 'site_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_sites', $data); + + // default site must exist + db_execute("INSERT INTO mac_track_sites (site_name, site_info) VALUES ('Default','Default site')"); + + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['primary'] = 'id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Group of SNMP Option Sets'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp', $data); + + $data = []; + $data['columns'][] = ['name' => 'id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'snmp_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'sequence', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'snmp_version', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_readstring', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'snmp_port', 'type' => 'int(10)', 'NULL' => false, 'default' => '161']; + $data['columns'][] = ['name' => 'snmp_timeout', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '500']; + $data['columns'][] = ['name' => 'snmp_retries', 'unsigned' => true, 'type' => 'tinyint(11)', 'NULL' => false, 'default' => '3']; + $data['columns'][] = ['name' => 'max_oids', 'unsigned' => true, 'type' => 'int(12)', 'NULL' => true, 'default' => '10']; + $data['columns'][] = ['name' => 'snmp_username', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_password', 'type' => 'varchar(50)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_auth_protocol', 'type' => 'char(5)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_passphrase', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_priv_protocol', 'type' => 'char(6)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_context', 'type' => 'varchar(64)', 'NULL' => true]; + $data['columns'][] = ['name' => 'snmp_engine_id', 'type' => 'varchar(64)', 'NULL' => true]; + $data['primary'] = 'id`,`snmp_id'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Set of SNMP Options'; + api_plugin_db_table_create('mactrack', 'mac_track_snmp_items', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'device_name', 'type' => 'varchar(100)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vlan_id', 'type' => 'varchar(5)', 'NULL' => false, 'default' => 'N/A']; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'vendor_mac', 'type' => 'varchar(8)', 'NULL' => true]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'dns_hostname', 'type' => 'varchar(200)', 'NULL' => true]; + $data['columns'][] = ['name' => 'port_number', 'type' => 'varchar(30)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'port_name', 'type' => 'varchar(50)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'timestamp', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['columns'][] = ['name' => 'updated', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0']; + $data['primary'] = 'port_number`,`scan_date`,`mac_address`,`device_id'; + $data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id']; + $data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name']; + $data['keys'][] = ['name' => 'ip_address', 'columns' => 'ip_address']; + $data['keys'][] = ['name' => 'hostname', 'columns' => 'hostname']; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['keys'][] = ['name' => 'vlan_id', 'columns' => 'vlan_id']; + $data['keys'][] = ['name' => 'device_id', 'columns' => 'device_id']; + $data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address']; + $data['keys'][] = ['name' => 'updated', 'columns' => 'updated']; + $data['keys'][] = ['name' => 'vendor_mac', 'columns' => 'vendor_mac']; + $data['keys'][] = ['name' => 'authorized', 'columns' => 'authorized']; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Database for Storing Temporary Results for Tracking Device MACS'; + api_plugin_db_table_create('mactrack', 'mac_track_temp_ports', $data); + + $data = []; + $data['columns'][] = ['name' => 'vlan_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'vlan_name', 'type' => 'varchar(128)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'present', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '1']; + $data['primary'] = 'vlan_id`,`site_id`,`device_id'; + $data['keys'][] = ['name' => 'vlan_name', 'columns' => 'vlan_name']; + $data['type'] = 'InnoDB'; + $data['comment'] = ''; + api_plugin_db_table_create('mactrack', 'mac_track_vlans', $data); + + $data = []; + $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false]; + $data['columns'][] = ['name' => 'ip_address', 'type' => 'varchar(20)', 'NULL' => true, 'default' => '']; + $data['columns'][] = ['name' => 'mac_address', 'type' => 'varchar(20)', 'NULL' => false, 'default' => '']; + $data['columns'][] = ['name' => 'scan_date', 'type' => 'datetime', 'NULL' => false, 'default' => '0000-00-00 00:00:00']; + $data['primary'] = 'mac_address`, `ip_address'; + $data['type'] = 'InnoDB'; + $data['comment'] = 'Table for VRF ARP translation'; + api_plugin_db_table_create('mactrack', 'mac_track_arp', $data); + + // add few device types examples if does not exist + $count = db_fetch_cell("SELECT count(*) FROM mac_track_device_types WHERE description LIKE '%-default'"); + + if ($count == 0) { + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5130-default','H3C','2','','.1.3.6.1.4.1.25506.11.1.18*','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6300-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.109','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 6200-default','Aruba','2','','.1.3.6.1.4.1.47196.4.1.1.1.300','get_oscx_switch_ports','get_oscx_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 1920-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.164','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Comware 5140-default','HPE','2','','.1.3.6.1.4.1.25506.11.1.297','get_h3c_3com_switch_ports','get_h3c_3com_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2530 8p-default','HPE','2','','.1.3.6.1.4.1.11.2.3.7.11.141','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Aruba 2930 8p-default','Aruba','2','','.1.3.6.1.4.1.11.2.3.7.11.181.16','get_generic_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2600 Router-default','Cisco','3','*C2600*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960S Switch-default','Cisco','2','*C2960S*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3550 Switch-default','Cisco','2','*C3550*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3750 Switch-default','Cisco','2','*C3750*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*cat4000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('45xx Switch-default','Cisco','2','*4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2900 Router-default','Cisco','3','*C2900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ASR Router-default','Cisco','3','*ASR1000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('6513 Switch/Router-default','Cisco','2','*s72033_rp*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CE500 Switch-default','Cisco','1','*CE500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2950 Switch-default','Cisco','2','*C2950*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2800 Router-default','Cisco','3','*C2800*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('BladeCenter2 10G-default','Cisco','2','*CBS31X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('DellBladeCenter-default','Dell','2','*Ethernet Switch*','','get_dell_dot1q_switch_ports','get_CTAlias_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG224-default','Cisco','3','*vg224*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C870 Router-default','Cisco','3','*C870*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Cisco ASA-default','Cisco','3','*Adaptive Security Appliance*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3x50 Switch-default','Cisco','2','*CAT3K*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3900 Router-default','Cisco','3','*C3900*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Blade Center 10/100-default','Cisco','2','*CIGESM-I6K2L2Q4-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT4500-default','Cisco','2','*cat4500*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C3560 Switch-default','Cisco','2','*C3560*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('ProCurve Switch-default','HP','2','*ProCurve Switch*','','get_procurve_ngi_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('CAT3K_CAA-UNIVERSALK9-M-default','Cisco','2','*CAT3K_CAA-UNIVERSALK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('IBM Flex System Fabric-default','IBM','2','*IBM Flex System Fabric*','','get_generic_dot1q_switch_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('C2960X Switch-default','Cisco','2','*C2960X*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Lite-default','Cisco','2','*C2960-LANLITEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('2960 Switch Base-default','Cisco','2','*C2960-LANBASEK9-M*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('VG3X0-default','Cisco','3','*VG3X0*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('93xx + 94xx Switch-default','Cisco','2','*CAT9K_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('43xx Router-default','Cisco','3','*ISR Software*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus Generic-default','Cisco','2','*nxos*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 7K-default','Cisco','2','*n7000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','.1.3.6.1.4.1.9.12.3.1.3.932',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('Nexus 5K-default','Cisco','2','*n5000*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - db_execute("INSERT INTO mac_track_device_types + db_execute("INSERT INTO mac_track_device_types (description, vendor, device_type, sysDescr_match, sysObjectID_match, scanning_function, ip_scanning_function, dot1x_scanning_function, serial_number_oid, lowPort, highPort, disabled) VALUES ('92xx Switch-default','Cisco','1','*CAT9K_LITE_IOSXE*','','get_IOS_dot1dTpFdbEntry_ports','get_standard_arp_table','0','',0,0,'on')"); - } + } } diff --git a/lib/mactrack_3com.php b/lib/mactrack_3com.php index 128ced0a..c9747c21 100644 --- a/lib/mactrack_3com.php +++ b/lib/mactrack_3com.php @@ -25,257 +25,260 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_3Com_dot1dTpFdbEntry_ports'); /* complete_3com_ifName - for buggy 3com SSII 1100 : they dont have ifName use ifDescr but it contains ':' - making it unusable for 'ignore port' - so transform it in PortN/M where N is stackId and M portnumber + for buggy 3com SSII 1100 : they dont have ifName use ifDescr but it contains ':' + making it unusable for 'ignore port' + so transform it in PortN/M where N is stackId and M portnumber */ -function complete_3com_ifName(&$device, &$ifIndexes) -{ - mactrack_debug('Start complete_3com_ifName'); - // device without ifName detection - foreach ($ifIndexes as $ifidx) { - if ('' != $ifidx['ifName']) { - return; - } - - break; - } - $pattern = '/RMON:V(\d+) Port (\d+) on Unit (\d+)/i'; - $pattern2 = '/RMON Port (\d+) on Unit (\d+)/i'; - $pattern3 = '/RMON:10\/100 Port (\d+) on Unit (\d+)/i'; - $replacement = 'Port${3}/${2}'; - $replacement2 = 'Port${2}/${1}'; - $replacement3 = 'Port${2}/${1}'; - - $local_graph_id = db_fetch_assoc_prepared( - 'SELECT local_graph_id +function complete_3com_ifName(&$device, &$ifIndexes) { + mactrack_debug('Start complete_3com_ifName'); + + // device without ifName detection + foreach ($ifIndexes as $ifidx) { + if ($ifidx['ifName'] != '') { + return; + } + + break; + } + $pattern = '/RMON:V(\d+) Port (\d+) on Unit (\d+)/i'; + $pattern2 = '/RMON Port (\d+) on Unit (\d+)/i'; + $pattern3 = '/RMON:10\/100 Port (\d+) on Unit (\d+)/i'; + $replacement = 'Port${3}/${2}'; + $replacement2 = 'Port${2}/${1}'; + $replacement3 = 'Port${2}/${1}'; + + $local_graph_id = db_fetch_assoc_prepared( + 'SELECT local_graph_id FROM mac_track_interface_graphs WHERE device_id= ?', - [$device['device_id']] - ); - - sort($local_graph_id); - - // Get ifDescr and Format it - $i = 0; - $device_descr_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); - if (cacti_sizeof($device_descr_array)) { - foreach ($device_descr_array as $key => $ifd) { - if ('' == $ifIndexes[$key]['ifName']) { - $ifdesc = $device_descr_array[$key]; - $ifdesc = preg_replace($pattern, $replacement, $ifdesc); - $ifdesc = preg_replace($pattern2, $replacement2, $ifdesc); - $ifdesc = preg_replace($pattern3, $replacement3, $ifdesc); - $ifIndexes[$key]['ifName'] = $ifdesc; - - db_execute_prepared( - 'UPDATE mac_track_interfaces + [$device['device_id']] + ); + + sort($local_graph_id); + + // Get ifDescr and Format it + $i = 0; + $device_descr_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); + + if (cacti_sizeof($device_descr_array)) { + foreach ($device_descr_array as $key => $ifd) { + if ($ifIndexes[$key]['ifName'] == '') { + $ifdesc = $device_descr_array[$key]; + $ifdesc = preg_replace($pattern, $replacement, $ifdesc); + $ifdesc = preg_replace($pattern2, $replacement2, $ifdesc); + $ifdesc = preg_replace($pattern3, $replacement3, $ifdesc); + $ifIndexes[$key]['ifName'] = $ifdesc; + + db_execute_prepared( + 'UPDATE mac_track_interfaces SET ifName = ? WHERE device_id = ? AND ifIndex = ?', - [$ifdesc, $device['device_id'], $key] - ); + [$ifdesc, $device['device_id'], $key] + ); - if ($i < cacti_sizeof($local_graph_id)) { - db_execute( - 'UPDATE mac_track_interface_graphs + if ($i < cacti_sizeof($local_graph_id)) { + db_execute( + 'UPDATE mac_track_interface_graphs SET ifIndex = ?, ifName = ? WHERE device_id = ? AND local_graph_id = ?', - [$key, $ifdesc, $device['device_id'], ${$local_graph_id}[$i]['local_graph_id']] - ); - } - - ++$i; - } - } - } + [$key, $ifdesc, $device['device_id'], ${$local_graph_id}[$i]['local_graph_id']] + ); + } + + ++$i; + } + } + } } /* get_3Com_dot1dTpFdbEntry_ports same as get_dot1dTpFdbEntry_ports with small modification for 3com devices */ -function get_3Com_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; +function get_3Com_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - complete_3com_ifName($device, $ifInterfaces); + complete_3com_ifName($device, $ifInterfaces); - get_3Com_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_3Com_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /* same as get_base_dot1dTpFdbEntry_ports - but add iftype 117 gbit ethernet. */ -function get_3Com_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - mactrack_debug('Start get_3Com_base_dot1dTpFdbEntry_ports'); - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_descr = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // cisco uses a hybrid read string, if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - // get the console port - $link_ports = get_link_port_status($device); - - $i = 0; - foreach ($active_ports_array as $port_info) { - if ((6 == $ifInterfaces[$indexes[$i]]['ifType']) && (1 != $ifInterfaces[$indexes[$i]]['linkPort'])) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - // get bridge port to ifIndex mapping - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - // get device active port numbers - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - // get the ignore ports list from device - // $device['ignorePorts'] = $device['ignorePorts'].':Port1/50'; - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - foreach ($port_numbers as $key => $port_number) { - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort))) { - $ifname = $ifInterfaces[$bridgePortIfIndexes[$port_number]]['ifName']; - if (!in_array($ifname, $ignore_ports)) { - if (isset($port_status[$key]) && '3' == $port_status[$key]) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - ++$i; - } - } - } - } - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (0 != cacti_sizeof($bridgePortIfIndexes)) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - } else { - $brPortIfIndex = isset($port_key['port_number']) ? $port_key['port_number'] : ''; - } - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if (((($brPortIfType >= 6) - && ($brPortIfType <= 9)) || 117 == $brPortIfType) - && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $new_port_key_array[$i]['port_name'] = $ifInterfaces[$brPortIfIndex]['ifName']; - - ++$i; - } - } - } - mactrack_debug('Port number information collected.'); - - // map mac address - // only continue if there were user ports defined - if (cacti_sizeof($new_port_key_array) > 0) { - // get the bridges active MAC addresses - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_3Com_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + mactrack_debug('Start get_3Com_base_dot1dTpFdbEntry_ports'); + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_descr = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + // get the console port + $link_ports = get_link_port_status($device); + + $i = 0; + + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] == 6) && ($ifInterfaces[$indexes[$i]]['linkPort'] != 1)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + // get the ignore ports list from device + // $device['ignorePorts'] = $device['ignorePorts'].':Port1/50'; + $ignore_ports = port_list_to_array($device['ignorePorts']); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + foreach ($port_numbers as $key => $port_number) { + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + $ifname = $ifInterfaces[$bridgePortIfIndexes[$port_number]]['ifName']; + + if (!in_array($ifname, $ignore_ports, true)) { + if (isset($port_status[$key]) && $port_status[$key] == '3') { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + ++$i; + } + } + } + } + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes) != 0) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + } else { + $brPortIfIndex = isset($port_key['port_number']) ? $port_key['port_number'] : ''; + } + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if (((($brPortIfType >= 6) + && ($brPortIfType <= 9)) || $brPortIfType == 117) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + $new_port_key_array[$i]['port_name'] = $ifInterfaces[$brPortIfIndex]['ifName']; + + ++$i; + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array) > 0) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } diff --git a/lib/mactrack_aruba_oscx.php b/lib/mactrack_aruba_oscx.php index a85441b8..7b5d62ef 100644 --- a/lib/mactrack_aruba_oscx.php +++ b/lib/mactrack_aruba_oscx.php @@ -25,465 +25,470 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_aruba_oscx_switch_ports'); if (!isset($mactrack_scanning_functions_ip)) { - $mactrack_scanning_functions_ip = []; + $mactrack_scanning_functions_ip = []; } array_push($mactrack_scanning_functions_ip, 'get_aruba_oscx_arp_table'); -function oscx_mac($mac) -{ - $slabiky = explode('.', trim($mac)); - $mac = ''; +function oscx_mac($mac) { + $slabiky = explode('.', trim($mac)); + $mac = ''; - for ($f = 0; $f < 6; ++$f) { - $slabiky[$f] = strtoupper(dechex($slabiky[$f])); - if (strlen($slabiky[$f]) < 2) { - $slabiky[$f] = '0'.$slabiky[$f]; - } - } + for ($f = 0; $f < 6; ++$f) { + $slabiky[$f] = strtoupper(dechex($slabiky[$f])); - return implode(':', $slabiky); + if (strlen($slabiky[$f]) < 2) { + $slabiky[$f] = '0' . $slabiky[$f]; + } + } + + return implode(':', $slabiky); } -function get_aruba_oscx_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - - /* - get VLAN information - .1.3.6.1.2.1.47.1.2.1.1.2 - .1.3.6.1.2.1.47.1.2.1.1.2.1 = STRING: "DEFAULT_VLAN_1" - .1.3.6.1.2.1.47.1.2.1.1.2.11 = STRING: "guest" - .1.3.6.1.2.1.47.1.2.1.1.2.199 = STRING: "management" - .1.3.6.1.2.1.47.1.2.1.1.2.215 = STRING: "x" - */ - - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); - - foreach ($vlan_names as $key => $value) { - $vlan_ids[$key] = $key; - } - - $device['vlans_total'] = cacti_sizeof($vlan_names); - mactrack_debug('There are '.cacti_sizeof($vlan_names).' VLANS.'); - - /* - vlan_ids: - array(8) { - [1]=> - string(1) "1" - [102]=> - string(3) "102" - [103]=> - string(3) "103" - [122]=> - string(3) "122" - - vlan_names: - array(8) { - [1]=> - string(9) "VLAN 0001" - [102]=> - string(6) "kamery" - [103]=> - string(8) "technici" - [122]=> - string(10) "vlan122-pc" - [144]=> - string(11) "test 802.1x" - */ - - /* - ports vlan membership - .1.3.6.1.2.1.17.7.1.2.2 - tady je i cislo vlany, je to prvni kousek indexu, pak je mac adresa - last six - mac address, before - vlanid - .1.3.6.1.2.1.17.7.1.2.2.1.2.11.0.12.41.5.138.209 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.9.15.9.0.18 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.5.138.209 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.48.235.60 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.30.193.124.199.1 = INTEGER: 52 - .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.80.86.175.58.24 = INTEGER: 52 - */ - - $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); - $port_vlan_data = []; - - foreach ($xdata as $key => $value) { - $keys = explode('.', $key); - // it doesn't work for trunk ports. It If port has more vlans, last is used - if (!isset($port_vlan_data[$value])) { - $port_vlan_data[$value] = $keys[0]; - } - } - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete: '.cacti_sizeof($ifIndexes)); - - // get and store the interfaces table - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - - foreach ($ifIndexes as $ifIndex) { - if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { - ++$device['ports_total']; - } - } - mactrack_debug('ifInterfaces assembly complete: '.cacti_sizeof($ifIndexes)); - - // map vlans to bridge ports - if (cacti_sizeof($vlan_ids) > 0) { - // get the port status information - - $port_results = get_aruba_oscx_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); - - // get the ifIndexes for the device - $i = 0; - $j = 0; - $port_array = []; - foreach ($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - - $ifType = $ifInterfaces[$ifIndex]['ifType']; - - // only output legitimate end user ports - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); - $port_array[$i]['vlan_name'] = isset($vlan_names[$port_array[$i]['vlan_id']]) ? $vlan_names[$port_array[$i]['vlan_id']] : ''; - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' - .'NAME: '.$port_array[$i]['vlan_name'].', ' - .'PORT: '.$ifInterfaces[$ifIndex]['ifName'].', ' - .'NAME: '.$port_array[$i]['port_name'].', ' - .'MAC: '.$port_array[$i]['mac_address']); - - ++$i; - } - - ++$j; - } - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.trim(substr($device['snmp_sysDescr'], 0, 40)).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - mactrack_debug('macs active on this switch:'.$device['macs_active']); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_aruba_oscx_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + + /* + get VLAN information + .1.3.6.1.2.1.47.1.2.1.1.2 + .1.3.6.1.2.1.47.1.2.1.1.2.1 = STRING: "DEFAULT_VLAN_1" + .1.3.6.1.2.1.47.1.2.1.1.2.11 = STRING: "guest" + .1.3.6.1.2.1.47.1.2.1.1.2.199 = STRING: "management" + .1.3.6.1.2.1.47.1.2.1.1.2.215 = STRING: "x" + */ + + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); + + foreach ($vlan_names as $key => $value) { + $vlan_ids[$key] = $key; + } + + $device['vlans_total'] = cacti_sizeof($vlan_names); + mactrack_debug('There are ' . cacti_sizeof($vlan_names) . ' VLANS.'); + + /* + vlan_ids: + array(8) { + [1]=> + string(1) "1" + [102]=> + string(3) "102" + [103]=> + string(3) "103" + [122]=> + string(3) "122" + + vlan_names: + array(8) { + [1]=> + string(9) "VLAN 0001" + [102]=> + string(6) "kamery" + [103]=> + string(8) "technici" + [122]=> + string(10) "vlan122-pc" + [144]=> + string(11) "test 802.1x" + */ + + /* + ports vlan membership + .1.3.6.1.2.1.17.7.1.2.2 - tady je i cislo vlany, je to prvni kousek indexu, pak je mac adresa + last six - mac address, before - vlanid + .1.3.6.1.2.1.17.7.1.2.2.1.2.11.0.12.41.5.138.209 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.9.15.9.0.18 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.5.138.209 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.12.41.48.235.60 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.30.193.124.199.1 = INTEGER: 52 + .1.3.6.1.2.1.17.7.1.2.2.1.2.199.0.80.86.175.58.24 = INTEGER: 52 + */ + + $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); + $port_vlan_data = []; + + foreach ($xdata as $key => $value) { + $keys = explode('.', $key); + + // it doesn't work for trunk ports. It If port has more vlans, last is used + if (!isset($port_vlan_data[$value])) { + $port_vlan_data[$value] = $keys[0]; + } + } + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete: ' . cacti_sizeof($ifIndexes)); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + + foreach ($ifIndexes as $ifIndex) { + if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { + ++$device['ports_total']; + } + } + mactrack_debug('ifInterfaces assembly complete: ' . cacti_sizeof($ifIndexes)); + + // map vlans to bridge ports + if (cacti_sizeof($vlan_ids) > 0) { + // get the port status information + + $port_results = get_aruba_oscx_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); + + // get the ifIndexes for the device + $i = 0; + $j = 0; + $port_array = []; + + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + + $ifType = $ifInterfaces[$ifIndex]['ifType']; + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); + $port_array[$i]['vlan_name'] = isset($vlan_names[$port_array[$i]['vlan_id']]) ? $vlan_names[$port_array[$i]['vlan_id']] : ''; + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' + . 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' + . 'PORT: ' . $ifInterfaces[$ifIndex]['ifName'] . ', ' + . 'NAME: ' . $port_array[$i]['port_name'] . ', ' + . 'MAC: ' . $port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . trim(substr($device['snmp_sysDescr'], 0, 40)) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + mactrack_debug('macs active on this switch:' . $device['macs_active']); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_base_dot1dTpFdbEntry_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. This is a foundational function for all vendor data collection functions. */ -function get_aruba_oscx_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - mactrack_debug('FUNCTION: get_aruba_oscx_dot1dTpFdbEntry_ports started'); - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // cisco uses a hybrid read string, if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - mactrack_debug('get active ports: '.cacti_sizeof($active_ports_array)); - $indexes = array_keys($active_ports_array); - - $i = 0; - foreach ($active_ports_array as $port_info) { - if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 - where - table index = bridge port (dot1dBasePort) and - table value = ifIndex */ - // -------------------------------------------- - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('get bridgePortIfIndexes: '.cacti_sizeof($bridgePortIfIndexes)); - - /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ - // -------------------------------------------- - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - mactrack_debug('get port_status: '.cacti_sizeof($port_status)); - - /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = bridge port */ - // -------------------------------------------- - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - mactrack_debug('get port_numbers: '.cacti_sizeof($port_numbers)); - - // get VLAN information - // -------------------------------------------- - - $vlan_ids = []; - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); - foreach ($vlan_names as $key => $value) { - $vlan_ids[$key] = $key; - } - - mactrack_debug('get vlan_ids: '.cacti_sizeof($vlan_ids)); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); - $port_vlan_data = []; - - foreach ($xdata as $key => $value) { - $keys = explode('.', $key); - $port_vlan_data[$value] = $keys[0]; - } - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - foreach ($port_numbers as $key => $port_number) { - // key = MAC Address from dot1dTpFdbTable - // value = bridge port - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort))) { - if (!in_array($port_number, $ignore_ports)) { - if (isset($port_status[$key]) && '3' == $port_status[$key]) { - $port_key_array[$i]['key'] = substr($key, 1); - $port_key_array[$i]['port_number'] = $port_number; - ++$i; - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - - $i = 0; - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (0 != cacti_sizeof($bridgePortIfIndexes)) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - mactrack_debug('Searching Bridge Port: '.$port_key['port_number'].', Bridge: '.$bridgePortIfIndexes[$port_key['port_number']]); - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - } else { - $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); - } - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if (($brPortIfType >= 6) - && ($brPortIfType <= 9) - && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); - $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; - $new_port_key_array[$i]['port_name'] = mactrack_arr_key($ifInterfaces, $port_key['port_number']); - $new_port_key_array[$i]['mac_address'] = oscx_mac($port_key['key']); - $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $brPortIfIndex); - $new_port_key_array[$i]['vlan_name'] = isset($brPortIfIndex) ? mactrack_arr_key($vlan_names, $port_vlan_data[$brPortIfIndex]) : ''; - - ++$i; - } - } - } - mactrack_debug('Port number information collected: '.cacti_sizeof($new_port_key_array)); - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_aruba_oscx_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + mactrack_debug('FUNCTION: get_aruba_oscx_dot1dTpFdbEntry_ports started'); + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + mactrack_debug('get active ports: ' . cacti_sizeof($active_ports_array)); + $indexes = array_keys($active_ports_array); + + $i = 0; + + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 + where + table index = bridge port (dot1dBasePort) and + table value = ifIndex */ + // -------------------------------------------- + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('get bridgePortIfIndexes: ' . cacti_sizeof($bridgePortIfIndexes)); + + /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ + // -------------------------------------------- + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + mactrack_debug('get port_status: ' . cacti_sizeof($port_status)); + + /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = bridge port */ + // -------------------------------------------- + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + mactrack_debug('get port_numbers: ' . cacti_sizeof($port_numbers)); + + // get VLAN information + // -------------------------------------------- + + $vlan_ids = []; + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.47.1.2.1.1.2', $device); + + foreach ($vlan_names as $key => $value) { + $vlan_ids[$key] = $key; + } + + mactrack_debug('get vlan_ids: ' . cacti_sizeof($vlan_ids)); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 7); + $port_vlan_data = []; + + foreach ($xdata as $key => $value) { + $keys = explode('.', $key); + $port_vlan_data[$value] = $keys[0]; + } + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + foreach ($port_numbers as $key => $port_number) { + // key = MAC Address from dot1dTpFdbTable + // value = bridge port + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports, true)) { + if (isset($port_status[$key]) && $port_status[$key] == '3') { + $port_key_array[$i]['key'] = substr($key, 1); + $port_key_array[$i]['port_number'] = $port_number; + ++$i; + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + + $i = 0; + + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes) != 0) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + mactrack_debug('Searching Bridge Port: ' . $port_key['port_number'] . ', Bridge: ' . $bridgePortIfIndexes[$port_key['port_number']]); + + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + } else { + $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); + } + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if (($brPortIfType >= 6) + && ($brPortIfType <= 9) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); + $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; + $new_port_key_array[$i]['port_name'] = mactrack_arr_key($ifInterfaces, $port_key['port_number']); + $new_port_key_array[$i]['mac_address'] = oscx_mac($port_key['key']); + $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $brPortIfIndex); + $new_port_key_array[$i]['vlan_name'] = isset($brPortIfIndex) ? mactrack_arr_key($vlan_names, $port_vlan_data[$brPortIfIndex]) : ''; + + ++$i; + } + } + } + mactrack_debug('Port number information collected: ' . cacti_sizeof($new_port_key_array)); + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /* get_aruba_oscx_arp_table - This function reads a devices CTAlias table for a site and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_aruba_oscx_arp_table($site, &$device) -{ - global $debug, $scan_date; - - mactrack_debug('FUNCTION: get_aruba_oscx_arp_table started'); - - /* - joining mac = port with ip = mac - 1.3.6.1.2.1.17.7.1.2.2.1.2 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.2.209.50.110.192 = INTEGER: 28 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.9.15.9.0.18 = INTEGER: 28 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.11.134.101.90.128 = INTEGER: 28 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.12.41.187.210.4 = INTEGER: 28 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.16.116.104.90.49 = INTEGER: 28 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.17.50.44.9.137 = INTEGER: 28 - .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.22.108.186.185.185 = INTEGER: 28 - - .1.3.6.1.2.1.4.35.1.4 - .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.95 = STRING: 4c:ae:a3:64:5a:cb - .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.96 = STRING: 4c:ae:a3:64:50:ab - .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.97 = STRING: 40:b9:3c:4b:9c:de - .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.98 = STRING: ec:9b:8b:78:9b:d7 - */ - - $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 6); - $port_vlan_data = []; - - foreach ($xdata as $key => $value) { - $mac_port[oscx_mac($key)] = $value; - } - - $xdata = xform_indexed_data('.1.3.6.1.2.1.4.35.1.4', $device, 4); - foreach ($xdata as $key => $value) { - $ip_mac[$key] = strtr($value, ' ', ':'); - } - - $result = []; - - foreach ($ip_mac as $key => $value) { - if (isset($mac_port[$value])) { - $result[$key]['port'] = $mac_port[$value]; - $result[$key]['mac'] = $value; - } - } - - mactrack_debug('arp assembly complete.'); - - // output details to database - if (cacti_sizeof($result)) { - $sql = []; - - foreach ($result as $key => $value) { - $sql[] = '(' - .$device['site_id'].', ' - .$device['device_id'].', ' - .db_qstr($device['hostname']).', ' - .db_qstr($device['device_name']).', ' - .db_qstr($value['port']).', ' - .db_qstr($value['mac']).', ' - .db_qstr($key).', ' - .db_qstr($scan_date).')'; - } - - if (cacti_sizeof($sql)) { - db_execute('REPLACE INTO mac_track_ips +function get_aruba_oscx_arp_table($site, &$device) { + global $debug, $scan_date; + + mactrack_debug('FUNCTION: get_aruba_oscx_arp_table started'); + + /* + joining mac = port with ip = mac + 1.3.6.1.2.1.17.7.1.2.2.1.2 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.2.209.50.110.192 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.9.15.9.0.18 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.11.134.101.90.128 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.12.41.187.210.4 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.16.116.104.90.49 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.17.50.44.9.137 = INTEGER: 28 + .1.3.6.1.2.1.17.7.1.2.2.1.2.1.0.22.108.186.185.185 = INTEGER: 28 + + .1.3.6.1.2.1.4.35.1.4 + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.95 = STRING: 4c:ae:a3:64:5a:cb + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.96 = STRING: 4c:ae:a3:64:50:ab + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.97 = STRING: 40:b9:3c:4b:9c:de + .1.3.6.1.2.1.4.35.1.4.16777415.1.4.192.168.199.98 = STRING: ec:9b:8b:78:9b:d7 + */ + + $xdata = xform_indexed_data('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, 6); + $port_vlan_data = []; + + foreach ($xdata as $key => $value) { + $mac_port[oscx_mac($key)] = $value; + } + + $xdata = xform_indexed_data('.1.3.6.1.2.1.4.35.1.4', $device, 4); + + foreach ($xdata as $key => $value) { + $ip_mac[$key] = strtr($value, ' ', ':'); + } + + $result = []; + + foreach ($ip_mac as $key => $value) { + if (isset($mac_port[$value])) { + $result[$key]['port'] = $mac_port[$value]; + $result[$key]['mac'] = $value; + } + } + + mactrack_debug('arp assembly complete.'); + + // output details to database + if (cacti_sizeof($result)) { + $sql = []; + + foreach ($result as $key => $value) { + $sql[] = '(' + . $device['site_id'] . ', ' + . $device['device_id'] . ', ' + . db_qstr($device['hostname']) . ', ' + . db_qstr($device['device_name']) . ', ' + . db_qstr($value['port']) . ', ' + . db_qstr($value['mac']) . ', ' + . db_qstr($key) . ', ' + . db_qstr($scan_date) . ')'; + } + + if (cacti_sizeof($sql)) { + db_execute('REPLACE INTO mac_track_ips (site_id, device_id, hostname, device_name, port_number, mac_address,ip_address,scan_date) - VALUES '.implode(', ', $sql)); - } - } + VALUES ' . implode(', ', $sql)); + } + } - // save ip information for the device - $device['ips_total'] = cacti_sizeof($result); + // save ip information for the device + $device['ips_total'] = cacti_sizeof($result); - db_execute_prepared( - 'UPDATE mac_track_devices + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - [$device['ips_total'], $device['device_id']] - ); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete. IP='.cacti_sizeof($result).'.'); + mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete. IP=' . cacti_sizeof($result) . '.'); } diff --git a/lib/mactrack_cabletron.php b/lib/mactrack_cabletron.php index 6555d3a3..3f02e56a 100644 --- a/lib/mactrack_cabletron.php +++ b/lib/mactrack_cabletron.php @@ -25,348 +25,349 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_cabletron_switch_ports'); array_push($mactrack_scanning_functions, 'get_repeater_rev4_ports'); -function get_cabletron_switch_ports($site, &$device, $lowPort, $highPort) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); - - // get and store the interfaces table - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, false, false); - - $securefast_marker = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.4.1.52.4.2.4.2.1.1.1.1.1.1.1', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - mactrack_debug('Cabletron securefast marker obtained'); - - if (empty($securefast_marker)) { - get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - } else { - get_base_sfps_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - } - - return $device; +function get_cabletron_switch_ports($site, &$device, $lowPort, $highPort) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, false, false); + + $securefast_marker = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.4.1.52.4.2.4.2.1.1.1.1.1.1.1', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + mactrack_debug('Cabletron securefast marker obtained'); + + if (empty($securefast_marker)) { + get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + } else { + get_base_sfps_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + } + + return $device; } -function get_base_sfps_ports($site, &$device, &$ifInterfaces, $snmp_readstring, $store_to_db, $lowPort, $highPort) -{ - global $debug, $scan_date; - - // initialize variables - $port_number = 0; - $ports_active = 0; - $ports_total = 0; - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - // get the ignore ports list - $ignore_ports = port_list_to_array($device['ignorePorts']); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - } - - // now obtain securefast port information - $sfps_A_ports = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.6', $device, 3); - $sfps_A_mac_addresses = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.8', $device, 3, true); - - $sfps_A_keys = array_keys($sfps_A_ports); - $sfps_A_size = cacti_sizeof($sfps_A_ports); - - $j = 0; - $i = 0; - while ($j < $sfps_A_size) { - $port_number = $sfps_A_ports[$sfps_A_keys[$j]]; - $mac_address = $sfps_A_mac_addresses[$sfps_A_keys[$j]]; - - if (($port_number >= $lowPort) && ($port_number <= $highPort)) { - if (!in_array($port_number, $ignore_ports)) { - $temp_port_A_array[$i]['port_number'] = $port_number; - $temp_port_A_array[$i]['mac_address'] = xform_mac_address($mac_address); - ++$i; - } - } - ++$j; - } - - $j = 0; - $port_array = []; - for ($i = 0; $i < cacti_sizeof($temp_port_A_array); ++$i) { - $port_array[$temp_port_A_array[$i]['port_number']]['vlan_id'] = 'N/A'; - $port_array[$temp_port_A_array[$i]['port_number']]['vlan_name'] = 'N/A'; - $port_array[$temp_port_A_array[$i]['port_number']]['port_name'] = 'N/A'; - $port_array[$temp_port_A_array[$i]['port_number']]['port_number'] = $temp_port_A_array[$i]['port_number']; - $port_array[$temp_port_A_array[$i]['port_number']]['mac_address'] = $temp_port_A_array[$i]['mac_address']; - } - - if ($store_to_db) { - if (cacti_sizeof($port_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $port_array; - } +function get_base_sfps_ports($site, &$device, &$ifInterfaces, $snmp_readstring, $store_to_db, $lowPort, $highPort) { + global $debug, $scan_date; + + // initialize variables + $port_number = 0; + $ports_active = 0; + $ports_total = 0; + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + // get the ignore ports list + $ignore_ports = port_list_to_array($device['ignorePorts']); + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + } + + // now obtain securefast port information + $sfps_A_ports = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.6', $device, 3); + $sfps_A_mac_addresses = xform_indexed_data('.1.3.6.1.4.1.52.4.2.4.2.2.3.6.1.1.8', $device, 3, true); + + $sfps_A_keys = array_keys($sfps_A_ports); + $sfps_A_size = cacti_sizeof($sfps_A_ports); + + $j = 0; + $i = 0; + + while ($j < $sfps_A_size) { + $port_number = $sfps_A_ports[$sfps_A_keys[$j]]; + $mac_address = $sfps_A_mac_addresses[$sfps_A_keys[$j]]; + + if (($port_number >= $lowPort) && ($port_number <= $highPort)) { + if (!in_array($port_number, $ignore_ports, true)) { + $temp_port_A_array[$i]['port_number'] = $port_number; + $temp_port_A_array[$i]['mac_address'] = xform_mac_address($mac_address); + ++$i; + } + } + ++$j; + } + + $j = 0; + $port_array = []; + + for ($i = 0; $i < cacti_sizeof($temp_port_A_array); ++$i) { + $port_array[$temp_port_A_array[$i]['port_number']]['vlan_id'] = 'N/A'; + $port_array[$temp_port_A_array[$i]['port_number']]['vlan_name'] = 'N/A'; + $port_array[$temp_port_A_array[$i]['port_number']]['port_name'] = 'N/A'; + $port_array[$temp_port_A_array[$i]['port_number']]['port_number'] = $temp_port_A_array[$i]['port_number']; + $port_array[$temp_port_A_array[$i]['port_number']]['mac_address'] = $temp_port_A_array[$i]['mac_address']; + } + + if ($store_to_db) { + if (cacti_sizeof($port_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $port_array; + } } /* get_repeater_snmp_readstring - Cabletron SEHI's are quite odd. They have potentially - 5 distinct snmp_readstrings for each of 5 agent structures. If the read_string - for the port information is different than sysObjectID, then let's find it and - set it. + 5 distinct snmp_readstrings for each of 5 agent structures. If the read_string + for the port information is different than sysObjectID, then let's find it and + set it. */ -function get_repeater_snmp_readstring(&$device) -{ - $active_ports = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $active_ports) { - mactrack_debug('Repeater readstring is: '.$device['snmp_readstring']); - - return $device['snmp_readstring']; - } - // loop through the default and then other common for the correct answer - $read_strings = explode(':', $device['snmp_readstrings']); - - if (cacti_sizeof($read_strings)) { - foreach ($read_strings as $snmp_readstring) { - $active_ports = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $active_ports) { - mactrack_debug('Repeater readstring is: '.$snmp_readstring); - - return $snmp_readstring; - } - } - } - - return ''; +function get_repeater_snmp_readstring(&$device) { + $active_ports = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($active_ports != '') { + mactrack_debug('Repeater readstring is: ' . $device['snmp_readstring']); + + return $device['snmp_readstring']; + } + // loop through the default and then other common for the correct answer + $read_strings = explode(':', $device['snmp_readstrings']); + + if (cacti_sizeof($read_strings)) { + foreach ($read_strings as $snmp_readstring) { + $active_ports = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($active_ports != '') { + mactrack_debug('Repeater readstring is: ' . $snmp_readstring); + + return $snmp_readstring; + } + } + } + + return ''; } -function get_repeater_rev4_ports($site, &$device, $lowPort, $highPort) -{ - global $debug, $scan_date; - - $snmp_readstring = get_repeater_snmp_readstring($device); - - if ('' != $snmp_readstring) { - $ports_active = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.5.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ) - 1; - - $ports_total = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ) - 1; - - // get the ignore ports list - $ignore_ports = port_list_to_array($device['ignorePorts']); - - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', ACTIVE PORTS: '.$ports_active); - - $device['vlans_total'] = 0; - $device['ports_total'] = $ports_total; - - if ($ports_active >= 0) { - $device['ports_active'] = $ports_active; - } else { - $device['ports_active'] = 0; - } - - if (2 == $device['snmp_version']) { - $snmp_version = '2c'; - } else { - $snmp_version = $device['snmp_version']; - } - - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_number = 0; - $nextOID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.2'; - $to = ceil($device['snmp_timeout'] / 1000); - - $i = 0; - $previous_port = 0; - while (1) { - $exec_string = trim(read_config_option('path_snmpgetnext') - .' -c '.$snmp_readstring - .' -OnUQ -v '.$snmp_version - .' -r '.$device['snmp_retries'] - .' -t '.$to.' ' - .$device['hostname'].':'.$device['snmp_port'].' ' - .$nextOID); - - exec($exec_string, $return_array, $return_code); - - list($nextOID, $port_number) = explode('=', $return_array[$i]); - - if ($port_number < $previous_port) { - break; - } - - if (($port_number <= $highPort) && ($port_number >= $lowPort)) { - if (!in_array($port_number, $ignore_ports)) { - // set defaults for devices in case they don't have/support vlans - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - $new_port_key_array[$i]['key'] = trim(substr($nextOID, 36)); - $new_port_key_array[$i]['port_number'] = trim(strtr($port_number, ' ', '')); - } - - $previous_port = trim(strtr($port_number, ' ', '')); - } else { - break; - } - - mactrack_debug('CMD: '.$exec_string.', PORT: '.$port_number); - ++$i; - $port_number = ''; - } - - if (cacti_sizeof($new_port_key_array) > 0) { - // map mac address - $i = 0; - foreach ($new_port_key_array as $port_key) { - $OID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.1.'.$port_key['key']; - - $mac_address = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - $OID, - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - $new_port_key_array[$i]['mac_address'] = xform_mac_address($mac_address); - - mactrack_debug('OID: '.$OID.', MAC ADDRESS: '.$new_port_key_array[$i]['mac_address']); - ++$i; - } - - $device['last_runmessage'] = 'Data collection completed ok'; - } else { - mactrack_debug('INFO: The following device has no active ports: '.$site.'/'.$device['hostname']); - - $device['last_runmessage'] = 'Data collection completed ok'; - } - } else { - mactrack_debug('ERROR: Could not determine snmp_readstring for host: '.$site.'/'.$device['hostname']); - - $device['snmp_status'] = HOST_ERROR; - $device['last_runmessage'] = 'ERROR: Could not determine snmp_readstring for host.'; - } - - $device['ports_active'] = $ports_active; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - - return $device; +function get_repeater_rev4_ports($site, &$device, $lowPort, $highPort) { + global $debug, $scan_date; + + $snmp_readstring = get_repeater_snmp_readstring($device); + + if ($snmp_readstring != '') { + $ports_active = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.5.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ) - 1; + + $ports_total = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.4.1.52.4.1.1.1.4.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ) - 1; + + // get the ignore ports list + $ignore_ports = port_list_to_array($device['ignorePorts']); + + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', ACTIVE PORTS: ' . $ports_active); + + $device['vlans_total'] = 0; + $device['ports_total'] = $ports_total; + + if ($ports_active >= 0) { + $device['ports_active'] = $ports_active; + } else { + $device['ports_active'] = 0; + } + + if ($device['snmp_version'] == 2) { + $snmp_version = '2c'; + } else { + $snmp_version = $device['snmp_version']; + } + + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_number = 0; + $nextOID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.2'; + $to = ceil($device['snmp_timeout'] / 1000); + + $i = 0; + $previous_port = 0; + + while (1) { + $exec_string = trim(read_config_option('path_snmpgetnext') + . ' -c ' . $snmp_readstring + . ' -OnUQ -v ' . $snmp_version + . ' -r ' . $device['snmp_retries'] + . ' -t ' . $to . ' ' + . $device['hostname'] . ':' . $device['snmp_port'] . ' ' + . $nextOID); + + exec($exec_string, $return_array, $return_code); + + [$nextOID, $port_number] = explode('=', $return_array[$i]); + + if ($port_number < $previous_port) { + break; + } + + if (($port_number <= $highPort) && ($port_number >= $lowPort)) { + if (!in_array($port_number, $ignore_ports, true)) { + // set defaults for devices in case they don't have/support vlans + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + $new_port_key_array[$i]['key'] = trim(substr($nextOID, 36)); + $new_port_key_array[$i]['port_number'] = trim(strtr($port_number, ' ', '')); + } + + $previous_port = trim(strtr($port_number, ' ', '')); + } else { + break; + } + + mactrack_debug('CMD: ' . $exec_string . ', PORT: ' . $port_number); + ++$i; + $port_number = ''; + } + + if (cacti_sizeof($new_port_key_array) > 0) { + // map mac address + $i = 0; + + foreach ($new_port_key_array as $port_key) { + $OID = '.1.3.6.1.4.1.52.4.1.1.1.4.1.5.2.1.1.' . $port_key['key']; + + $mac_address = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + $OID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $new_port_key_array[$i]['mac_address'] = xform_mac_address($mac_address); + + mactrack_debug('OID: ' . $OID . ', MAC ADDRESS: ' . $new_port_key_array[$i]['mac_address']); + ++$i; + } + + $device['last_runmessage'] = 'Data collection completed ok'; + } else { + mactrack_debug('INFO: The following device has no active ports: ' . $site . '/' . $device['hostname']); + + $device['last_runmessage'] = 'Data collection completed ok'; + } + } else { + mactrack_debug('ERROR: Could not determine snmp_readstring for host: ' . $site . '/' . $device['hostname']); + + $device['snmp_status'] = HOST_ERROR; + $device['last_runmessage'] = 'ERROR: Could not determine snmp_readstring for host.'; + } + + $device['ports_active'] = $ports_active; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + + return $device; } diff --git a/lib/mactrack_cisco.php b/lib/mactrack_cisco.php index f8829015..7c14bf77 100644 --- a/lib/mactrack_cisco.php +++ b/lib/mactrack_cisco.php @@ -25,598 +25,607 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_catalyst_dot1dTpFdbEntry_ports'); array_push($mactrack_scanning_functions, 'get_IOS_dot1dTpFdbEntry_ports'); if (!isset($mactrack_scanning_functions_ip)) { - $mactrack_scanning_functions_ip = []; + $mactrack_scanning_functions_ip = []; } array_push($mactrack_scanning_functions_ip, 'get_cisco_dhcpsnooping_table'); array_push($mactrack_scanning_functions_ip, 'get_cisco_vrf_arp_table'); if (!isset($mactrack_scanning_functions_dot1x)) { - $mactrack_scanning_functions_dot1x = []; + $mactrack_scanning_functions_dot1x = []; } array_push($mactrack_scanning_functions_dot1x, 'get_cisco_dot1x_table'); /* get_catalyst_doet1dTpFdbEntry_ports - obtains port associations for Cisco Catalyst Switches. Catalyst - switches are unique in that they support a different snmp_readstring for - every VLAN interface on the switch. + obtains port associations for Cisco Catalyst Switches. Catalyst + switches are unique in that they support a different snmp_readstring for + every VLAN interface on the switch. */ -function get_catalyst_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - - // Variables to determine VLAN information - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); - $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); - - $device['vlans_total'] = cacti_sizeof($vlan_ids) - 3; - mactrack_debug('There are '.(cacti_sizeof($vlan_ids) - 3).' VLANS.'); - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); - - // get and store the interfaces table - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - - // get the Voice VLAN information if it exists - $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); - if (cacti_sizeof($portVoiceVLANs)) { - $vvlans = true; - } else { - $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); - if (cacti_sizeof($portVoiceVLANs)) { - $vvlans = true; - } else { - $vvlans = false; - } - } - mactrack_debug('Cisco Voice VLAN collection complete'); - if ($vvlans) { - mactrack_debug('Voice VLANs exist on this device'); - } else { - mactrack_debug('Voice VLANs do not exist on this device'); - } - - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['trunkPortState'] = isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''; - if ($vvlans) { - $ifInterfaces[$ifIndex]['vVlanID'] = isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''; - } - - if (6 == $ifInterfaces[$ifIndex]['ifType']) { - ++$device['ports_total']; - } - } - } - mactrack_debug('ifInterfaces assembly complete.'); - - // get the portNames - $portNames = xform_cisco_workgroup_port_data('.1.3.6.1.4.1.9.5.1.4.1.1.4', $device); - mactrack_debug('portNames data collected.'); - - // get trunking status - $portTrunking = xform_cisco_workgroup_port_data('.1.3.6.1.4.1.9.5.1.9.3.1.8', $device); - mactrack_debug('portTrunking data collected.'); - - // calculate the number of end user ports - if (cacti_sizeof($portTrunking)) { - foreach ($portTrunking as $portTrunk) { - if (1 == $portTrunk) { - ++$device['ports_trunk']; - } - } - } - - // build VLAN array from results - $i = 0; - $j = 0; - $active_vlans = []; - - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_number => $vlanStatus) { - $vlanName = $vlan_names[$vlan_number]; - - if (1 == $vlanStatus) { // vlan is operatinal - switch ($vlan_number) { - case '1002': - case '1003': - case '1004': - case '1005': - $active_vlan_ports = 0; - - break; - - default: - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'].'@'.$vlan_number; - $active_vlan_ports = cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - SNMP_POLLER, - $device['snmp_engine_id'] - ); - } else { - $active_vlan_ports = cacti_snmp_get( - $device['hostname'], - '', - '.1.3.6.1.2.1.17.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - 'vlan-'.$vlan_number, - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - SNMP_POLLER, - $device['snmp_engine_id'] - ); - } - - if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { - $active_vlan_ports = 0; - } - - mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is complete. ACTIVE PORTS: '.$active_vlan_ports); - - if ($active_vlan_ports > 0) { // does the vlan have active ports on it - $active_vlans[$j]['vlan_id'] = $vlan_number; - $active_vlans[$j]['vlan_name'] = $vlanName; - $active_vlans[$j]['active_ports'] = $active_vlan_ports; - - // Commented out because why wuuld you increment an array!! - // $active_vlans++; - - ++$j; - } - } - } - - ++$i; - } - } - - if (cacti_sizeof($active_vlans)) { - $i = 0; - // get the port status information - foreach ($active_vlans as $active_vlan) { - // ignore empty vlans - if ($active_vlan['active_ports'] <= $device['ports_trunk']) { - $active_vlans[$i]['port_results'] = []; - ++$i; - - continue; - } - - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'].'@'.$active_vlan['vlan_id']; - } else { - $snmp_readstring = 'cisco@'.$active_vlan['vlan_id']; - } - - mactrack_debug('Processing has begun for VLAN: '.$active_vlan['vlan_id']); - - if (0 == $highPort) { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); - } else { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); - } - - // get bridge port mappings - // get bridge port to ifIndex mappings - mactrack_debug('Bridge port information about to be collected.'); - mactrack_debug('VLAN_ID: '.$active_vlans[$i]['vlan_id'].', VLAN_NAME: '.$active_vlans[$i]['vlan_name'].', ACTIVE PORTS: '.cacti_sizeof($active_vlans[$i]['port_results'])); - - if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { - $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('Bridge port information collection complete.'); - } - - ++$i; - } - - mactrack_debug('Final cross check\'s now being performed.'); - $i = 0; - $j = 0; - $port_array = []; - - if (cacti_sizeof($active_vlans)) { - foreach ($active_vlans as $active_vlan) { - if (cacti_sizeof($active_vlan['port_results'])) { - foreach ($active_vlan['port_results'] as $port_result) { - $ifIndex = isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''; - $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); - $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); - $portName = (isset($portNames[$ifName]) ? $portNames[$ifName] : ''); - $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); - $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); - - if ($vvlans) { - $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); - } else { - $vVlanID = -1; - } - - // only output legitimate end user ports - if ((6 == $ifType) && (2 == $portTrunk)) { - if (('2' == $portTrunkStatus) || ('4' == $portTrunkStatus) || ('' == $portTrunkStatus)) { - $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; - $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; - $port_array[$i]['port_number'] = $ifInterfaces[$ifIndex]['ifName']; - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - ++$i; - - mactrack_debug('VLAN: '.$active_vlan['vlan_id'].', ' - .'NAME: '.$active_vlan['vlan_name'].', ' - .'PORT: '.$ifInterfaces[$ifIndex]['ifName'].', ' - .'NAME: '.$portName.', ' - .'MAC: '.$port_result['mac_address']); - } - } - } - } - - ++$j; - } - } - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_catalyst_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // Variables to determine VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); + + $device['vlans_total'] = cacti_sizeof($vlan_ids) - 3; + mactrack_debug('There are ' . (cacti_sizeof($vlan_ids) - 3) . ' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + + // get the Voice VLAN information if it exists + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); + + if (cacti_sizeof($portVoiceVLANs)) { + $vvlans = true; + } else { + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); + + if (cacti_sizeof($portVoiceVLANs)) { + $vvlans = true; + } else { + $vvlans = false; + } + } + mactrack_debug('Cisco Voice VLAN collection complete'); + + if ($vvlans) { + mactrack_debug('Voice VLANs exist on this device'); + } else { + mactrack_debug('Voice VLANs do not exist on this device'); + } + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['trunkPortState'] = isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''; + + if ($vvlans) { + $ifInterfaces[$ifIndex]['vVlanID'] = isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''; + } + + if ($ifInterfaces[$ifIndex]['ifType'] == 6) { + ++$device['ports_total']; + } + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // get the portNames + $portNames = xform_cisco_workgroup_port_data('.1.3.6.1.4.1.9.5.1.4.1.1.4', $device); + mactrack_debug('portNames data collected.'); + + // get trunking status + $portTrunking = xform_cisco_workgroup_port_data('.1.3.6.1.4.1.9.5.1.9.3.1.8', $device); + mactrack_debug('portTrunking data collected.'); + + // calculate the number of end user ports + if (cacti_sizeof($portTrunking)) { + foreach ($portTrunking as $portTrunk) { + if ($portTrunk == 1) { + ++$device['ports_trunk']; + } + } + } + + // build VLAN array from results + $i = 0; + $j = 0; + $active_vlans = []; + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_number => $vlanStatus) { + $vlanName = $vlan_names[$vlan_number]; + + if ($vlanStatus == 1) { // vlan is operatinal + switch ($vlan_number) { + case '1002': + case '1003': + case '1004': + case '1005': + $active_vlan_ports = 0; + + break; + default: + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'] . '@' . $vlan_number; + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } else { + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + '', + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + 'vlan-' . $vlan_number, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } + + if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { + $active_vlan_ports = 0; + } + + mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is complete. ACTIVE PORTS: ' . $active_vlan_ports); + + if ($active_vlan_ports > 0) { // does the vlan have active ports on it + $active_vlans[$j]['vlan_id'] = $vlan_number; + $active_vlans[$j]['vlan_name'] = $vlanName; + $active_vlans[$j]['active_ports'] = $active_vlan_ports; + + // Commented out because why wuuld you increment an array!! + // $active_vlans++; + + ++$j; + } + } + } + + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + $i = 0; + + // get the port status information + foreach ($active_vlans as $active_vlan) { + // ignore empty vlans + if ($active_vlan['active_ports'] <= $device['ports_trunk']) { + $active_vlans[$i]['port_results'] = []; + ++$i; + + continue; + } + + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'] . '@' . $active_vlan['vlan_id']; + } else { + $snmp_readstring = 'cisco@' . $active_vlan['vlan_id']; + } + + mactrack_debug('Processing has begun for VLAN: ' . $active_vlan['vlan_id']); + + if ($highPort == 0) { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); + } else { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); + } + + // get bridge port mappings + // get bridge port to ifIndex mappings + mactrack_debug('Bridge port information about to be collected.'); + mactrack_debug('VLAN_ID: ' . $active_vlans[$i]['vlan_id'] . ', VLAN_NAME: ' . $active_vlans[$i]['vlan_name'] . ', ACTIVE PORTS: ' . cacti_sizeof($active_vlans[$i]['port_results'])); + + if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { + $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('Bridge port information collection complete.'); + } + + ++$i; + } + + mactrack_debug('Final cross check\'s now being performed.'); + $i = 0; + $j = 0; + $port_array = []; + + if (cacti_sizeof($active_vlans)) { + foreach ($active_vlans as $active_vlan) { + if (cacti_sizeof($active_vlan['port_results'])) { + foreach ($active_vlan['port_results'] as $port_result) { + $ifIndex = isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''; + $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); + $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); + $portName = (isset($portNames[$ifName]) ? $portNames[$ifName] : ''); + $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); + $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); + + if ($vvlans) { + $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); + } else { + $vVlanID = -1; + } + + // only output legitimate end user ports + if (($ifType == 6) && ($portTrunk == 2)) { + if (($portTrunkStatus == '2') || ($portTrunkStatus == '4') || ($portTrunkStatus == '')) { + $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; + $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; + $port_array[$i]['port_number'] = $ifInterfaces[$ifIndex]['ifName']; + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + ++$i; + + mactrack_debug('VLAN: ' . $active_vlan['vlan_id'] . ', ' + . 'NAME: ' . $active_vlan['vlan_name'] . ', ' + . 'PORT: ' . $ifInterfaces[$ifIndex]['ifName'] . ', ' + . 'NAME: ' . $portName . ', ' + . 'MAC: ' . $port_result['mac_address']); + } + } + } + } + + ++$j; + } + } + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_IOS_dot1dTpFdbEntry_ports - obtains port associations for Cisco Catalyst Switches. Catalyst - switches are unique in that they support a different snmp_readstring for - every VLAN interface on the switch. + obtains port associations for Cisco Catalyst Switches. Catalyst + switches are unique in that they support a different snmp_readstring for + every VLAN interface on the switch. */ -function get_IOS_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - $ifIndexes = []; - - // get and store the interfaces table - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - - // Variables to determine VLAN information - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); - $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); - - $device['vlans_total'] = cacti_sizeof($vlan_ids) - 4; - mactrack_debug('There are '.(cacti_sizeof($vlan_ids) - 4).' VLANS.'); - - if (0 == cacti_sizeof($vlan_names)) { - cacti_log('No VLANs Name found: '.$device['device_name']); - - return $device; - } - - if (0 == cacti_sizeof($vlan_trunkstatus)) { - cacti_log('No VLANs Trunk Status found: '.$device['device_name']); - - return $device; - } - - // get the Voice VLAN information if it exists - $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); - if (cacti_sizeof($portVoiceVLANs) > 0) { - $vvlans = true; - } else { - $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); - if (cacti_sizeof($portVoiceVLANs) > 0) { - $vvlans = true; - } else { - $vvlans = false; - } - } - - mactrack_debug('Cisco Voice VLAN collection complete'); - if ($vvlans) { - mactrack_debug('Voice VLANs exist on this device'); - } else { - mactrack_debug('Voice VLANs do not exist on this device'); - } - - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['trunkPortState'] = (isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''); - if ($vvlans) { - $ifInterfaces[$ifIndex]['vVlanID'] = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); - } - - if (6 == $ifInterfaces[$ifIndex]['ifType']) { - ++$device['ports_total']; - } - - if ('1' == $ifInterfaces[$ifIndex]['trunkPortState']) { - ++$device['ports_trunk']; - } - } - } - mactrack_debug('ifInterfaces assembly complete.'); - - // build VLAN array from results - $i = 0; - $j = 0; - $active_vlans = []; - - $skip_vlans = []; - $sql_result = db_fetch_cell_prepared( - 'SELECT skip_vlans +function get_IOS_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + $ifIndexes = []; + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // Variables to determine VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.6.1.1.14', $device); + + $device['vlans_total'] = cacti_sizeof($vlan_ids) - 4; + mactrack_debug('There are ' . (cacti_sizeof($vlan_ids) - 4) . ' VLANS.'); + + if (cacti_sizeof($vlan_names) == 0) { + cacti_log('No VLANs Name found: ' . $device['device_name']); + + return $device; + } + + if (cacti_sizeof($vlan_trunkstatus) == 0) { + cacti_log('No VLANs Trunk Status found: ' . $device['device_name']); + + return $device; + } + + // get the Voice VLAN information if it exists + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.87.1.4.1.1.37.0', $device); + + if (cacti_sizeof($portVoiceVLANs) > 0) { + $vvlans = true; + } else { + $portVoiceVLANs = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.68.1.5.1.1.1', $device); + + if (cacti_sizeof($portVoiceVLANs) > 0) { + $vvlans = true; + } else { + $vvlans = false; + } + } + + mactrack_debug('Cisco Voice VLAN collection complete'); + + if ($vvlans) { + mactrack_debug('Voice VLANs exist on this device'); + } else { + mactrack_debug('Voice VLANs do not exist on this device'); + } + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['trunkPortState'] = (isset($vlan_trunkstatus[$ifIndex]) ? $vlan_trunkstatus[$ifIndex] : ''); + + if ($vvlans) { + $ifInterfaces[$ifIndex]['vVlanID'] = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); + } + + if ($ifInterfaces[$ifIndex]['ifType'] == 6) { + ++$device['ports_total']; + } + + if ($ifInterfaces[$ifIndex]['trunkPortState'] == '1') { + ++$device['ports_trunk']; + } + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // build VLAN array from results + $i = 0; + $j = 0; + $active_vlans = []; + + $skip_vlans = []; + $sql_result = db_fetch_cell_prepared( + 'SELECT skip_vlans FROM mac_track_sites WHERE site_name = ?', - [$site] - ); + [$site] + ); - if ('' != $sql_result) { - $skip_vlans = explode(',', $sql_result); - } + if ($sql_result != '') { + $skip_vlans = explode(',', $sql_result); + } - $scan_vlans = []; - $sql_result = db_fetch_cell_prepared( - 'SELECT scan_vlans + $scan_vlans = []; + $sql_result = db_fetch_cell_prepared( + 'SELECT scan_vlans FROM mac_track_sites WHERE site_name = ?', - [$site] - ); - - if ('' != $sql_result) { - $scan_vlans = explode(',', $sql_result); - $scan_vlans = array_merge(array_diff($scan_vlans, $skip_vlans)); - } - - $scan_trunk_port = []; - if ('' != $device['scan_trunk_port']) { - $scan_trunk_port = explode(',', $device['scan_trunk_port']); - } - - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_number => $vlanStatus) { - $vlanName = mactrack_arr_key($vlan_names, $vlan_number); - - if ('' == $vlanName) { - cacti_log('Empty VLAN Name: '.$device['device_name']); - - continue; - } - - // VLAN-ID to skip - if (in_array($vlan_number, $skip_vlans)) { - mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is skipped. *** ALWAYS FORCED ***'); - - continue; - } - - // VLAN-ID to scan - if (count($scan_vlans) > 0) { - if (!in_array($vlan_number, $scan_vlans)) { - mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is skipped. *** NOT CONFIGURED ***'); - - continue; - } - } - - if (1 == $vlanStatus) { // vlan is operatinal - switch ($vlan_number) { - case '1002': - case '1003': - case '1004': - case '1005': - $active_vlan_ports = 0; - - break; - - default: - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'].'@'.$vlan_number; - $active_vlan_ports = cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - SNMP_POLLER, - $device['snmp_engine_id'] - ); - } else { - $active_vlan_ports = cacti_snmp_get( - $device['hostname'], - 'vlan-'.$vlan_number, - '.1.3.6.1.2.1.17.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - 'vlan-'.$vlan_number, - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - SNMP_POLLER, - $device['snmp_engine_id'] - ); - } - - if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { - $active_vlan_ports = 0; - } - - mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is complete. ACTIVE PORTS: '.$active_vlan_ports); - - if ($active_vlan_ports > 0) { // does the vlan have active ports on it - $active_vlans[$j]['vlan_id'] = $vlan_number; - $active_vlans[$j]['vlan_name'] = $vlanName; - $active_vlans[$j]['active_ports'] = $active_vlan_ports; - - ++$j; - } - } - } - - ++$i; - } - } - - if (cacti_sizeof($active_vlans)) { - $i = 0; - // get the port status information - foreach ($active_vlans as $active_vlan) { - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'].'@'.$active_vlan['vlan_id']; - } else { - $snmp_readstring = 'vlan-'.$active_vlan['vlan_id']; - } - - mactrack_debug('Processing has begun for VLAN: '.$active_vlan['vlan_id']); - if (0 == $highPort) { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); - } else { - $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); - } - - // get bridge port mappings - // get bridge port to ifIndex mappings - mactrack_debug('Bridge port information about to be collected.'); - mactrack_debug('VLAN_ID: '.$active_vlans[$i]['vlan_id'].', VLAN_NAME: '.$active_vlans[$i]['vlan_name'].', ACTIVE PORTS: '.cacti_sizeof($active_vlans[$i]['port_results'])); - - if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { - $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('Bridge port information collection complete.'); - } - ++$i; - } - - $i = 0; - $j = 0; - $port_array = []; - - mactrack_debug('Final cross check\'s now being performed.'); - if (cacti_sizeof($active_vlans)) { - foreach ($active_vlans as $active_vlan) { - if (cacti_sizeof($active_vlan['port_results'])) { - foreach ($active_vlan['port_results'] as $port_result) { - $ifIndex = (isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''); - $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); - $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); - $portNumber = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); - $portName = (isset($ifInterfaces[$ifIndex]['ifAlias']) ? $ifInterfaces[$ifIndex]['ifAlias'] : ''); - $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); - $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); - - if ($vvlans) { - $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); - } else { - $vVlanID = -1; - } - - // only output legitimate end user ports - /* ifType: 6 = ethernetCsmacd - 53 = propVirtual - 161 = ieee8023adLag - */ - if (6 == $ifType || 53 == $ifType || 161 == $ifType) { - if (('2' == $portTrunkStatus) - // (empty($portTrunkStatus)) || - || in_array($portNumber, $scan_trunk_port) - || (($vVlanID > 0) && ($vVlanID <= 1000))) { - $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; - $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; - $port_array[$i]['port_number'] = $portNumber; - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - $port_array[$i]['ifType'] = $ifType; - $port_array[$i]['portTrunkStatus'] = $portTrunkStatus; - ++$i; - - mactrack_debug('HOST: '.$device['hostname'].', ' - .'VLAN: '.$active_vlan['vlan_id'].', ' - .'NAME: '.$active_vlan['vlan_name'].', ' - .'TRUNK: '.$portTrunkStatus.', ' - .'TYPE: '.$ifType.', ' - .'PORT: '.$portNumber.', ' - .'NAME: '.$portName.', ' - .'MAC: '.$port_result['mac_address']); - } - } - } - } - - ++$j; - } - } - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active end devices on this device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; - } - - return $device; + [$site] + ); + + if ($sql_result != '') { + $scan_vlans = explode(',', $sql_result); + $scan_vlans = array_merge(array_diff($scan_vlans, $skip_vlans)); + } + + $scan_trunk_port = []; + + if ($device['scan_trunk_port'] != '') { + $scan_trunk_port = explode(',', $device['scan_trunk_port']); + } + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_number => $vlanStatus) { + $vlanName = mactrack_arr_key($vlan_names, $vlan_number); + + if ($vlanName == '') { + cacti_log('Empty VLAN Name: ' . $device['device_name']); + + continue; + } + + // VLAN-ID to skip + if (in_array($vlan_number, $skip_vlans, true)) { + mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is skipped. *** ALWAYS FORCED ***'); + + continue; + } + + // VLAN-ID to scan + if (count($scan_vlans) > 0) { + if (!in_array($vlan_number, $scan_vlans, true)) { + mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is skipped. *** NOT CONFIGURED ***'); + + continue; + } + } + + if ($vlanStatus == 1) { // vlan is operatinal + switch ($vlan_number) { + case '1002': + case '1003': + case '1004': + case '1005': + $active_vlan_ports = 0; + + break; + default: + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'] . '@' . $vlan_number; + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } else { + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + 'vlan-' . $vlan_number, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + 'vlan-' . $vlan_number, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } + + if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { + $active_vlan_ports = 0; + } + + mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is complete. ACTIVE PORTS: ' . $active_vlan_ports); + + if ($active_vlan_ports > 0) { // does the vlan have active ports on it + $active_vlans[$j]['vlan_id'] = $vlan_number; + $active_vlans[$j]['vlan_name'] = $vlanName; + $active_vlans[$j]['active_ports'] = $active_vlan_ports; + + ++$j; + } + } + } + + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + $i = 0; + + // get the port status information + foreach ($active_vlans as $active_vlan) { + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'] . '@' . $active_vlan['vlan_id']; + } else { + $snmp_readstring = 'vlan-' . $active_vlan['vlan_id']; + } + + mactrack_debug('Processing has begun for VLAN: ' . $active_vlan['vlan_id']); + + if ($highPort == 0) { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false); + } else { + $active_vlans[$i]['port_results'] = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $snmp_readstring, false, $lowPort, $highPort); + } + + // get bridge port mappings + // get bridge port to ifIndex mappings + mactrack_debug('Bridge port information about to be collected.'); + mactrack_debug('VLAN_ID: ' . $active_vlans[$i]['vlan_id'] . ', VLAN_NAME: ' . $active_vlans[$i]['vlan_name'] . ', ACTIVE PORTS: ' . cacti_sizeof($active_vlans[$i]['port_results'])); + + if (cacti_sizeof($active_vlans[$i]['port_results']) > 0) { + $brPorttoifIndexes[$i] = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('Bridge port information collection complete.'); + } + ++$i; + } + + $i = 0; + $j = 0; + $port_array = []; + + mactrack_debug('Final cross check\'s now being performed.'); + + if (cacti_sizeof($active_vlans)) { + foreach ($active_vlans as $active_vlan) { + if (cacti_sizeof($active_vlan['port_results'])) { + foreach ($active_vlan['port_results'] as $port_result) { + $ifIndex = (isset($brPorttoifIndexes[$j][$port_result['port_number']]) ? $brPorttoifIndexes[$j][$port_result['port_number']] : ''); + $ifType = (isset($ifInterfaces[$ifIndex]['ifType']) ? $ifInterfaces[$ifIndex]['ifType'] : ''); + $ifName = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); + $portNumber = (isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''); + $portName = (isset($ifInterfaces[$ifIndex]['ifAlias']) ? $ifInterfaces[$ifIndex]['ifAlias'] : ''); + $portTrunk = (isset($portTrunking[$ifName]) ? $portTrunking[$ifName] : ''); + $portTrunkStatus = (isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''); + + if ($vvlans) { + $vVlanID = (isset($portVoiceVLANs[$ifIndex]) ? $portVoiceVLANs[$ifIndex] : ''); + } else { + $vVlanID = -1; + } + + // only output legitimate end user ports + /* ifType: 6 = ethernetCsmacd + 53 = propVirtual + 161 = ieee8023adLag + */ + if ($ifType == 6 || $ifType == 53 || $ifType == 161) { + if (($portTrunkStatus == '2') + // (empty($portTrunkStatus)) || + || in_array($portNumber, $scan_trunk_port, true) + || (($vVlanID > 0) && ($vVlanID <= 1000))) { + $port_array[$i]['vlan_id'] = $active_vlan['vlan_id']; + $port_array[$i]['vlan_name'] = $active_vlan['vlan_name']; + $port_array[$i]['port_number'] = $portNumber; + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + $port_array[$i]['ifType'] = $ifType; + $port_array[$i]['portTrunkStatus'] = $portTrunkStatus; + ++$i; + + mactrack_debug('HOST: ' . $device['hostname'] . ', ' + . 'VLAN: ' . $active_vlan['vlan_id'] . ', ' + . 'NAME: ' . $active_vlan['vlan_name'] . ', ' + . 'TRUNK: ' . $portTrunkStatus . ', ' + . 'TYPE: ' . $ifType . ', ' + . 'PORT: ' . $portNumber . ', ' + . 'NAME: ' . $portName . ', ' + . 'MAC: ' . $port_result['mac_address']); + } + } + } + } + + ++$j; + } + } + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active end devices on this device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; + } + + return $device; } /* get_cisco_dhcpsnooping_table - This function reads a devices DHCP Snooping table for a site and stores @@ -624,297 +633,296 @@ function get_IOS_dot1dTpFdbEntry_ports($site, &$device, $lowPort = 0, $highPort fully implemented we match MACs from dot1dTpFdbEntry so some IPs won't get the MAC populated. Send an email to mii@external.cisco.com with the word 'help' in the subject to get MIBs supported per IOS Image. */ -function get_cisco_dhcpsnooping_table($site, &$device) -{ - global $debug, $scan_date; - - // get the cdsBindingInterface Index for the device - $cdsBindingInterface = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.5', $device); - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); - $cdsBindingsIpAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.4', $device); - $cdsBindingEntries = []; - $dot1dTpFdbEntries = []; - - // build VLAN array from results - $i = 0; - $j = 0; - $active_vlans = []; - - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_number => $vlanStatus) { - $vlanName = $vlan_names[$vlan_number]; - - if (1 == $vlanStatus) { // vlan is operatinal - switch ($vlan_number) { - case '1002': - case '1003': - case '1004': - case '1005': - $active_vlan_ports = 0; - - break; - - default: - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'].'@'.$vlan_number; - $active_vlan_ports = cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - SNMP_POLLER, - $device['snmp_engine_id'] - ); - } else { - $active_vlan_ports = cacti_snmp_get( - $device['hostname'], - 'vlan-'.$vlan_number, - '.1.3.6.1.2.1.17.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - 'vlan-'.$vlan_number, - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - SNMP_POLLER, - $device['snmp_engine_id'] - ); - } - - if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { - $active_vlan_ports = 0; - } - - mactrack_debug('VLAN Analysis for VLAN: '.$vlan_number.'/'.$vlanName.' is complete. ACTIVE PORTS: '.$active_vlan_ports); - - if ($active_vlan_ports > 0) { // does the vlan have active ports on it - $active_vlans[$j]['vlan_id'] = $vlan_number; - $active_vlans[$j]['vlan_name'] = $vlanName; - $active_vlans[$j]['active_ports'] = $active_vlan_ports; - - // Commented out because why wuuld you increment an array!! - // $active_vlans++; - - ++$j; - } - } - } - - ++$i; - } - } - - if (cacti_sizeof($active_vlans)) { - $n = 1; - $dot1dTpFdbEntry = []; - - // get the port status information - foreach ($active_vlans as $active_vlan) { - if ($device['snmp_version'] < '3') { - $snmp_readstring = $device['snmp_readstring'].'@'.$active_vlan['vlan_id']; - } else { - $snmp_readstring = 'vlan-'.$active_vlan['vlan_id']; - } - - mactrack_debug('Processing has begun for VLAN: '.$active_vlan['vlan_id']); - - if (cacti_sizeof($active_vlans)) { - $dot1dTpFdbEntries[$n] = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring); - foreach ($dot1dTpFdbEntries[$n] as $key => $val) { - $dot1dTpFdbEntries[$n][$active_vlan['vlan_id'].'.'.$key] = $val; // ugly tweak to add vlan id to OID. - unset($dot1dTpFdbEntries[$n][$key]); - } - - mactrack_debug('dot1dTpFdbEntry data collection complete :'.cacti_sizeof($dot1dTpFdbEntries[$n])); - - if ($n > 0) { - $dot1dTpFdbEntry = array_merge($dot1dTpFdbEntry, $dot1dTpFdbEntries[$n]); - mactrack_debug('merge data collection complete : '.cacti_sizeof($dot1dTpFdbEntry)); - } - } - ++$n; - - mactrack_debug('dot1dTpFdbEntry vlan_id: '.$active_vlan['vlan_id']); - } - - $keys = array_keys($cdsBindingInterface); - - $j = 0; - if (cacti_sizeof($cdsBindingInterface)) { - foreach ($cdsBindingInterface as $cdsBindingIndex) { - $cdsBindingEntries[$j]['cdsBindingIndex'] = $cdsBindingIndex; - $cdsBindingEntries[$j]['dot1dTpFdbEntry'] = isset($dot1dTpFdbEntry[$keys[$j]]) ? xform_mac_address($dot1dTpFdbEntry[$keys[$j]]) : ''; - $cdsBindingEntries[$j]['cdsBindingsIpAddress'] = isset($cdsBindingsIpAddress[$keys[$j]]) ? xform_net_address($cdsBindingsIpAddress[$keys[$j]]) : ''; - ++$j; - } - - mactrack_debug('cdsBindingEntries Total entries: '.cacti_sizeof($cdsBindingEntries)); - } - - mactrack_debug('cdsBindingEntries assembly complete.'); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active end devices on this device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; - } - - // output details to database - if (cacti_sizeof($cdsBindingEntries)) { - foreach ($cdsBindingEntries as $cdsBindingEntry) { - if ('' != $cdsBindingEntry['cdsBindingsIpAddress']) { // It's acceptable to have IPs without a MAC (meaning that MAC is not present but DHCP entry is still present) here but not the other way around. - $insert_string = 'REPLACE INTO mac_track_ips +function get_cisco_dhcpsnooping_table($site, &$device) { + global $debug, $scan_date; + + // get the cdsBindingInterface Index for the device + $cdsBindingInterface = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.5', $device); + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.2', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.9.9.46.1.3.1.1.4', $device); + $cdsBindingsIpAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.380.1.4.1.1.4', $device); + $cdsBindingEntries = []; + $dot1dTpFdbEntries = []; + + // build VLAN array from results + $i = 0; + $j = 0; + $active_vlans = []; + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_number => $vlanStatus) { + $vlanName = $vlan_names[$vlan_number]; + + if ($vlanStatus == 1) { // vlan is operatinal + switch ($vlan_number) { + case '1002': + case '1003': + case '1004': + case '1005': + $active_vlan_ports = 0; + + break; + default: + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'] . '@' . $vlan_number; + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } else { + $active_vlan_ports = cacti_snmp_get( + $device['hostname'], + 'vlan-' . $vlan_number, + '.1.3.6.1.2.1.17.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + 'vlan-' . $vlan_number, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + SNMP_POLLER, + $device['snmp_engine_id'] + ); + } + + if ((!is_numeric($active_vlan_ports)) || $active_vlan_ports < 0) { + $active_vlan_ports = 0; + } + + mactrack_debug('VLAN Analysis for VLAN: ' . $vlan_number . '/' . $vlanName . ' is complete. ACTIVE PORTS: ' . $active_vlan_ports); + + if ($active_vlan_ports > 0) { // does the vlan have active ports on it + $active_vlans[$j]['vlan_id'] = $vlan_number; + $active_vlans[$j]['vlan_name'] = $vlanName; + $active_vlans[$j]['active_ports'] = $active_vlan_ports; + + // Commented out because why wuuld you increment an array!! + // $active_vlans++; + + ++$j; + } + } + } + + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + $n = 1; + $dot1dTpFdbEntry = []; + + // get the port status information + foreach ($active_vlans as $active_vlan) { + if ($device['snmp_version'] < '3') { + $snmp_readstring = $device['snmp_readstring'] . '@' . $active_vlan['vlan_id']; + } else { + $snmp_readstring = 'vlan-' . $active_vlan['vlan_id']; + } + + mactrack_debug('Processing has begun for VLAN: ' . $active_vlan['vlan_id']); + + if (cacti_sizeof($active_vlans)) { + $dot1dTpFdbEntries[$n] = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring); + + foreach ($dot1dTpFdbEntries[$n] as $key => $val) { + $dot1dTpFdbEntries[$n][$active_vlan['vlan_id'] . '.' . $key] = $val; // ugly tweak to add vlan id to OID. + unset($dot1dTpFdbEntries[$n][$key]); + } + + mactrack_debug('dot1dTpFdbEntry data collection complete :' . cacti_sizeof($dot1dTpFdbEntries[$n])); + + if ($n > 0) { + $dot1dTpFdbEntry = array_merge($dot1dTpFdbEntry, $dot1dTpFdbEntries[$n]); + mactrack_debug('merge data collection complete : ' . cacti_sizeof($dot1dTpFdbEntry)); + } + } + ++$n; + + mactrack_debug('dot1dTpFdbEntry vlan_id: ' . $active_vlan['vlan_id']); + } + + $keys = array_keys($cdsBindingInterface); + + $j = 0; + + if (cacti_sizeof($cdsBindingInterface)) { + foreach ($cdsBindingInterface as $cdsBindingIndex) { + $cdsBindingEntries[$j]['cdsBindingIndex'] = $cdsBindingIndex; + $cdsBindingEntries[$j]['dot1dTpFdbEntry'] = isset($dot1dTpFdbEntry[$keys[$j]]) ? xform_mac_address($dot1dTpFdbEntry[$keys[$j]]) : ''; + $cdsBindingEntries[$j]['cdsBindingsIpAddress'] = isset($cdsBindingsIpAddress[$keys[$j]]) ? xform_net_address($cdsBindingsIpAddress[$keys[$j]]) : ''; + ++$j; + } + + mactrack_debug('cdsBindingEntries Total entries: ' . cacti_sizeof($cdsBindingEntries)); + } + + mactrack_debug('cdsBindingEntries assembly complete.'); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active end devices on this device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active end devices on this device.'; + } + + // output details to database + if (cacti_sizeof($cdsBindingEntries)) { + foreach ($cdsBindingEntries as $cdsBindingEntry) { + if ($cdsBindingEntry['cdsBindingsIpAddress'] != '') { // It's acceptable to have IPs without a MAC (meaning that MAC is not present but DHCP entry is still present) here but not the other way around. + $insert_string = 'REPLACE INTO mac_track_ips (site_id,device_id,hostname,device_name,port_number, mac_address,ip_address,scan_date) VALUES (' - .$device['site_id'].',' - .$device['device_id'].',' - .db_qstr($device['hostname']).',' - .db_qstr($device['device_name']).',' - .db_qstr($cdsBindingEntry['cdsBindingIndex']).',' - .db_qstr($cdsBindingEntry['dot1dTpFdbEntry']).',' - .db_qstr($cdsBindingEntry['cdsBindingsIpAddress']).',' - .db_qstr($scan_date).')'; - - db_execute($insert_string); - } - } - } - - // save ip information for the device - $device['ips_total'] = cacti_sizeof($cdsBindingEntries); - db_execute('UPDATE mac_track_devices SET ips_total ='.$device['ips_total'].' WHERE device_id='.$device['device_id']); - - mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete'); + . $device['site_id'] . ',' + . $device['device_id'] . ',' + . db_qstr($device['hostname']) . ',' + . db_qstr($device['device_name']) . ',' + . db_qstr($cdsBindingEntry['cdsBindingIndex']) . ',' + . db_qstr($cdsBindingEntry['dot1dTpFdbEntry']) . ',' + . db_qstr($cdsBindingEntry['cdsBindingsIpAddress']) . ',' + . db_qstr($scan_date) . ')'; + + db_execute($insert_string); + } + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($cdsBindingEntries); + db_execute('UPDATE mac_track_devices SET ips_total =' . $device['ips_total'] . ' WHERE device_id=' . $device['device_id']); + + mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete'); } /* get_cisco_vrf_arp_table - This function reads a devices ARP table for a site with VRF/MPLS and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_cisco_vrf_arp_table($site, &$device) -{ - global $debug, $scan_date; +function get_cisco_vrf_arp_table($site, &$device) { + global $debug, $scan_date; - // get the cdsBindingInterface Index for the device - $cdsBindingEntries = get_ios_vrf_arp_table('.1.3.6.1.2.1.3.1.1.2', $device); + // get the cdsBindingInterface Index for the device + $cdsBindingEntries = get_ios_vrf_arp_table('.1.3.6.1.2.1.3.1.1.2', $device); - // output details to database - if (cacti_sizeof($cdsBindingEntries)) { - foreach ($cdsBindingEntries as $cdsBindingEntry) { - $insert_string = 'INSERT INTO mac_track_arp + // output details to database + if (cacti_sizeof($cdsBindingEntries)) { + foreach ($cdsBindingEntries as $cdsBindingEntry) { + $insert_string = 'INSERT INTO mac_track_arp (site_id,ip_address,mac_address,scan_date) VALUES (' - .$device['site_id'].',' - .db_qstr($cdsBindingEntry['key']).',' - .db_qstr($cdsBindingEntry['value']).',' - .db_qstr($scan_date).' + . $device['site_id'] . ',' + . db_qstr($cdsBindingEntry['key']) . ',' + . db_qstr($cdsBindingEntry['value']) . ',' + . db_qstr($scan_date) . ' ) ON DUPLICATE KEY UPDATE - `ip_address` = '.db_qstr($cdsBindingEntry['key']).', - `scan_date` = '.db_qstr($scan_date).';'; + `ip_address` = ' . db_qstr($cdsBindingEntry['key']) . ', + `scan_date` = ' . db_qstr($scan_date) . ';'; - db_execute($insert_string); - } - } + db_execute($insert_string); + } + } - // save ip information for the device - $device['ips_total'] = cacti_sizeof($cdsBindingEntries); - db_execute('UPDATE mac_track_devices SET ips_total ='.$device['ips_total'].' WHERE device_id='.$device['device_id']); + // save ip information for the device + $device['ips_total'] = cacti_sizeof($cdsBindingEntries); + db_execute('UPDATE mac_track_devices SET ips_total =' . $device['ips_total'] . ' WHERE device_id=' . $device['device_id']); - mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete'); + mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete'); } /* get_cisco_dot1x_table - This function reads a devices Dot1x table for a site and stores the IP address, MAC address, Username, Domain and Status combinations in the mac_track_dot1x table. */ -function get_cisco_dot1x_table($site, &$device) -{ - global $debug, $scan_date; - - // get the cafSessionAuthUserName from the device - $cafSessionAuthUserName = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.10', $device); - - if (cacti_sizeof($cafSessionAuthUserName)) { - mactrack_debug('cafSessionAuthUserName data collection complete: '.cacti_sizeof($cafSessionAuthUserName)); - $cafSessionClientMacAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.2', $device, '', true); - mactrack_debug('cafSessionClientMacAddress data collection complete: '.cacti_sizeof($cafSessionClientMacAddress)); - $cafSessionClientAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.4', $device, '', true); - mactrack_debug('cafSessionClientAddress data collection complete: '.cacti_sizeof($cafSessionClientAddress)); - $cafSessionDomain = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.6', $device); - mactrack_debug('cafSessionDomain data collection complete: '.cacti_sizeof($cafSessionDomain)); - $cafSessionStatus = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.5', $device); - mactrack_debug('cafSessionStatus data collection complete: '.cacti_sizeof($cafSessionStatus)); - } else { - mactrack_debug(sprintf('The Device: %s does not support dot1x', $device['hostname'])); - - return false; - } - - $ifIndex = []; - $entries = []; - $cafSessionAuthUserNames = []; - $cafSessionAuthUserKey = array_keys($cafSessionAuthUserName); // Getting the keys to explode the first part which is the ifIndex - - mactrack_debug('cafSessionAuthUserName assembly complete: '.cacti_sizeof($cafSessionAuthUserName)); - - $i = 0; - if (cacti_sizeof($cafSessionAuthUserName)) { - foreach ($cafSessionAuthUserName as $index => $value) { - $entries[$i]['Dot1xIndex'] = $index; - $entries[$i]['UserName'] = $value; - $entries[$i]['cafSessionClientMacAddress'] = isset($cafSessionClientMacAddress[$index]) ? xform_mac_address($cafSessionClientMacAddress[$index]) : ''; - $entries[$i]['cafSessionClientAddress'] = isset($cafSessionClientAddress[$index]) ? xform_net_address($cafSessionClientAddress[$index]) : ''; - $entries[$i]['cafSessionDomain'] = isset($cafSessionDomain[$index]) ? $cafSessionDomain[$index] : ''; - $entries[$i]['cafSessionStatus'] = isset($cafSessionStatus[$index]) ? $cafSessionStatus[$index] : ''; - - $parts = explode('.', trim($index, '.')); - $entries[$i]['port_number'] = $parts[0]; - - ++$i; - } - } - mactrack_debug('cafSession assembly complete.'); - - // output details to database - $sql = []; - $prefix = 'REPLACE INTO mac_track_dot1x +function get_cisco_dot1x_table($site, &$device) { + global $debug, $scan_date; + + // get the cafSessionAuthUserName from the device + $cafSessionAuthUserName = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.10', $device); + + if (cacti_sizeof($cafSessionAuthUserName)) { + mactrack_debug('cafSessionAuthUserName data collection complete: ' . cacti_sizeof($cafSessionAuthUserName)); + $cafSessionClientMacAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.2', $device, '', true); + mactrack_debug('cafSessionClientMacAddress data collection complete: ' . cacti_sizeof($cafSessionClientMacAddress)); + $cafSessionClientAddress = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.4', $device, '', true); + mactrack_debug('cafSessionClientAddress data collection complete: ' . cacti_sizeof($cafSessionClientAddress)); + $cafSessionDomain = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.6', $device); + mactrack_debug('cafSessionDomain data collection complete: ' . cacti_sizeof($cafSessionDomain)); + $cafSessionStatus = xform_stripped_oid('.1.3.6.1.4.1.9.9.656.1.4.1.1.5', $device); + mactrack_debug('cafSessionStatus data collection complete: ' . cacti_sizeof($cafSessionStatus)); + } else { + mactrack_debug(sprintf('The Device: %s does not support dot1x', $device['hostname'])); + + return false; + } + + $ifIndex = []; + $entries = []; + $cafSessionAuthUserNames = []; + $cafSessionAuthUserKey = array_keys($cafSessionAuthUserName); // Getting the keys to explode the first part which is the ifIndex + + mactrack_debug('cafSessionAuthUserName assembly complete: ' . cacti_sizeof($cafSessionAuthUserName)); + + $i = 0; + + if (cacti_sizeof($cafSessionAuthUserName)) { + foreach ($cafSessionAuthUserName as $index => $value) { + $entries[$i]['Dot1xIndex'] = $index; + $entries[$i]['UserName'] = $value; + $entries[$i]['cafSessionClientMacAddress'] = isset($cafSessionClientMacAddress[$index]) ? xform_mac_address($cafSessionClientMacAddress[$index]) : ''; + $entries[$i]['cafSessionClientAddress'] = isset($cafSessionClientAddress[$index]) ? xform_net_address($cafSessionClientAddress[$index]) : ''; + $entries[$i]['cafSessionDomain'] = isset($cafSessionDomain[$index]) ? $cafSessionDomain[$index] : ''; + $entries[$i]['cafSessionStatus'] = isset($cafSessionStatus[$index]) ? $cafSessionStatus[$index] : ''; + + $parts = explode('.', trim($index, '.')); + $entries[$i]['port_number'] = $parts[0]; + + ++$i; + } + } + mactrack_debug('cafSession assembly complete.'); + + // output details to database + $sql = []; + $prefix = 'REPLACE INTO mac_track_dot1x (site_id, device_id, hostname, device_name, username, mac_address, ip_address, domain, status, port_number, scan_date) VALUES '; - if (cacti_sizeof($entries)) { - foreach ($entries as $entry) { - if ('' != $entry['UserName']) { - $sql[] = '('.$device['site_id'].',' - .$device['device_id'].',' - .db_qstr($device['hostname']).',' - .db_qstr($device['device_name']).',' - .db_qstr($entry['UserName']).',' - .db_qstr($entry['cafSessionClientMacAddress']).',' - .db_qstr($entry['cafSessionClientAddress']).',' - .db_qstr($entry['cafSessionDomain']).',' - .db_qstr($entry['cafSessionStatus']).',' - .db_qstr($entry['port_number']).',' - .db_qstr($scan_date).')'; - } - } - - if (cacti_sizeof($sql)) { - db_execute($prefix.implode(', ', $sql)); - } - } + if (cacti_sizeof($entries)) { + foreach ($entries as $entry) { + if ($entry['UserName'] != '') { + $sql[] = '(' . $device['site_id'] . ',' + . $device['device_id'] . ',' + . db_qstr($device['hostname']) . ',' + . db_qstr($device['device_name']) . ',' + . db_qstr($entry['UserName']) . ',' + . db_qstr($entry['cafSessionClientMacAddress']) . ',' + . db_qstr($entry['cafSessionClientAddress']) . ',' + . db_qstr($entry['cafSessionDomain']) . ',' + . db_qstr($entry['cafSessionStatus']) . ',' + . db_qstr($entry['port_number']) . ',' + . db_qstr($scan_date) . ')'; + } + } + + if (cacti_sizeof($sql)) { + db_execute($prefix . implode(', ', $sql)); + } + } } diff --git a/lib/mactrack_dell.php b/lib/mactrack_dell.php index 8d67b2f5..9a5b5dc0 100644 --- a/lib/mactrack_dell.php +++ b/lib/mactrack_dell.php @@ -25,7 +25,7 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_dell_dot1q_switch_ports'); @@ -34,32 +34,31 @@ mac_track_temp_ports table for future processing in the finalization steps of the scanning process. */ -function get_dell_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; +function get_dell_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); - // sanitize ifInterfaces by removing text from ifType field - if (cacti_sizeof($ifInterfaces)) { - foreach ($ifInterfaces as $key => $tempInterfaces) { - preg_match('/[0-9]{1,3}/', $tempInterfaces['ifType'], $newType); - $ifInterfaces[$key]['ifType'] = $newType[0]; - } - } + // sanitize ifInterfaces by removing text from ifType field + if (cacti_sizeof($ifInterfaces)) { + foreach ($ifInterfaces as $key => $tempInterfaces) { + preg_match('/[0-9]{1,3}/', $tempInterfaces['ifType'], $newType); + $ifInterfaces[$key]['ifType'] = $newType[0]; + } + } - get_base_dell_dot1qFdb_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_dell_dot1qFdb_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /* get_base_dell_dot1qFdb_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. @@ -67,215 +66,218 @@ function get_dell_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = This was mainly copied from the default dot1q function in mactrack_functions.php but was modified to work with Dell switches */ -function get_base_dell_dot1qFdb_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - $snmp_readstring = $device['snmp_readstring']; - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - // Sanitize active ports array, removing text junk as the dell's don't return just a plain numeric value - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $key => $tempPorts) { - preg_match('/[0-9]{1,3}/', $tempPorts, $newStatus); - $active_ports_array[$key] = $newStatus[0]; - } - } - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) - || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - // get bridge port to ifIndex mapping - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); - // Sanitize port_status array, removing text junk as the dell's don't return just a plain numeric value - if (cacti_sizeof($port_status)) { - foreach ($port_status as $key => $tempStatus) { - preg_match('/[0-9]{1,3}/', $tempStatus, $newStatus); - $port_status[$key] = $newStatus[0]; - } - } - - // print_r($port_status); - /* get device active port numbers - This is the OID that shows the mac address as the index and the port as the value*/ - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - // get the bridge root port so we don't capture active ports on it - $bridge_root_port = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.2.7.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort) - && ($bridge_root_port != $port_number))) { - if (!in_array($port_number, $ignore_ports)) { - if ((isset($port_status[$key]) && '3' == $port_status[$key]) || (isset($port_status[$key]) && '5' == $port_status[$key])) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - ++$i; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (0 != cacti_sizeof($bridgePortIfIndexes)) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || (71 == $brPortIfType)) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $new_port_key_array[$i]['port_name'] = $ifInterfaces[$port_key['port_number']]['ifAlias']; - ++$i; - } - } - } - } - mactrack_debug('Port number information collected.'); - - // map mac address - // only continue if there were user ports defined - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_mac) { - $new_port_key_array[$key]['mac_address'] = dell_mac_address_convert($port_mac['key']); - mactrack_debug('INDEX: '.$key.' MAC ADDRESS: '.$new_port_key_array[$key]['mac_address']); - } - - // Map Vlan names to pvid's - $vlan_names = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); - - // map pvid's to ports with vlan names - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port) { - $temp_array = explode('.', $port['key']); - $new_port_key_array[$key]['vlan_id'] = $temp_array[0]; - $new_port_key_array[$key]['vlan_name'] = mactrack_arr_key($vlan_names, $new_port_key_array[$key]['vlan_id']); - } - } - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_base_dell_dot1qFdb_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + $snmp_readstring = $device['snmp_readstring']; + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + // Sanitize active ports array, removing text junk as the dell's don't return just a plain numeric value + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $key => $tempPorts) { + preg_match('/[0-9]{1,3}/', $tempPorts, $newStatus); + $active_ports_array[$key] = $newStatus[0]; + } + } + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); + + // Sanitize port_status array, removing text junk as the dell's don't return just a plain numeric value + if (cacti_sizeof($port_status)) { + foreach ($port_status as $key => $tempStatus) { + preg_match('/[0-9]{1,3}/', $tempStatus, $newStatus); + $port_status[$key] = $newStatus[0]; + } + } + + // print_r($port_status); + /* get device active port numbers + This is the OID that shows the mac address as the index and the port as the value*/ + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // get the bridge root port so we don't capture active ports on it + $bridge_root_port = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.2.7.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort) + && ($bridge_root_port != $port_number))) { + if (!in_array($port_number, $ignore_ports, true)) { + if ((isset($port_status[$key]) && $port_status[$key] == '3') || (isset($port_status[$key]) && $port_status[$key] == '5')) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes) != 0) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || ($brPortIfType == 71)) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + $new_port_key_array[$i]['port_name'] = $ifInterfaces[$port_key['port_number']]['ifAlias']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_mac) { + $new_port_key_array[$key]['mac_address'] = dell_mac_address_convert($port_mac['key']); + mactrack_debug('INDEX: ' . $key . ' MAC ADDRESS: ' . $new_port_key_array[$key]['mac_address']); + } + + // Map Vlan names to pvid's + $vlan_names = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); + + // map pvid's to ports with vlan names + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port) { + $temp_array = explode('.', $port['key']); + $new_port_key_array[$key]['vlan_id'] = $temp_array[0]; + $new_port_key_array[$key]['vlan_name'] = mactrack_arr_key($vlan_names, $new_port_key_array[$key]['vlan_id']); + } + } + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } -function dell_mac_address_convert($mac_address) -{ - if ('' == $mac_address) { - $mac_address = 'NOT USER'; - } elseif (strlen($mac_address) > 10) { // return is in ascii - $mac_address = trim(str_replace('"', '', $mac_address)); - $mac_address = str_replace('.', ':', $mac_address); - $mac_address = str_replace('-', ':', $mac_address); - $mac = explode(':', $mac_address); - - foreach ($mac as $key => $mac_item) { - if (!empty($mac_item)) { - $mac_item = dechex($mac_item); - if (strlen($mac_item) < 2) { - $mac_item = '0'.$mac_item; - } - $mac[$key] = strtoupper($mac_item); - } - } - - $mac_address = implode('', $mac); - } - - return $mac_address; +function dell_mac_address_convert($mac_address) { + if ($mac_address == '') { + $mac_address = 'NOT USER'; + } elseif (strlen($mac_address) > 10) { // return is in ascii + $mac_address = trim(str_replace('"', '', $mac_address)); + $mac_address = str_replace('.', ':', $mac_address); + $mac_address = str_replace('-', ':', $mac_address); + $mac = explode(':', $mac_address); + + foreach ($mac as $key => $mac_item) { + if (!empty($mac_item)) { + $mac_item = dechex($mac_item); + + if (strlen($mac_item) < 2) { + $mac_item = '0' . $mac_item; + } + $mac[$key] = strtoupper($mac_item); + } + } + + $mac_address = implode('', $mac); + } + + return $mac_address; } diff --git a/lib/mactrack_dlink.php b/lib/mactrack_dlink.php index 58b3bc61..306b050c 100644 --- a/lib/mactrack_dlink.php +++ b/lib/mactrack_dlink.php @@ -26,11 +26,12 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_dlink_l2_switch_ports'); + if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_dlink_l2_dot1dTpFdbEntry_ports'); @@ -39,338 +40,335 @@ mac_track_temp_ports table for future processing in the finalization steps of the scanning process. */ -function get_dlink_l2_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); - - // get the ifTypes for the device - $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); - mactrack_debug('ifTypes data collection complete.'); - - // get the ifNames for the device - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete.'); - - // get ports that happen to be link ports - $link_ports = get_link_port_status($device); - mactrack_debug('ipAddrTable scanning for Dlink ports data collection complete.'); - - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; - $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); - $ifInterfaces[$ifIndex]['ifType'] = $ifTypes[$ifIndex]; - $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); - } - } - mactrack_debug('ifInterfaces assembly complete.'); - - get_dlink_l2_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - - return $device; - mactrack_debug('Finish function get_dlink_l2_switch_ports for dev=: dev='.$device['hostname']); +function get_dlink_l2_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get the ifTypes for the device + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + mactrack_debug('ifTypes data collection complete.'); + + // get the ifNames for the device + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete.'); + + // get ports that happen to be link ports + $link_ports = get_link_port_status($device); + mactrack_debug('ipAddrTable scanning for Dlink ports data collection complete.'); + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); + $ifInterfaces[$ifIndex]['ifType'] = $ifTypes[$ifIndex]; + $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + get_dlink_l2_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + + return $device; + mactrack_debug('Finish function get_dlink_l2_switch_ports for dev=: dev=' . $device['hostname']); } /* get_base_dot1dTpFdbEntry_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. This is a foundational function for all vendor data collection functions. */ -function get_dlink_l2_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - if (((convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) >= 6) - && (convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) <= 9)) - || (117 == convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']))) { - if (1 == convert_dlink_data($port_info)) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - // get bridge port to ifIndex mapping - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); - - // get device active port numbers - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - // determine user ports for this device and transfer user ports to a new array. - $i = 0; - - if (cacti_sizeof($port_numbers) > 0) { - foreach ($port_numbers as $key => $port_number) { - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort))) { - if (!in_array($port_number, $ignore_ports)) { - if (('3' == @$port_status[$key]) || ('1' == @$port_status[$key])) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - ++$i; - } - } - } - } - } - - $i = 0; - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); - - $i = 0; - if (cacti_sizeof($port_key_array) > 0) { - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] >= 0) { - if (0 != cacti_sizeof($bridgePortIfIndexes)) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; - } else { - $brPortIfIndex = @$port_key['port_number']; - } - $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; - } - - if ((((convert_dlink_data($brPortIfType) >= 6) - && (convert_dlink_data($brPortIfType) <= 9)) || (117 == convert_dlink_data($brPortIfType))) - && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = get_dlink_vlan_id($port_key['key']); - $new_port_key_array[$i]['vlan_name'] = $vlan_names[$new_port_key_array[$i]['vlan_id']]; - $new_port_key_array[$i]['mac_address'] = dlink_convert_macs($port_key['key']); - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - $new_port_key_array[$i]['port_name'] = @$ifNames[$port_key['port_number']]; - // now set the real data - $new_port_key_array[$i]['key'] = $port_key['key']; - ++$i; - } - } - } - } - mactrack_debug('Port number information collected.'); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_dlink_l2_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + if (((convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) >= 6) + && (convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) <= 9)) + || (convert_dlink_data($ifInterfaces[$indexes[$i]]['ifType']) == 117)) { + if (convert_dlink_data($port_info) == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // determine user ports for this device and transfer user ports to a new array. + $i = 0; + + if (cacti_sizeof($port_numbers) > 0) { + foreach ($port_numbers as $key => $port_number) { + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports, true)) { + if ((@$port_status[$key] == '3') || (@$port_status[$key] == '1')) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + ++$i; + } + } + } + } + } + + $i = 0; + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); + + $i = 0; + + if (cacti_sizeof($port_key_array) > 0) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] >= 0) { + if (cacti_sizeof($bridgePortIfIndexes) != 0) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; + } else { + $brPortIfIndex = @$port_key['port_number']; + } + $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; + } + + if ((((convert_dlink_data($brPortIfType) >= 6) + && (convert_dlink_data($brPortIfType) <= 9)) || (convert_dlink_data($brPortIfType) == 117)) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = get_dlink_vlan_id($port_key['key']); + $new_port_key_array[$i]['vlan_name'] = $vlan_names[$new_port_key_array[$i]['vlan_id']]; + $new_port_key_array[$i]['mac_address'] = dlink_convert_macs($port_key['key']); + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + $new_port_key_array[$i]['port_name'] = @$ifNames[$port_key['port_number']]; + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } -function dlink_convert_macs($oldmac) -{ - if ('.' != $oldmac[0]) { - $oldmac = '.'.$oldmac; - } +function dlink_convert_macs($oldmac) { + if ($oldmac[0] != '.') { + $oldmac = '.' . $oldmac; + } - $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); - $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); - $piece = explode('.', $oldmac); - $newmac = ''; + $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); + $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); + $piece = explode('.', $oldmac); + $newmac = ''; - for ($i = 0; $i < 6; ++$i) { - $newmac = $newmac.dec2hex($piece[$i], 2).':'; - } + for ($i = 0; $i < 6; ++$i) { + $newmac = $newmac . dec2hex($piece[$i], 2) . ':'; + } - return substr($newmac, 0, strlen($newmac) - 1); + return substr($newmac, 0, strlen($newmac) - 1); } -function dec2hex($number, $length) -{ - $hexval = ''; - - while ($number > 0) { - $remainder = $number % 16; - if ($remainder < 10) { - $hexval = $remainder.$hexval; - } elseif (10 == $remainder) { - $hexval = 'a'.$hexval; - } elseif (11 == $remainder) { - $hexval = 'b'.$hexval; - } elseif (12 == $remainder) { - $hexval = 'c'.$hexval; - } elseif (13 == $remainder) { - $hexval = 'd'.$hexval; - } elseif (14 == $remainder) { - $hexval = 'e'.$hexval; - } elseif (15 == $remainder) { - $hexval = 'f'.$hexval; - } - $number = floor($number / 16); - } - - while (strlen($hexval) < $length) { - $hexval = '0'.$hexval; - } - - // this is just to add zero's at the beginning to make hexval a certain length - return $hexval; +function dec2hex($number, $length) { + $hexval = ''; + + while ($number > 0) { + $remainder = $number % 16; + + if ($remainder < 10) { + $hexval = $remainder . $hexval; + } elseif ($remainder == 10) { + $hexval = 'a' . $hexval; + } elseif ($remainder == 11) { + $hexval = 'b' . $hexval; + } elseif ($remainder == 12) { + $hexval = 'c' . $hexval; + } elseif ($remainder == 13) { + $hexval = 'd' . $hexval; + } elseif ($remainder == 14) { + $hexval = 'e' . $hexval; + } elseif ($remainder == 15) { + $hexval = 'f' . $hexval; + } + $number = floor($number / 16); + } + + while (strlen($hexval) < $length) { + $hexval = '0' . $hexval; + } + + // this is just to add zero's at the beginning to make hexval a certain length + return $hexval; } if (!function_exists('stripos')) { - function stripos($str, $needle) - { - return strpos(strtolower($str), strtolower($needle)); - } + function stripos($str, $needle) { + return strpos(strtolower($str), strtolower($needle)); + } } -function xform_dlink_vlan_associations(&$device, $snmp_readstring = '') -{ - // get raw index data - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // initialize the output array - $output_array = []; - - // obtain vlan associations - $xformArray = cacti_snmp_walk( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.2.2.1.2', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'] - ); - - $i = 0; - foreach ($xformArray as $xformItem) { - // peel off the beginning of the OID - $key = $xformItem['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); - // now grab the VLAN - $perPos = strpos($key, '.', 1); - $output_array[$i]['vlan_id'] = substr($key, 1, $perPos - 1); - // save the key for association with the dot1d table - $output_array[$i]['key'] = substr($key, $perPos + 1); - $vlan_name = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.4.3.1.1.'.$output_array[$i]['vlan_id'], - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - $output_array[$i]['vlan_name'] = $vlan_name; - - ++$i; - } - - // return array_rekey($output_array, 'key', 'vlan_name'); - return $output_array; +function xform_dlink_vlan_associations(&$device, $snmp_readstring = '') { + // get raw index data + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // initialize the output array + $output_array = []; + + // obtain vlan associations + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.2.2.1.2', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + $i = 0; + + foreach ($xformArray as $xformItem) { + // peel off the beginning of the OID + $key = $xformItem['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); + // now grab the VLAN + $perPos = strpos($key, '.', 1); + $output_array[$i]['vlan_id'] = substr($key, 1, $perPos - 1); + // save the key for association with the dot1d table + $output_array[$i]['key'] = substr($key, $perPos + 1); + $vlan_name = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.4.3.1.1.' . $output_array[$i]['vlan_id'], + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $output_array[$i]['vlan_name'] = $vlan_name; + + ++$i; + } + + // return array_rekey($output_array, 'key', 'vlan_name'); + return $output_array; } -function get_dlink_vlan_id($OID) -{ - if ('.' != $OID[0]) { - $OID = '.'.$OID; - } +function get_dlink_vlan_id($OID) { + if ($OID[0] != '.') { + $OID = '.' . $OID; + } - $perPos = strpos($OID, '.', 1); + $perPos = strpos($OID, '.', 1); - return substr($OID, 1, $perPos - 1); + return substr($OID, 1, $perPos - 1); } -function convert_dlink_data($old_port_type) -{ - $result = $old_port_type; - if (is_string($old_port_type) && substr_count($old_port_type, '(') > 0) { - $pos1 = strpos($old_port_type, '('); - $pos2 = strpos($old_port_type, ')'); - $result = substr($old_port_type, $pos1 + 1, $pos2 - $pos1 - 1); - } +function convert_dlink_data($old_port_type) { + $result = $old_port_type; + + if (is_string($old_port_type) && substr_count($old_port_type, '(') > 0) { + $pos1 = strpos($old_port_type, '('); + $pos2 = strpos($old_port_type, ')'); + $result = substr($old_port_type, $pos1 + 1, $pos2 - $pos1 - 1); + } - return $result; + return $result; } diff --git a/lib/mactrack_enterasys.php b/lib/mactrack_enterasys.php index e7e699af..52933795 100644 --- a/lib/mactrack_enterasys.php +++ b/lib/mactrack_enterasys.php @@ -26,136 +26,136 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_enterasys_switch_ports'); -function get_enterasys_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - - // get VLAN information - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.4.4.1.2', $device); - - // get VLAN Trunk status - $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.5.4', $device); - $device['vlans_total'] = cacti_sizeof($vlan_trunkstatus); - mactrack_debug('VLAN data collected. There are '.cacti_sizeof($vlan_ids).' VLANS.'); - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); - - // get the ifTypes for the device - $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); - mactrack_debug('ifTypes data collection complete.'); - - // get the ifNames for the device - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete.'); - - // get ports that happen to be link ports - $link_ports = get_link_port_status($device); - mactrack_debug('ipAddrTable scanning for link ports data collection complete.'); - - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; - $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); - $ifInterfaces[$ifIndex]['ifType'] = mactrack_strip_alpha($ifTypes[$ifIndex]); - $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); - $ifInterfaces[$ifIndex]['trunkPortState'] = mactrack_arr_key($vlan_trunkstatus, $ifIndex); - } - } - mactrack_debug('ifInterfaces assembly complete.'); - - // calculate the number of end user ports - if (cacti_sizeof($ifTypes)) { - foreach ($ifTypes as $ifType) { - $ifType = mactrack_strip_alpha($ifType); - - if (($ifType >= 6) && ($ifType <= 9)) { - ++$device['ports_total']; - } - } - } - mactrack_debug('Total Ports = '.$device['ports_total']); - - // calculate the number of trunk ports - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - if (1 == $ifInterfaces[$ifIndex]['trunkPortState']) { - ++$device['ports_trunk']; - } - } - } - mactrack_debug('Total Trunk Ports = '.$device['ports_trunk']); - - // get VLAN details - $i = 0; - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_id => $vlan_name) { - $active_vlans[$i]['vlan_id'] = $vlan_id; - $active_vlans[$i]['vlan_name'] = $vlan_name; - ++$active_vlans; - ++$i; - } - } - - if (cacti_sizeof($active_vlans)) { - // get the port status information - $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); - $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.3.4', $device); - - $i = 0; - $j = 0; - $port_array = []; - - foreach ($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - $ifType = mactrack_strip_alpha($ifTypes[$ifIndex]); - $ifName = $ifNames[$ifIndex]; - $portName = $ifName; - $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; - - // only output legitimate end user ports - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); - $port_array[$i]['vlan_name'] = isset($vlan_ids[$port_array[$i]['vlan_id']]) ? $vlan_ids[$port_array[$i]['vlan_id']] : ''; - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - - mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' - .'NAME: '.$port_array[$i]['vlan_name'].', ' - .'PORT: '.$ifIndex.', ' - .'NAME: '.$port_array[$i]['port_name'].', ' - .'MAC: '.$port_array[$i]['mac_address']); - - ++$i; - } - - ++$j; - } - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_enterasys_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + + // get VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.4.4.1.2', $device); + + // get VLAN Trunk status + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.5.4', $device); + $device['vlans_total'] = cacti_sizeof($vlan_trunkstatus); + mactrack_debug('VLAN data collected. There are ' . cacti_sizeof($vlan_ids) . ' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get the ifTypes for the device + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + mactrack_debug('ifTypes data collection complete.'); + + // get the ifNames for the device + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete.'); + + // get ports that happen to be link ports + $link_ports = get_link_port_status($device); + mactrack_debug('ipAddrTable scanning for link ports data collection complete.'); + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); + $ifInterfaces[$ifIndex]['ifType'] = mactrack_strip_alpha($ifTypes[$ifIndex]); + $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); + $ifInterfaces[$ifIndex]['trunkPortState'] = mactrack_arr_key($vlan_trunkstatus, $ifIndex); + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // calculate the number of end user ports + if (cacti_sizeof($ifTypes)) { + foreach ($ifTypes as $ifType) { + $ifType = mactrack_strip_alpha($ifType); + + if (($ifType >= 6) && ($ifType <= 9)) { + ++$device['ports_total']; + } + } + } + mactrack_debug('Total Ports = ' . $device['ports_total']); + + // calculate the number of trunk ports + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + if ($ifInterfaces[$ifIndex]['trunkPortState'] == 1) { + ++$device['ports_trunk']; + } + } + } + mactrack_debug('Total Trunk Ports = ' . $device['ports_trunk']); + + // get VLAN details + $i = 0; + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_id => $vlan_name) { + $active_vlans[$i]['vlan_id'] = $vlan_id; + $active_vlans[$i]['vlan_name'] = $vlan_name; + ++$active_vlans; + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + // get the port status information + $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); + $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.52.4.1.2.16.3.1.1.3.4', $device); + + $i = 0; + $j = 0; + $port_array = []; + + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + $ifType = mactrack_strip_alpha($ifTypes[$ifIndex]); + $ifName = $ifNames[$ifIndex]; + $portName = $ifName; + $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); + $port_array[$i]['vlan_name'] = isset($vlan_ids[$port_array[$i]['vlan_id']]) ? $vlan_ids[$port_array[$i]['vlan_id']] : ''; + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + + mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' + . 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' + . 'PORT: ' . $ifIndex . ', ' + . 'NAME: ' . $port_array[$i]['port_name'] . ', ' + . 'MAC: ' . $port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } diff --git a/lib/mactrack_enterasys_N7.php b/lib/mactrack_enterasys_N7.php index 2801c364..45e7c147 100644 --- a/lib/mactrack_enterasys_N7.php +++ b/lib/mactrack_enterasys_N7.php @@ -25,12 +25,12 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_enterasys_N7_switch_ports'); if (!isset($mactrack_scanning_functions_ip)) { - $mactrack_scanning_functions_ip = []; + $mactrack_scanning_functions_ip = []; } array_push($mactrack_scanning_functions_ip, 'get_CTAlias_table'); @@ -39,477 +39,478 @@ mac_track_temp_ports table for future processing in the finalization steps of the scanning process. */ -function get_enterasys_N7_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - - // get VLAN information - $vlan_ids = xform_dot1q_vlan_associations($device, $device['snmp_readstring']); - // $vlan_ids = xform_enterasys_N7_vlan_associations($device, $device['snmp_readstring']); - // print_r($vlan_ids); - // get VLAN Trunk status: not (yet) implemented for Enterasys N7 - // $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.2272.1.3.3.1.4', $device); - $device['vlans_total'] = cacti_sizeof($vlan_ids); - mactrack_debug('VLAN data collected. There are '.cacti_sizeof($vlan_ids).' VLANS.'); - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete: '.cacti_sizeof($ifIndexes)); - - // get and store the interfaces table - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - // print_r($ifInterfaces); - - foreach ($ifIndexes as $ifIndex) { - if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { - ++$device['ports_total']; - } - } - mactrack_debug('ifInterfaces assembly complete: '.cacti_sizeof($ifIndexes)); - - // map vlans to bridge ports - if (cacti_sizeof($vlan_ids) > 0) { - // get the port status information - // $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); - $port_results = get_enterasys_N7_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); - // print_r($port_results); - // get the ifIndexes for the device - $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device); - // print_r($vlan_names); - - $i = 0; - $j = 0; - $port_array = []; - foreach ($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - // print_r($port_result); print_r($ifInterfaces[$ifIndex]); - $ifType = $ifInterfaces[$ifIndex]['ifType']; - - // only output legitimate end user ports - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_result['key']); - $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_names, $port_array[$i]['vlan_id']); - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - - mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' - .'NAME: '.$port_array[$i]['vlan_name'].', ' - .'PORT: '.$ifInterfaces[$ifIndex]['ifName'].', ' - .'NAME: '.$port_array[$i]['port_name'].', ' - .'MAC: '.$port_array[$i]['mac_address']); - - ++$i; - } - - ++$j; - } - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.trim(substr($device['snmp_sysDescr'], 0, 40)).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - mactrack_debug('macs active on this switch:'.$device['macs_active']); - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_enterasys_N7_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + + // get VLAN information + $vlan_ids = xform_dot1q_vlan_associations($device, $device['snmp_readstring']); + // $vlan_ids = xform_enterasys_N7_vlan_associations($device, $device['snmp_readstring']); + // print_r($vlan_ids); + // get VLAN Trunk status: not (yet) implemented for Enterasys N7 + // $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.2272.1.3.3.1.4', $device); + $device['vlans_total'] = cacti_sizeof($vlan_ids); + mactrack_debug('VLAN data collected. There are ' . cacti_sizeof($vlan_ids) . ' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete: ' . cacti_sizeof($ifIndexes)); + + // get and store the interfaces table + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + // print_r($ifInterfaces); + + foreach ($ifIndexes as $ifIndex) { + if (($ifInterfaces[$ifIndex]['ifType'] >= 6) && ($ifInterfaces[$ifIndex]['ifType'] <= 9)) { + ++$device['ports_total']; + } + } + mactrack_debug('ifInterfaces assembly complete: ' . cacti_sizeof($ifIndexes)); + + // map vlans to bridge ports + if (cacti_sizeof($vlan_ids) > 0) { + // get the port status information + // $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); + $port_results = get_enterasys_N7_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, $device['snmp_readstring'], false, $lowPort, $highPort); + // print_r($port_results); + // get the ifIndexes for the device + $vlan_names = xform_standard_indexed_data('.1.3.6.1.2.1.17.7.1.4.3.1.1', $device); + // print_r($vlan_names); + + $i = 0; + $j = 0; + $port_array = []; + + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + // print_r($port_result); print_r($ifInterfaces[$ifIndex]); + $ifType = $ifInterfaces[$ifIndex]['ifType']; + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_result['key']); + $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_names, $port_array[$i]['vlan_id']); + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = isset($ifInterfaces[$ifIndex]['ifName']) ? $ifInterfaces[$ifIndex]['ifName'] : ''; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + + mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' + . 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' + . 'PORT: ' . $ifInterfaces[$ifIndex]['ifName'] . ', ' + . 'NAME: ' . $port_array[$i]['port_name'] . ', ' + . 'MAC: ' . $port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . trim(substr($device['snmp_sysDescr'], 0, 40)) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + mactrack_debug('macs active on this switch:' . $device['macs_active']); + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_base_dot1dTpFdbEntry_ports - This function will grab information from the port bridge snmp table and return it to the calling progrem for further processing. This is a foundational function for all vendor data collection functions. */ -function get_enterasys_N7_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - mactrack_debug('FUNCTION: get_enterasys_N7_dot1dTpFdbEntry_ports started'); - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // cisco uses a hybrid read string, if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - mactrack_debug('get active ports: '.cacti_sizeof($active_ports_array)); - $indexes = array_keys($active_ports_array); - - $i = 0; - foreach ($active_ports_array as $port_info) { - if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 - GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 - where - table index = bridge port (dot1dBasePort) and - table value = ifIndex */ - // -------------------------------------------- - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - mactrack_debug('get bridgePortIfIndexes: '.cacti_sizeof($bridgePortIfIndexes)); - - /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ - // -------------------------------------------- - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - mactrack_debug('get port_status: '.cacti_sizeof($port_status)); - - /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 - GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 - where - table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and - table value = bridge port */ - // -------------------------------------------- - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - mactrack_debug('get port_numbers: '.cacti_sizeof($port_numbers)); - - // get VLAN information - // -------------------------------------------- - // $vlan_ids = xform_enterasys_N7_vlan_associations($device, $snmp_readstring); - $vlan_ids = xform_dot1q_vlan_associations($device, $snmp_readstring); - mactrack_debug('get vlan_ids: '.cacti_sizeof($vlan_ids)); - // print_r($vlan_ids); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - foreach ($port_numbers as $key => $port_number) { - // key = MAC Address from dot1dTpFdbTable - // value = bridge port - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort))) { - if (!in_array($port_number, $ignore_ports)) { - if (isset($port_status[$key]) && '3' == $port_status[$key]) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - // print('i: $i, Key: ' . $port_key_array[$i]['key'] . ', Number: $port_number\n'); - ++$i; - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (0 != cacti_sizeof($bridgePortIfIndexes)) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - mactrack_debug('Searching Bridge Port: '.$port_key['port_number'].', Bridge: '.$bridgePortIfIndexes[$port_key['port_number']]); - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); - } else { - $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); - } - $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; - } - - if (($brPortIfType >= 6) - && ($brPortIfType <= 9) - && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); - $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; - $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_key['key']); - // print_r($new_port_key_array[$i]); - ++$i; - } - } - } - mactrack_debug('Port number information collected: '.cacti_sizeof($new_port_key_array)); - - // map mac address - // only continue if there were user ports defined - if (cacti_sizeof($new_port_key_array) > 0) { - // get the bridges active MAC addresses - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); - mactrack_debug('INDEX: '.$key.' MAC ADDRESS: '.$new_port_key_array[$key]['mac_address']); - } - - mactrack_debug('Port mac address information collected: '.cacti_sizeof($port_macs)); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array) > 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_enterasys_N7_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + mactrack_debug('FUNCTION: get_enterasys_N7_dot1dTpFdbEntry_ports started'); + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + mactrack_debug('get active ports: ' . cacti_sizeof($active_ports_array)); + $indexes = array_keys($active_ports_array); + + $i = 0; + + foreach ($active_ports_array as $port_info) { + if (($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + /* get bridge port to ifIndex mapping: dot1dBasePortIfIndex from dot1dBasePortTable + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.1: 1 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.2: 4 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.64: 12001 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.65: 12002 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.66: 12003 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.67: 12004 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.68: 12005 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.69: 12006 + GET NEXT: 1.3.6.1.2.1.17.1.4.1.2.70: 12007 + where + table index = bridge port (dot1dBasePort) and + table value = ifIndex */ + // -------------------------------------------- + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + mactrack_debug('get bridgePortIfIndexes: ' . cacti_sizeof($bridgePortIfIndexes)); + + /* get port status: dot1dTpFdbStatus from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.0.94.0.1.1: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.32.11.99: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.228.26: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.227.37.238.180: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.56.96.234: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.59.133.114: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.157.61: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.107.189.168: 3 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.3.0.1.230.109.208.105: 3 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = port status (other(1), invalid(2), learned(3), self(4), mgmt(5)*/ + // -------------------------------------------- + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + mactrack_debug('get port_status: ' . cacti_sizeof($port_status)); + + /* get device active port numbers: dot1dTpFdbPort from dot1dTpFdbTable + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.0.94.0.1.1: 72 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.32.11.99: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.228.26: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.227.37.238.180: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.56.96.234: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.59.133.114: 69 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.157.61: 70 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.107.189.168: 68 + GET NEXT: 1.3.6.1.2.1.17.4.3.1.2.0.1.230.109.208.105: 68 + where + table index = MAC Address (dot1dTpFdbAddress e.g. 0.0.94.0.1.1 = 00:00:5E:00:01:01) and + table value = bridge port */ + // -------------------------------------------- + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + mactrack_debug('get port_numbers: ' . cacti_sizeof($port_numbers)); + + // get VLAN information + // -------------------------------------------- + // $vlan_ids = xform_enterasys_N7_vlan_associations($device, $snmp_readstring); + $vlan_ids = xform_dot1q_vlan_associations($device, $snmp_readstring); + mactrack_debug('get vlan_ids: ' . cacti_sizeof($vlan_ids)); + // print_r($vlan_ids); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + foreach ($port_numbers as $key => $port_number) { + // key = MAC Address from dot1dTpFdbTable + // value = bridge port + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports, true)) { + if (isset($port_status[$key]) && $port_status[$key] == '3') { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + // print('i: $i, Key: ' . $port_key_array[$i]['key'] . ', Number: $port_number\n'); + ++$i; + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes) != 0) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + mactrack_debug('Searching Bridge Port: ' . $port_key['port_number'] . ', Bridge: ' . $bridgePortIfIndexes[$port_key['port_number']]); + + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = mactrack_arr_key($bridgePortIfIndexes, $port_key['port_number']); + } else { + $brPortIfIndex = mactrack_arr_key($port_key, 'port_number'); + } + $brPortIfType = isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = isset($ifInterfaces[$port_key['port_number']]['ifType']) ? $ifInterfaces[$port_key['port_number']]['ifType'] : ''; + } + + if (($brPortIfType >= 6) + && ($brPortIfType <= 9) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = mactrack_arr_key($port_key, 'key'); + $new_port_key_array[$i]['port_number'] = isset($brPortIfIndex) ? $brPortIfIndex : ''; + $new_port_key_array[$i]['vlan_id'] = mactrack_arr_key($vlan_ids, $port_key['key']); + // print_r($new_port_key_array[$i]); + ++$i; + } + } + } + mactrack_debug('Port number information collected: ' . cacti_sizeof($new_port_key_array)); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array) > 0) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = mactrack_arr_key($port_macs, $port_key['key']); + mactrack_debug('INDEX: ' . $key . ' MAC ADDRESS: ' . $new_port_key_array[$key]['mac_address']); + } + + mactrack_debug('Port mac address information collected: ' . cacti_sizeof($port_macs)); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array) > 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } -function enterasys_N7_convert_macs($oldmac) -{ - $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); - $oldmac = substr($oldmac, stripos($oldmac, '.')); - $piece = explode('.', $oldmac); - $newmac = ''; +function enterasys_N7_convert_macs($oldmac) { + $oldmac = substr($oldmac, stripos($oldmac, '.') + 1); + $oldmac = substr($oldmac, stripos($oldmac, '.')); + $piece = explode('.', $oldmac); + $newmac = ''; - for ($i = 0; $i < 6; ++$i) { - $newmac .= ('' != $newmac ? ':' : '').dec2hex($piece[$i], 2); - } + for ($i = 0; $i < 6; ++$i) { + $newmac .= ($newmac != '' ? ':' : '') . dec2hex($piece[$i], 2); + } - return $newmac; + return $newmac; } -function xform_enterasys_N7_vlan_associations(&$device, $snmp_readstring = '') -{ - // get raw index data - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // initialize the output array - $output_array = []; - - // obtain vlan associations: dot1qTpFdbStatus from dot1qTpFdbTable - $xformArray = cacti_snmp_walk( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.2.2.1.2', - $device['snmp_version'], - '', - '', - '', - '', - '', - '', - $device['snmp_port'], - $device['snmp_timeout'] - ); - - $i = 0; - foreach ($xformArray as $xformItem) { - // peel off the beginning of the OID - $key = $xformItem['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); - - // now grab the VLAN Id - $perPos = strpos($key, '.', 1); - $output_array[$i]['vlan_id'] = substr($key, 1, $perPos - 1); - - // save the key=MAC Address for association with the dot1d table - $output_array[$i]['key'] = substr($key, $perPos); - - // get VLAN name, if any: dot1qVlanStaticName from dot1qVlanStaticTable - $vlan_name = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.4.3.1.1.'.$output_array[$i]['vlan_id'], - $device['snmp_version'], - '', - '', - '', - '', - '', - '', - $device['snmp_port'], - $device['snmp_timeout'] - ); - $output_array[$i]['vlan_name'] = $vlan_name; - ++$i; - } - - return array_rekey($output_array, 'key', 'vlan_id'); - // return $output_array; +function xform_enterasys_N7_vlan_associations(&$device, $snmp_readstring = '') { + // get raw index data + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // initialize the output array + $output_array = []; + + // obtain vlan associations: dot1qTpFdbStatus from dot1qTpFdbTable + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.2.2.1.2', + $device['snmp_version'], + '', + '', + '', + '', + '', + '', + $device['snmp_port'], + $device['snmp_timeout'] + ); + + $i = 0; + + foreach ($xformArray as $xformItem) { + // peel off the beginning of the OID + $key = $xformItem['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); + + // now grab the VLAN Id + $perPos = strpos($key, '.', 1); + $output_array[$i]['vlan_id'] = substr($key, 1, $perPos - 1); + + // save the key=MAC Address for association with the dot1d table + $output_array[$i]['key'] = substr($key, $perPos); + + // get VLAN name, if any: dot1qVlanStaticName from dot1qVlanStaticTable + $vlan_name = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.4.3.1.1.' . $output_array[$i]['vlan_id'], + $device['snmp_version'], + '', + '', + '', + '', + '', + '', + $device['snmp_port'], + $device['snmp_timeout'] + ); + $output_array[$i]['vlan_name'] = $vlan_name; + ++$i; + } + + return array_rekey($output_array, 'key', 'vlan_id'); + // return $output_array; } -function get_enterasys_N7_vlan_id($OID) -{ - $perPos = strpos($OID, '.', 1); +function get_enterasys_N7_vlan_id($OID) { + $perPos = strpos($OID, '.', 1); - return substr($OID, 0, $perPos); + return substr($OID, 0, $perPos); } /* get_CTAlias_table - This function reads a devices CTAlias table for a site and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_CTAlias_table($site, &$device) -{ - global $debug, $scan_date; - - mactrack_debug('FUNCTION: get_CTAlias_table started'); - - // get the CTAlias Table for the device - $CTAliasInterfaces = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.3', $device, 2); - mactrack_debug('CTAliasInterfaces data collection complete: '.cacti_sizeof($CTAliasInterfaces)); - - // get the CTAliasMacAddress for the device - $CTAliasMacAddress = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.4', $device, 2, true); - mactrack_debug('CTAliasMacAddress data collection complete: '.cacti_sizeof($CTAliasMacAddress)); - - // convert the mac address if necessary - $keys = array_keys($CTAliasMacAddress); - $i = 0; - foreach ($CTAliasMacAddress as $MacAddress) { - $CTAliasMacAddress[$keys[$i]] = xform_mac_address($MacAddress); - ++$i; - } - - // get the CTAliasProtocol Table for the device - $CTAliasProtocol = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.6', $device, 2); - mactrack_debug('CTAliasProtocol data collection complete: '.cacti_sizeof($CTAliasProtocol)); - - // get the CTAliasAddressText for the device - $CTAliasAddressText = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.9', $device, 2); - mactrack_debug('CTAliasAddressText data collection complete: '.cacti_sizeof($CTAliasAddressText)); - - // get the ifNames for the device - $keys = array_keys($CTAliasInterfaces); - $i = 0; - $CTAliasEntries = []; - - foreach ($CTAliasInterfaces as $ifIndex) { - $CTAliasEntries[$i]['ifIndex'] = $ifIndex; - $CTAliasEntries[$i]['timestamp'] = $keys[$i]; - $CTAliasEntries[$i]['CTAliasProtocol'] = mactrack_arr_key($CTAliasProtocol, $keys[$i]); - $CTAliasEntries[$i]['CTAliasMacAddress'] = mactrack_arr_key($CTAliasMacAddress, $keys[$i]); - $CTAliasEntries[$i]['CTAliasAddressText'] = mactrack_arr_key($CTAliasAddressText, $keys[$i]); - ++$i; - } - mactrack_debug('CTAliasEntries assembly complete: '.cacti_sizeof($CTAliasEntries)); - - // output details to database - if (cacti_sizeof($CTAliasEntries)) { - $sql = []; - - foreach ($CTAliasEntries as $CTAliasEntry) { - // drop non-IP protocols - if (1 != $CTAliasEntry['CTAliasProtocol']) { - continue; - } - - $sql[] = '(' - .$device['site_id'].', ' - .$device['device_id'].', ' - .db_qstr($device['hostname']).', ' - .db_qstr($device['device_name']).', ' - .db_qstr($CTAliasEntry['ifIndex']).', ' - .db_qstr($CTAliasEntry['CTAliasMacAddress']).', ' - .db_qstr($CTAliasEntry['CTAliasAddressText']).', ' - .db_qstr($scan_date).')'; - } - - db_execute('REPLACE INTO mac_track_ips +function get_CTAlias_table($site, &$device) { + global $debug, $scan_date; + + mactrack_debug('FUNCTION: get_CTAlias_table started'); + + // get the CTAlias Table for the device + $CTAliasInterfaces = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.3', $device, 2); + mactrack_debug('CTAliasInterfaces data collection complete: ' . cacti_sizeof($CTAliasInterfaces)); + + // get the CTAliasMacAddress for the device + $CTAliasMacAddress = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.4', $device, 2, true); + mactrack_debug('CTAliasMacAddress data collection complete: ' . cacti_sizeof($CTAliasMacAddress)); + + // convert the mac address if necessary + $keys = array_keys($CTAliasMacAddress); + $i = 0; + + foreach ($CTAliasMacAddress as $MacAddress) { + $CTAliasMacAddress[$keys[$i]] = xform_mac_address($MacAddress); + ++$i; + } + + // get the CTAliasProtocol Table for the device + $CTAliasProtocol = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.6', $device, 2); + mactrack_debug('CTAliasProtocol data collection complete: ' . cacti_sizeof($CTAliasProtocol)); + + // get the CTAliasAddressText for the device + $CTAliasAddressText = xform_indexed_data('.1.3.6.1.4.1.52.4.1.3.7.1.1.1.1.9', $device, 2); + mactrack_debug('CTAliasAddressText data collection complete: ' . cacti_sizeof($CTAliasAddressText)); + + // get the ifNames for the device + $keys = array_keys($CTAliasInterfaces); + $i = 0; + $CTAliasEntries = []; + + foreach ($CTAliasInterfaces as $ifIndex) { + $CTAliasEntries[$i]['ifIndex'] = $ifIndex; + $CTAliasEntries[$i]['timestamp'] = $keys[$i]; + $CTAliasEntries[$i]['CTAliasProtocol'] = mactrack_arr_key($CTAliasProtocol, $keys[$i]); + $CTAliasEntries[$i]['CTAliasMacAddress'] = mactrack_arr_key($CTAliasMacAddress, $keys[$i]); + $CTAliasEntries[$i]['CTAliasAddressText'] = mactrack_arr_key($CTAliasAddressText, $keys[$i]); + ++$i; + } + mactrack_debug('CTAliasEntries assembly complete: ' . cacti_sizeof($CTAliasEntries)); + + // output details to database + if (cacti_sizeof($CTAliasEntries)) { + $sql = []; + + foreach ($CTAliasEntries as $CTAliasEntry) { + // drop non-IP protocols + if ($CTAliasEntry['CTAliasProtocol'] != 1) { + continue; + } + + $sql[] = '(' + . $device['site_id'] . ', ' + . $device['device_id'] . ', ' + . db_qstr($device['hostname']) . ', ' + . db_qstr($device['device_name']) . ', ' + . db_qstr($CTAliasEntry['ifIndex']) . ', ' + . db_qstr($CTAliasEntry['CTAliasMacAddress']) . ', ' + . db_qstr($CTAliasEntry['CTAliasAddressText']) . ', ' + . db_qstr($scan_date) . ')'; + } + + db_execute('REPLACE INTO mac_track_ips (site_id,device_id,hostname,device_name,port_number, mac_address,ip_address,scan_date) - VALUES '.implode(', ', $sql)); - } + VALUES ' . implode(', ', $sql)); + } - // save ip information for the device - $device['ips_total'] = cacti_sizeof($CTAliasEntries); + // save ip information for the device + $device['ips_total'] = cacti_sizeof($CTAliasEntries); - db_execute_prepared( - 'UPDATE mac_track_devices + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id= ?', - [$device['ips_total'], $device['device_id']] - ); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete: '.$device['ips_total']); + mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete: ' . $device['ips_total']); } diff --git a/lib/mactrack_extreme.php b/lib/mactrack_extreme.php index 704656bd..e90efb39 100644 --- a/lib/mactrack_extreme.php +++ b/lib/mactrack_extreme.php @@ -25,291 +25,292 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_extreme_switch_ports'); array_push($mactrack_scanning_functions, 'get_extreme_extremeware_switch_ports'); if (!isset($mactrack_scanning_functions_ip)) { - $mactrack_scanning_functions_ip = []; + $mactrack_scanning_functions_ip = []; } array_push($mactrack_scanning_functions_ip, 'get_extreme_arp_table'); array_push($mactrack_scanning_functions_ip, 'get_extreme_extremeware_arp_table'); -function get_extreme_extremeware_switch_ports($site, &$device, $lowPort = 0, $highPort = 0, $extremeware = false) -{ - return get_extreme_switch_ports($site, $device, $lowPort, $highPort, true); +function get_extreme_extremeware_switch_ports($site, &$device, $lowPort = 0, $highPort = 0, $extremeware = false) { + return get_extreme_switch_ports($site, $device, $lowPort, $highPort, true); } -function get_extreme_extremeware_arp_table($site, &$device, $extremeware = false) -{ - get_extreme_arp_table($site, $device, true); +function get_extreme_extremeware_arp_table($site, &$device, $extremeware = false) { + get_extreme_arp_table($site, $device, true); } -function get_extreme_switch_ports($site, &$device, $lowPort = 0, $highPort = 0, $extremeware = false) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - $device['macs_active'] = 0; - - /* get VLAN information - VLAN index - .1.3.6.1.4.1.1916.1.2.1.2.1.1 - EXTREME-VLAN-MIB::extremeVlanIfIndex. = index - VLAN name - .1.3.6.1.4.1.1916.1.2.1.2.1.2 - EXTREME-VLAN-MIB::extremeVlanIfDescr. = description - VLAN ID - .1.3.6.1.4.1.1916.1.2.1.2.1.10 - EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id - */ - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); - $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.2', $device); - $device['vlans_total'] = cacti_sizeof($vlan_ids); - mactrack_debug('There are '.cacti_sizeof($vlan_ids).' VLANS.'); - - /* get the ifIndexes for the device - .1.3.6.1.2.1.2.2.1.1 - RFC1213-MIB::ifIndex. = index - .1.3.6.1.2.1.2.2.1.2 - RFC1213-MIB::ifDescr. = description - .1.3.6.1.2.1.2.2.1.3 - RFC1213-MIB::ifType. = type (6=ether) - .1.3.6.1.2.1.31.1.1.1.1 - IF-MIB::ifName. = name - .1.3.6.1.2.1.31.1.1.1.18 - IF-MIB::ifAlias. = alias - */ - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); - - mactrack_debug('ifInterfaces assembly complete.'); - - // get VLAN details - $i = 0; - foreach ($vlan_ids as $vlan_index => $vlan_id) { - $active_vlans[$i]['vlan_id'] = $vlan_id; - $active_vlans[$i]['vlan_name'] = $vlan_names[$vlan_index]; - ++$active_vlans; - mactrack_debug('VLAN ID = '.$active_vlans[$i]['vlan_id'].' VLAN Name = '.$active_vlans[$i]['vlan_name']); - ++$i; - } - - if (cacti_sizeof($active_vlans) > 0) { - // get the port status information - // get port_number and MAC addr - /*extremeXOS - addr mac - .1.3.6.1.4.1.1916.1.16.4.1.1 - EXTREME-BASE-MIB::extremeFdb.4.1.1..= hex MAC - index du vlan ? - .1.3.6.1.4.1.1916.1.16.4.1.2 - EXTREME-BASE-MIB::extremeFdb.4.1.2..=vlanid - index du port - .1.3.6.1.4.1.1916.1.16.4.1.3 - EXTREME-BASE-MIB::extremeFdb.4.1.3..=port id - status - .1.3.6.1.4.1.1916.1.16.4.1.4 - EXTREME-BASE-MIB::extremeFdb.4.1.4..= 3 learned - - extremeware - .1.3.6.1.4.1.1916.1.16.1.1.3 - EXTREME-FDB-MIB::extremeFdbMacFdbMacAddress.. = mac - .1.3.6.1.4.1.1916.1.16.1.1.4 - EXTREME-FDB-MIB::extremeFdbMacFdbPortIfIndex.. = index du port - .1.3.6.1.4.1.1916.1.16.1.1.5 - EXTREME-FDB-MIB::extremeFdbMacFdbStatus.. = 3 learned - */ - if ($extremeware) { - $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.3', $device); - $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.4', $device); - $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.5', $device); - } else { - $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.1', $device); - $mac_vlan_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.2', $device); - $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.3', $device); - $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.4', $device); - } - - $port_array = []; - - foreach ($mac_addr_list as $mac_key => $mac_addr) { - // check if mac addr is 'learned' or 'mgnt' - if (isset($mac_status_list[$mac_key]) and (('3' == $mac_status_list[$mac_key]) || ('5' == $mac_status_list[$mac_key]))) { - $ifIndex = $mac_port_list[$mac_key]; - $ifType = $ifInterfaces[$ifIndex]['ifType']; - // $ifType = $ifTypes[$ifIndex]; - // only output legitimate end user ports - if (($ifType >= 6) && ($ifType <= 9)) { - if ($extremeware) { - $vlanid = substr($mac_key, 0, strpos($mac_key, '.')); - $new_port_array['vlan_id'] = $vlan_ids[$vlanid]; - $new_port_array['vlan_name'] = $vlan_names[$vlanid]; - } else { - $new_port_array['vlan_id'] = $vlan_ids[$mac_vlan_list[$mac_key]]; - $new_port_array['vlan_name'] = $vlan_names[$mac_vlan_list[$mac_key]]; - } - - // $new_port_array['port_number'] = $ifIndex; - // $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifName']; - $new_port_array['port_number'] = $ifInterfaces[$ifIndex]['ifName']; - $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifAlias']; - $new_port_array['mac_address'] = xform_mac_address($mac_addr_list[$mac_key]); - $ifInterfaces[$ifIndex]['Used'] = 1; - $port_array[] = $new_port_array; - - mactrack_debug('VLAN: '.$new_port_array['vlan_id'].', ' - .'NAME: '.$new_port_array['vlan_name'].', ' - .'PORT: '.$ifIndex.', ' - .'NAME: '.$new_port_array['port_name'].', ' - .'MAC: '.$new_port_array['mac_address']); - } - } - } - - $device['ports_total'] = cacti_sizeof($ifInterfaces); - $device['ports_active'] = 0; - - foreach ($ifInterfaces as $interface) { - if (isset($interface['Used'])) { - ++$device['ports_active']; - } - } - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_extreme_switch_ports($site, &$device, $lowPort = 0, $highPort = 0, $extremeware = false) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + $device['macs_active'] = 0; + + /* get VLAN information + VLAN index + .1.3.6.1.4.1.1916.1.2.1.2.1.1 + EXTREME-VLAN-MIB::extremeVlanIfIndex. = index + VLAN name + .1.3.6.1.4.1.1916.1.2.1.2.1.2 + EXTREME-VLAN-MIB::extremeVlanIfDescr. = description + VLAN ID + .1.3.6.1.4.1.1916.1.2.1.2.1.10 + EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id + */ + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); + $vlan_names = xform_standard_indexed_data('.1.3.6.1.4.1.1916.1.2.1.2.1.2', $device); + $device['vlans_total'] = cacti_sizeof($vlan_ids); + mactrack_debug('There are ' . cacti_sizeof($vlan_ids) . ' VLANS.'); + + /* get the ifIndexes for the device + .1.3.6.1.2.1.2.2.1.1 + RFC1213-MIB::ifIndex. = index + .1.3.6.1.2.1.2.2.1.2 + RFC1213-MIB::ifDescr. = description + .1.3.6.1.2.1.2.2.1.3 + RFC1213-MIB::ifType. = type (6=ether) + .1.3.6.1.2.1.31.1.1.1.1 + IF-MIB::ifName. = name + .1.3.6.1.2.1.31.1.1.1.18 + IF-MIB::ifAlias. = alias + */ + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, true); + + mactrack_debug('ifInterfaces assembly complete.'); + + // get VLAN details + $i = 0; + + foreach ($vlan_ids as $vlan_index => $vlan_id) { + $active_vlans[$i]['vlan_id'] = $vlan_id; + $active_vlans[$i]['vlan_name'] = $vlan_names[$vlan_index]; + ++$active_vlans; + mactrack_debug('VLAN ID = ' . $active_vlans[$i]['vlan_id'] . ' VLAN Name = ' . $active_vlans[$i]['vlan_name']); + ++$i; + } + + if (cacti_sizeof($active_vlans) > 0) { + // get the port status information + // get port_number and MAC addr + /*extremeXOS + addr mac + .1.3.6.1.4.1.1916.1.16.4.1.1 + EXTREME-BASE-MIB::extremeFdb.4.1.1..= hex MAC + index du vlan ? + .1.3.6.1.4.1.1916.1.16.4.1.2 + EXTREME-BASE-MIB::extremeFdb.4.1.2..=vlanid + index du port + .1.3.6.1.4.1.1916.1.16.4.1.3 + EXTREME-BASE-MIB::extremeFdb.4.1.3..=port id + status + .1.3.6.1.4.1.1916.1.16.4.1.4 + EXTREME-BASE-MIB::extremeFdb.4.1.4..= 3 learned + + extremeware + .1.3.6.1.4.1.1916.1.16.1.1.3 + EXTREME-FDB-MIB::extremeFdbMacFdbMacAddress.. = mac + .1.3.6.1.4.1.1916.1.16.1.1.4 + EXTREME-FDB-MIB::extremeFdbMacFdbPortIfIndex.. = index du port + .1.3.6.1.4.1.1916.1.16.1.1.5 + EXTREME-FDB-MIB::extremeFdbMacFdbStatus.. = 3 learned + */ + if ($extremeware) { + $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.3', $device); + $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.4', $device); + $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.1.1.5', $device); + } else { + $mac_addr_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.1', $device); + $mac_vlan_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.2', $device); + $mac_port_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.3', $device); + $mac_status_list = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.4.1.4', $device); + } + + $port_array = []; + + foreach ($mac_addr_list as $mac_key => $mac_addr) { + // check if mac addr is 'learned' or 'mgnt' + if (isset($mac_status_list[$mac_key]) && (($mac_status_list[$mac_key] == '3') || ($mac_status_list[$mac_key] == '5'))) { + $ifIndex = $mac_port_list[$mac_key]; + $ifType = $ifInterfaces[$ifIndex]['ifType']; + + // $ifType = $ifTypes[$ifIndex]; + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + if ($extremeware) { + $vlanid = substr($mac_key, 0, strpos($mac_key, '.')); + $new_port_array['vlan_id'] = $vlan_ids[$vlanid]; + $new_port_array['vlan_name'] = $vlan_names[$vlanid]; + } else { + $new_port_array['vlan_id'] = $vlan_ids[$mac_vlan_list[$mac_key]]; + $new_port_array['vlan_name'] = $vlan_names[$mac_vlan_list[$mac_key]]; + } + + // $new_port_array['port_number'] = $ifIndex; + // $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifName']; + $new_port_array['port_number'] = $ifInterfaces[$ifIndex]['ifName']; + $new_port_array['port_name'] = $ifInterfaces[$ifIndex]['ifAlias']; + $new_port_array['mac_address'] = xform_mac_address($mac_addr_list[$mac_key]); + $ifInterfaces[$ifIndex]['Used'] = 1; + $port_array[] = $new_port_array; + + mactrack_debug('VLAN: ' . $new_port_array['vlan_id'] . ', ' + . 'NAME: ' . $new_port_array['vlan_name'] . ', ' + . 'PORT: ' . $ifIndex . ', ' + . 'NAME: ' . $new_port_array['port_name'] . ', ' + . 'MAC: ' . $new_port_array['mac_address']); + } + } + } + + $device['ports_total'] = cacti_sizeof($ifInterfaces); + $device['ports_active'] = 0; + + foreach ($ifInterfaces as $interface) { + if (isset($interface['Used'])) { + ++$device['ports_active']; + } + } + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } /* get_extreme_arp_table - This function reads a devices ARP table for a site and stores the IP address and MAC address combinations in the mac_track_ips table. */ -function get_extreme_arp_table($site, &$device, $extremeware = false) -{ - global $debug, $scan_date; - /* - EXTREME-FDB-MIB::extremeFdbIpFdbIPAddress : The IP Address of the IP FDB entry. - .1.3.6.1.4.1.1916.1.16.2.1.2 - EXTREME-FDB-MIB::extremeFdbIpFdbMacAddress : The MAC address corresponding to the IP Address. - .1.3.6.1.4.1.1916.1.16.2.1.3 - EXTREME-FDB-MIB::extremeFdbIpFdbVlanIfIndex : The ifIndex of the Vlan on which this ip is learned. - .1.3.6.1.4.1.1916.1.16.2.1.4 - EXTREME-FDB-MIB::extremeFdbIpFdbPortIfIndex : The IfIndex of the port on which this entry was learned. - .1.3.6.1.4.1.1916.1.16.2.1.5 - EXTREME-VLAN-MIB::extremeVlanIfIndex. = index - .1.3.6.1.4.1.1916.1.2.1.2.1.1 - EXTREME-VLAN-MIB::extremeVlanIfDescr. = description - .1.3.6.1.4.1.1916.1.2.1.2.1.2 - EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id - .1.3.6.1.4.1.1916.1.2.1.2.1.10 - BRIDGE-MIB::dot1dBasePortIfIndex : get Ifindex from extremeFdbIpFdbPortIfIndex - .1.3.6.1.2.1.17.1.4.1.2 - IF-MIB::ifName : get name of port from IfIndex - .1.3.6.1.2.1.31.1.1.1.1 - */ - if ($extremeware) { // for extremeware use standard apr table + ifDescr for interface name - // get the atifIndexes for the device - $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); - $atEntries = []; - - if (cacti_sizeof($atifIndexes)) { - mactrack_debug('atifIndexes data collection complete'); - $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device, true); - mactrack_debug('atPhysAddress data collection complete'); - $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device, true); - mactrack_debug('atNetAddress data collection complete'); - $ifDescr = xform_stripped_oid('.1.3.6.1.2.1.2.2.1.2', $device); - mactrack_debug('ifDescr data collection complete'); - } - $i = 0; - if (cacti_sizeof($atifIndexes)) { - foreach ($atifIndexes as $key => $atifIndex) { - $atEntries[$i]['atifIndex'] = $ifDescr[$atifIndex]; - $atEntries[$i]['atPhysAddress'] = xform_mac_address($atPhysAddress[$key]); - $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$key]); - ++$i; - } - } - } else { - // get the atifIndexes for the device - $FdbPortIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.5', $device); - $atEntries = []; - - if (cacti_sizeof($FdbPortIfIndex)) { - mactrack_debug('FdbPortIfIndex data collection complete'); - $FdbMacAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.3', $device, true); - mactrack_debug('FdbMacAddress data collection complete'); - $FdbIPAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.2', $device); - mactrack_debug('FdbIPAddress data collection complete'); - $FdbVlanIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.4', $device); - mactrack_debug('FdbVlanIfIndex data collection complete'); - $VlanIfVlanId = xform_stripped_oid('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); - mactrack_debug('VlanIfVlanId data collection complete'); - $BasePortIfIndex = xform_stripped_oid('.1.3.6.1.2.1.17.1.4.1.2', $device); - mactrack_debug('BasePortIfIndex data collection complete'); - $ifName = xform_stripped_oid('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifName data collection complete'); - } - - $i = 0; - if (cacti_sizeof($FdbPortIfIndex)) { - foreach ($FdbPortIfIndex as $key => $PortIndex) { - $atEntries[$i]['atifIndex'] = $ifName[$BasePortIfIndex[$PortIndex]].', vlan:'.$VlanIfVlanId[$FdbVlanIfIndex[$key]]; - $atEntries[$i]['atPhysAddress'] = xform_mac_address($FdbMacAddress[$key]); - $atEntries[$i]['atNetAddress'] = xform_net_address($FdbIPAddress[$key]); - ++$i; - } - } - - mactrack_debug('atEntries assembly complete.'); - } - - // output details to database - if (cacti_sizeof($atEntries)) { - $sql = []; - - foreach ($atEntries as $atEntry) { - $sql[] = '(' - .$device['site_id'].', ' - .$device['device_id'].', ' - .db_qstr($device['hostname']).', ' - .db_qstr($device['device_name']).', ' - .db_qstr($atEntry['atifIndex']).', ' - .db_qstr($atEntry['atPhysAddress']).', ' - .db_qstr($atEntry['atNetAddress']).', ' - .db_qstr($scan_date).')'; - } - - if (cacti_sizeof($sql)) { - db_execute('REPLACE INTO mac_track_ips +function get_extreme_arp_table($site, &$device, $extremeware = false) { + global $debug, $scan_date; + + /* + EXTREME-FDB-MIB::extremeFdbIpFdbIPAddress : The IP Address of the IP FDB entry. + .1.3.6.1.4.1.1916.1.16.2.1.2 + EXTREME-FDB-MIB::extremeFdbIpFdbMacAddress : The MAC address corresponding to the IP Address. + .1.3.6.1.4.1.1916.1.16.2.1.3 + EXTREME-FDB-MIB::extremeFdbIpFdbVlanIfIndex : The ifIndex of the Vlan on which this ip is learned. + .1.3.6.1.4.1.1916.1.16.2.1.4 + EXTREME-FDB-MIB::extremeFdbIpFdbPortIfIndex : The IfIndex of the port on which this entry was learned. + .1.3.6.1.4.1.1916.1.16.2.1.5 + EXTREME-VLAN-MIB::extremeVlanIfIndex. = index + .1.3.6.1.4.1.1916.1.2.1.2.1.1 + EXTREME-VLAN-MIB::extremeVlanIfDescr. = description + .1.3.6.1.4.1.1916.1.2.1.2.1.2 + EXTREME-VLAN-MIB::extremeVlanIfVlanId. = tag id + .1.3.6.1.4.1.1916.1.2.1.2.1.10 + BRIDGE-MIB::dot1dBasePortIfIndex : get Ifindex from extremeFdbIpFdbPortIfIndex + .1.3.6.1.2.1.17.1.4.1.2 + IF-MIB::ifName : get name of port from IfIndex + .1.3.6.1.2.1.31.1.1.1.1 + */ + if ($extremeware) { // for extremeware use standard apr table + ifDescr for interface name + // get the atifIndexes for the device + $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); + $atEntries = []; + + if (cacti_sizeof($atifIndexes)) { + mactrack_debug('atifIndexes data collection complete'); + $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device, true); + mactrack_debug('atPhysAddress data collection complete'); + $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device, true); + mactrack_debug('atNetAddress data collection complete'); + $ifDescr = xform_stripped_oid('.1.3.6.1.2.1.2.2.1.2', $device); + mactrack_debug('ifDescr data collection complete'); + } + $i = 0; + + if (cacti_sizeof($atifIndexes)) { + foreach ($atifIndexes as $key => $atifIndex) { + $atEntries[$i]['atifIndex'] = $ifDescr[$atifIndex]; + $atEntries[$i]['atPhysAddress'] = xform_mac_address($atPhysAddress[$key]); + $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$key]); + ++$i; + } + } + } else { + // get the atifIndexes for the device + $FdbPortIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.5', $device); + $atEntries = []; + + if (cacti_sizeof($FdbPortIfIndex)) { + mactrack_debug('FdbPortIfIndex data collection complete'); + $FdbMacAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.3', $device, true); + mactrack_debug('FdbMacAddress data collection complete'); + $FdbIPAddress = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.2', $device); + mactrack_debug('FdbIPAddress data collection complete'); + $FdbVlanIfIndex = xform_stripped_oid('.1.3.6.1.4.1.1916.1.16.2.1.4', $device); + mactrack_debug('FdbVlanIfIndex data collection complete'); + $VlanIfVlanId = xform_stripped_oid('.1.3.6.1.4.1.1916.1.2.1.2.1.10', $device); + mactrack_debug('VlanIfVlanId data collection complete'); + $BasePortIfIndex = xform_stripped_oid('.1.3.6.1.2.1.17.1.4.1.2', $device); + mactrack_debug('BasePortIfIndex data collection complete'); + $ifName = xform_stripped_oid('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifName data collection complete'); + } + + $i = 0; + + if (cacti_sizeof($FdbPortIfIndex)) { + foreach ($FdbPortIfIndex as $key => $PortIndex) { + $atEntries[$i]['atifIndex'] = $ifName[$BasePortIfIndex[$PortIndex]] . ', vlan:' . $VlanIfVlanId[$FdbVlanIfIndex[$key]]; + $atEntries[$i]['atPhysAddress'] = xform_mac_address($FdbMacAddress[$key]); + $atEntries[$i]['atNetAddress'] = xform_net_address($FdbIPAddress[$key]); + ++$i; + } + } + + mactrack_debug('atEntries assembly complete.'); + } + + // output details to database + if (cacti_sizeof($atEntries)) { + $sql = []; + + foreach ($atEntries as $atEntry) { + $sql[] = '(' + . $device['site_id'] . ', ' + . $device['device_id'] . ', ' + . db_qstr($device['hostname']) . ', ' + . db_qstr($device['device_name']) . ', ' + . db_qstr($atEntry['atifIndex']) . ', ' + . db_qstr($atEntry['atPhysAddress']) . ', ' + . db_qstr($atEntry['atNetAddress']) . ', ' + . db_qstr($scan_date) . ')'; + } + + if (cacti_sizeof($sql)) { + db_execute('REPLACE INTO mac_track_ips (site_id, device_id, hostname, device_name, port_number, mac_address,ip_address,scan_date) - VALUES '.implode(', ', $sql)); - } - } - - // save ip information for the device - $device['ips_total'] = cacti_sizeof($atEntries); - db_execute_prepared( - 'UPDATE mac_track_devices + VALUES ' . implode(', ', $sql)); + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($atEntries); + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - [$device['ips_total'], $device['device_id']] - ); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete: nb IP='.cacti_sizeof($atEntries).'.'); + mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete: nb IP=' . cacti_sizeof($atEntries) . '.'); } diff --git a/lib/mactrack_foundry.php b/lib/mactrack_foundry.php index d22376d1..086c670b 100644 --- a/lib/mactrack_foundry.php +++ b/lib/mactrack_foundry.php @@ -25,190 +25,191 @@ // register this functions scanning functions if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_foundry_switch_ports'); -function get_foundry_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; - - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; - $device['vlans_total'] = 0; - $device['ports_dual_mode'] = 0; - - // get VLAN information - $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.7.1.21', $device); - - // get VLAN Trunk status - $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.3.5.1.4', $device); - $device['vlans_total'] = cacti_sizeof($vlan_trunkstatus); - mactrack_debug('VLAN data collected. There are '.cacti_sizeof($vlan_ids).' VLANS.'); - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); - - // get the ifTypes for the device - $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); - mactrack_debug('ifTypes data collection complete.'); - - // get the ifNames for the device - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete.'); - - // get ports that happen to be link ports - $link_ports = get_link_port_status($device); - mactrack_debug('ipAddrTable scanning for link ports data collection complete.'); - - // get ports that have no vlan id (non dual-mode) - $port_dualmode = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.3.5.1.24', $device); - mactrack_debug('ifVlanId data collection complete.'); - - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; - $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); - $ifInterfaces[$ifIndex]['ifType'] = $ifTypes[$ifIndex]; - $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); - $ifInterfaces[$ifIndex]['trunkPortState'] = mactrack_arr_key($vlan_trunkstatus, $ifIndex); - $ifInterfaces[$ifIndex]['ifVlanId'] = mactrack_arr_key($port_dualmode, $ifIndex); - } - } - mactrack_debug('ifInterfaces assembly complete.'); - - // calculate the number of end user ports - if (cacti_sizeof($ifTypes)) { - foreach ($ifTypes as $ifType) { - if (($ifType >= 6) && ($ifType <= 9)) { - ++$device['ports_total']; - } - } - } - mactrack_debug('Total Ports = '.$device['ports_total']); - - // calculate the number of trunk ports - if (cacti_sizeof($ifIndexes)) { - foreach ($ifIndexes as $ifIndex) { - if ((1 == $ifInterfaces[$ifIndex]['trunkPortState']) - && (0 == $ifInterfaces[$ifIndex]['ifVlanId'])) { - ++$device['ports_trunk']; - } - } - } - mactrack_debug('Total Trunk Ports = '.$device['ports_trunk']); - - // get VLAN details - $i = 0; - if (cacti_sizeof($vlan_ids)) { - foreach ($vlan_ids as $vlan_id => $vlan_name) { - $active_vlans[$i]['vlan_id'] = $vlan_id; - $active_vlans[$i]['vlan_name'] = $vlan_name; - ++$active_vlans; - mactrack_debug('VLAN ID = '.$active_vlans[$i]['vlan_id'].' VLAN Name = '.$active_vlans[$i]['vlan_name']); - ++$i; - } - } - - if (cacti_sizeof($active_vlans)) { - // get the port status information - $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); - $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.6.1.1', $device); - - $i = 0; - $j = 0; - $port_array = []; - - if (cacti_sizeof($port_results)) { - foreach ($port_results as $port_result) { - $ifIndex = $port_result['port_number']; - $ifType = $ifTypes[$ifIndex]; - $ifName = $ifNames[$ifIndex]; - $portName = $ifName; - $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; - mactrack_debug('Port Number = '.$ifIndex.' Type = '.$ifType.' Name = '.$ifName.' Port Name = '.$portName.' Trunk Status = '.$portTrunkStatus); - - // only output legitimate end user ports - if (($ifType >= 6) && ($ifType <= 9)) { - $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); - $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_ids, $port_array[$i]['vlan_id']); - $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); - $port_array[$i]['port_name'] = $portName; - $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); - - mactrack_debug('VLAN: '.$port_array[$i]['vlan_id'].', ' - .'NAME: '.$port_array[$i]['vlan_name'].', ' - .'PORT: '.$ifIndex.', ' - .'NAME: '.$port_array[$i]['port_name'].', ' - .'MAC: '.$port_array[$i]['mac_address']); - - ++$i; - } - - ++$j; - } - - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - $ifInterfaces[$indexes[$i]]['ifType'] = mactrack_strip_alpha($ifInterfaces[$indexes[$i]]['ifType']); - - mactrack_debug($ifInterfaces[$indexes[$i]]['ifType']); - - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) - || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { - if (1 == $port_info) { - ++$device['ports_active']; - } - - ++$i; - } - } - } - - $device['ports_active'] = $device['ports_active'] - $device['ports_trunk']; - - // get IP Addresses - $gateway = cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.4.1.1991.1.1.2.1.10.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - mactrack_debug('INFO: GATEWAY: '.$gateway); - - // display completion message - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$device['ports_total'].', ACTIVE PORTS: '.$device['ports_active']); - - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($port_array); - - db_store_device_port_results($device, $port_array, $scan_date); - } - } else { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', No active devices on this network device.'); - - $device['snmp_status'] = HOST_UP; - $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; - } - - return $device; +function get_foundry_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; + + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; + $device['vlans_total'] = 0; + $device['ports_dual_mode'] = 0; + + // get VLAN information + $vlan_ids = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.7.1.21', $device); + + // get VLAN Trunk status + $vlan_trunkstatus = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.3.5.1.4', $device); + $device['vlans_total'] = cacti_sizeof($vlan_trunkstatus); + mactrack_debug('VLAN data collected. There are ' . cacti_sizeof($vlan_ids) . ' VLANS.'); + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); + + // get the ifTypes for the device + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + mactrack_debug('ifTypes data collection complete.'); + + // get the ifNames for the device + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete.'); + + // get ports that happen to be link ports + $link_ports = get_link_port_status($device); + mactrack_debug('ipAddrTable scanning for link ports data collection complete.'); + + // get ports that have no vlan id (non dual-mode) + $port_dualmode = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.3.5.1.24', $device); + mactrack_debug('ifVlanId data collection complete.'); + + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = mactrack_arr_key($ifNames, $ifIndex); + $ifInterfaces[$ifIndex]['ifType'] = $ifTypes[$ifIndex]; + $ifInterfaces[$ifIndex]['linkPort'] = mactrack_arr_key($link_ports, $ifIndex); + $ifInterfaces[$ifIndex]['trunkPortState'] = mactrack_arr_key($vlan_trunkstatus, $ifIndex); + $ifInterfaces[$ifIndex]['ifVlanId'] = mactrack_arr_key($port_dualmode, $ifIndex); + } + } + mactrack_debug('ifInterfaces assembly complete.'); + + // calculate the number of end user ports + if (cacti_sizeof($ifTypes)) { + foreach ($ifTypes as $ifType) { + if (($ifType >= 6) && ($ifType <= 9)) { + ++$device['ports_total']; + } + } + } + mactrack_debug('Total Ports = ' . $device['ports_total']); + + // calculate the number of trunk ports + if (cacti_sizeof($ifIndexes)) { + foreach ($ifIndexes as $ifIndex) { + if (($ifInterfaces[$ifIndex]['trunkPortState'] == 1) + && ($ifInterfaces[$ifIndex]['ifVlanId'] == 0)) { + ++$device['ports_trunk']; + } + } + } + mactrack_debug('Total Trunk Ports = ' . $device['ports_trunk']); + + // get VLAN details + $i = 0; + + if (cacti_sizeof($vlan_ids)) { + foreach ($vlan_ids as $vlan_id => $vlan_name) { + $active_vlans[$i]['vlan_id'] = $vlan_id; + $active_vlans[$i]['vlan_name'] = $vlan_name; + ++$active_vlans; + mactrack_debug('VLAN ID = ' . $active_vlans[$i]['vlan_id'] . ' VLAN Name = ' . $active_vlans[$i]['vlan_name']); + ++$i; + } + } + + if (cacti_sizeof($active_vlans)) { + // get the port status information + $port_results = get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', '', false); + $port_vlan_data = xform_standard_indexed_data('.1.3.6.1.4.1.1991.1.1.3.2.6.1.1', $device); + + $i = 0; + $j = 0; + $port_array = []; + + if (cacti_sizeof($port_results)) { + foreach ($port_results as $port_result) { + $ifIndex = $port_result['port_number']; + $ifType = $ifTypes[$ifIndex]; + $ifName = $ifNames[$ifIndex]; + $portName = $ifName; + $portTrunkStatus = isset($ifInterfaces[$ifIndex]['trunkPortState']) ? $ifInterfaces[$ifIndex]['trunkPortState'] : ''; + mactrack_debug('Port Number = ' . $ifIndex . ' Type = ' . $ifType . ' Name = ' . $ifName . ' Port Name = ' . $portName . ' Trunk Status = ' . $portTrunkStatus); + + // only output legitimate end user ports + if (($ifType >= 6) && ($ifType <= 9)) { + $port_array[$i]['vlan_id'] = mactrack_arr_key($port_vlan_data, $port_result['port_number']); + $port_array[$i]['vlan_name'] = mactrack_arr_key($vlan_ids, $port_array[$i]['vlan_id']); + $port_array[$i]['port_number'] = mactrack_arr_key($port_result, 'port_number'); + $port_array[$i]['port_name'] = $portName; + $port_array[$i]['mac_address'] = xform_mac_address($port_result['mac_address']); + + mactrack_debug('VLAN: ' . $port_array[$i]['vlan_id'] . ', ' + . 'NAME: ' . $port_array[$i]['vlan_name'] . ', ' + . 'PORT: ' . $ifIndex . ', ' + . 'NAME: ' . $port_array[$i]['port_name'] . ', ' + . 'MAC: ' . $port_array[$i]['mac_address']); + + ++$i; + } + + ++$j; + } + + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + $ifInterfaces[$indexes[$i]]['ifType'] = mactrack_strip_alpha($ifInterfaces[$indexes[$i]]['ifType']); + + mactrack_debug($ifInterfaces[$indexes[$i]]['ifType']); + + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { + if ($port_info == 1) { + ++$device['ports_active']; + } + + ++$i; + } + } + } + + $device['ports_active'] = $device['ports_active'] - $device['ports_trunk']; + + // get IP Addresses + $gateway = cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.4.1.1991.1.1.2.1.10.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + mactrack_debug('INFO: GATEWAY: ' . $gateway); + + // display completion message + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $device['ports_total'] . ', ACTIVE PORTS: ' . $device['ports_active']); + + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($port_array); + + db_store_device_port_results($device, $port_array, $scan_date); + } + } else { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', No active devices on this network device.'); + + $device['snmp_status'] = HOST_UP; + $device['last_runmessage'] = 'Data collection completed ok. No active devices on this network device.'; + } + + return $device; } diff --git a/lib/mactrack_functions.php b/lib/mactrack_functions.php index aefe7aa8..d8a130f9 100644 --- a/lib/mactrack_functions.php +++ b/lib/mactrack_functions.php @@ -24,118 +24,119 @@ // register these scanning functions global $mactrack_scanning_functions; + if (!isset($mactrack_scanning_functions)) { - $mactrack_scanning_functions = []; + $mactrack_scanning_functions = []; } array_push($mactrack_scanning_functions, 'get_generic_dot1q_switch_ports', 'get_generic_switch_ports', 'get_generic_wireless_ports'); global $mactrack_scanning_functions_ip; + if (!isset($mactrack_scanning_functions_ip)) { - $mactrack_scanning_functions_ip = []; + $mactrack_scanning_functions_ip = []; } array_push($mactrack_scanning_functions_ip, 'get_standard_arp_table', 'get_netscreen_arp_table'); global $mactrack_device_status; + if (!isset($mactrack_device_status)) { - $mactrack_device_status = [ - 1 => __('Idle', 'mactrack'), - 2 => __('Running', 'mactrack'), - 3 => __('No method', 'mactrack'), - 4 => __('Authentication Success', 'mactrack'), - 5 => __('Authentication Failed', 'mactrack'), - 6 => __('Authorization Success', 'mactrack'), - 7 => __('Authorization Failed', 'mactrack'), - ]; + $mactrack_device_status = [ + 1 => __('Idle', 'mactrack'), + 2 => __('Running', 'mactrack'), + 3 => __('No method', 'mactrack'), + 4 => __('Authentication Success', 'mactrack'), + 5 => __('Authentication Failed', 'mactrack'), + 6 => __('Authorization Success', 'mactrack'), + 7 => __('Authorization Failed', 'mactrack'), + ]; } -function mactrack_debug($message) -{ - global $debug, $web, $config; +function mactrack_debug($message) { + global $debug, $web, $config; + + $print_output = !(isset($web) && $web); - $print_output = !(isset($web) && $web); - if (isset($web) && $web && is_string($message) && !substr_count($message, 'SQL')) { - echo $message.'
'; - } + if (isset($web) && $web && is_string($message) && !substr_count($message, 'SQL')) { + print $message . '
'; + } - $debug_level = POLLER_VERBOSITY_HIGH; - if (substr_count($message, 'ERROR:') || $debug) { - $debug_level = POLLER_VERBOSITY_LOW; - } + $debug_level = POLLER_VERBOSITY_HIGH; - if (!preg_match('~(\w): .*~', $message)) { - $message = 'DEBUG: '.$message; - } + if (substr_count($message, 'ERROR:') || $debug) { + $debug_level = POLLER_VERBOSITY_LOW; + } - cacti_log($message, $print_output, 'MACTRACK', $debug_level); + if (!preg_match('~(\w): .*~', $message)) { + $message = 'DEBUG: ' . $message; + } + + cacti_log($message, $print_output, 'MACTRACK', $debug_level); } -function mactrack_rebuild_scanning_funcs() -{ - global $config, $mactrack_scanning_functions_ip, $mactrack_scanning_functions, $mactrack_scanning_functions_dot1x; +function mactrack_rebuild_scanning_funcs() { + global $config, $mactrack_scanning_functions_ip, $mactrack_scanning_functions, $mactrack_scanning_functions_dot1x; - if (defined('CACTI_BASE_PATH')) { - $config['base_path'] = CACTI_BASE_PATH; - } + if (defined('CACTI_BASE_PATH')) { + $config['base_path'] = CACTI_BASE_PATH; + } - db_execute('TRUNCATE TABLE mac_track_scanning_functions'); + db_execute('TRUNCATE TABLE mac_track_scanning_functions'); - include_once $config['base_path'].'/plugins/mactrack/lib/mactrack_vendors.php'; + include_once $config['base_path'] . '/plugins/mactrack/lib/mactrack_vendors.php'; - // store the list of registered mactrack scanning functions - db_execute("REPLACE INTO mac_track_scanning_functions + // store the list of registered mactrack scanning functions + db_execute("REPLACE INTO mac_track_scanning_functions (scanning_function,type) VALUES ('Not Applicable - Router', '1')"); - if (isset($mactrack_scanning_functions)) { - foreach ($mactrack_scanning_functions as $scanning_function) { - db_execute_prepared( - 'REPLACE INTO mac_track_scanning_functions + if (isset($mactrack_scanning_functions)) { + foreach ($mactrack_scanning_functions as $scanning_function) { + db_execute_prepared( + 'REPLACE INTO mac_track_scanning_functions (scanning_function, type) VALUES (?, ?)', - [$scanning_function, 1] - ); - } - } + [$scanning_function, 1] + ); + } + } - db_execute("REPLACE INTO mac_track_scanning_functions + db_execute("REPLACE INTO mac_track_scanning_functions (scanning_function,type) VALUES ('Not Applicable - Switch/Hub', '2')"); - if (isset($mactrack_scanning_functions_ip)) { - foreach ($mactrack_scanning_functions_ip as $scanning_function) { - db_execute_prepared( - 'REPLACE INTO mac_track_scanning_functions + if (isset($mactrack_scanning_functions_ip)) { + foreach ($mactrack_scanning_functions_ip as $scanning_function) { + db_execute_prepared( + 'REPLACE INTO mac_track_scanning_functions (scanning_function, type) VALUES (?, ?)', - [$scanning_function, 2] - ); - } - } + [$scanning_function, 2] + ); + } + } - db_execute("REPLACE INTO mac_track_scanning_functions + db_execute("REPLACE INTO mac_track_scanning_functions (scanning_function,type) VALUES ('Not Applicable', '3')"); - if (isset($mactrack_scanning_functions_dot1x)) { - foreach ($mactrack_scanning_functions_dot1x as $scanning_function) { - db_execute_prepared( - 'REPLACE INTO mac_track_scanning_functions + if (isset($mactrack_scanning_functions_dot1x)) { + foreach ($mactrack_scanning_functions_dot1x as $scanning_function) { + db_execute_prepared( + 'REPLACE INTO mac_track_scanning_functions (scanning_function, type) VALUES (?, ?)', - [$scanning_function, 3] - ); - } - } + [$scanning_function, 3] + ); + } + } } -function mactrack_strip_alpha($string = '') -{ - return trim($string, 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ()[]{}'); +function mactrack_strip_alpha($string = '') { + return trim($string, 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ()[]{}'); } -function mactrack_check_user_realm($realm_id) -{ - return is_realm_allowed($realm_id); +function mactrack_check_user_realm($realm_id) { + return is_realm_allowed($realm_id); } /* valid_snmp_device - This function validates that the device is reachable via snmp. @@ -143,222 +144,221 @@ function mactrack_check_user_realm($realm_id) attempts to find the correct read string and then updates several system information variable. it returns the status of the host (up=true, down=false) */ -function valid_snmp_device(&$device) -{ - global $config; - - // initialize variable - $host_up = false; - $device['snmp_status'] = HOST_DOWN; - - // force php to return numeric oid's - cacti_oid_numeric_format(); - - // if the first read did not work, loop until found - $snmp_sysObjectID = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); - - if ('' != $snmp_sysObjectID - && 'U' != $snmp_sysObjectID - && (!substr_count($snmp_sysObjectID, 'No Such Object')) - && (!substr_count($snmp_sysObjectID, 'Error In'))) { - $snmp_sysObjectID = trim(str_replace('"', '', $snmp_sysObjectID)); - $host_up = true; - $device['snmp_status'] = HOST_UP; - } else { - // loop through the default and then other common for the correct answer - $snmp_options = db_fetch_assoc_prepared('SELECT * from mac_track_snmp_items WHERE snmp_id = ? ORDER BY sequence', [$device['snmp_options']]); - - if (cacti_sizeof($snmp_options)) { - foreach ($snmp_options as $snmp_option) { - // update $device for later db update via db_update_device_status - $device['snmp_readstring'] = $snmp_option['snmp_readstring']; - $device['snmp_version'] = $snmp_option['snmp_version']; - $device['snmp_username'] = $snmp_option['snmp_username']; - $device['snmp_password'] = $snmp_option['snmp_password']; - $device['snmp_auth_protocol'] = $snmp_option['snmp_auth_protocol']; - $device['snmp_priv_passphrase'] = $snmp_option['snmp_priv_passphrase']; - $device['snmp_priv_protocol'] = $snmp_option['snmp_priv_protocol']; - $device['snmp_context'] = $snmp_option['snmp_context']; - $device['snmp_port'] = $snmp_option['snmp_port']; - $device['snmp_timeout'] = $snmp_option['snmp_timeout']; - $device['snmp_retries'] = $snmp_option['snmp_retries']; - - $snmp_sysObjectID = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.2.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); - $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); - - if ('' != $snmp_sysObjectID - && 'U' != $snmp_sysObjectID - && (!substr_count($snmp_sysObjectID, 'No Such Object')) - && (!substr_count($snmp_sysObjectID, 'Error In'))) { - $snmp_sysObjectID = trim(str_replace("'", '', $snmp_sysObjectID)); - $device['snmp_readstring'] = $snmp_option['snmp_readstring']; - $device['snmp_status'] = HOST_UP; - $host_up = true; - // update cacti device, if required - sync_mactrack_to_cacti($device); - // update to mactrack itself is done by db_update_device_status in mactrack_scanner.php - // TODO: if db_update_device_status would use api_mactrack_device_save, there would be no need to call sync_mactrack_to_cacti here - // but currently the parameter set doesn't match - mactrack_debug('Result found on Option Set ('.$snmp_option['snmp_id'].') Sequence ('.$snmp_option['sequence'].'): '.$snmp_sysObjectID); - - break; // no need to continue if we have a match - } - $device['snmp_status'] = HOST_DOWN; - $host_up = false; - } - } - } - - if ($host_up) { - $device['snmp_sysObjectID'] = $snmp_sysObjectID; - - // get system name - $snmp_sysName = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.5.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $snmp_sysName) { - $snmp_sysName = trim(strtr($snmp_sysName, '"', ' ')); - $device['snmp_sysName'] = $snmp_sysName; - } - - // get system location - $snmp_sysLocation = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.6.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $snmp_sysLocation) { - $snmp_sysLocation = trim(strtr($snmp_sysLocation, '"', ' ')); - $device['snmp_sysLocation'] = $snmp_sysLocation; - } - - // get system contact - $snmp_sysContact = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.4.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $snmp_sysContact) { - $snmp_sysContact = trim(strtr($snmp_sysContact, '"', ' ')); - $device['snmp_sysContact'] = $snmp_sysContact; - } - - // get system description - $snmp_sysDescr = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.1.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $snmp_sysDescr) { - $snmp_sysDescr = trim(strtr($snmp_sysDescr, '"', ' ')); - $device['snmp_sysDescr'] = $snmp_sysDescr; - } - - // get system uptime - $snmp_sysUptime = @cacti_snmp_get( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.1.3.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - if ('' != $snmp_sysUptime) { - $snmp_sysUptime = trim(strtr($snmp_sysUptime, '"', ' ')); - $device['snmp_sysUptime'] = $snmp_sysUptime; - } - } - - return $host_up; +function valid_snmp_device(&$device) { + global $config; + + // initialize variable + $host_up = false; + $device['snmp_status'] = HOST_DOWN; + + // force php to return numeric oid's + cacti_oid_numeric_format(); + + // if the first read did not work, loop until found + $snmp_sysObjectID = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); + + if ($snmp_sysObjectID != '' + && $snmp_sysObjectID != 'U' + && (!substr_count($snmp_sysObjectID, 'No Such Object')) + && (!substr_count($snmp_sysObjectID, 'Error In'))) { + $snmp_sysObjectID = trim(str_replace('"', '', $snmp_sysObjectID)); + $host_up = true; + $device['snmp_status'] = HOST_UP; + } else { + // loop through the default and then other common for the correct answer + $snmp_options = db_fetch_assoc_prepared('SELECT * from mac_track_snmp_items WHERE snmp_id = ? ORDER BY sequence', [$device['snmp_options']]); + + if (cacti_sizeof($snmp_options)) { + foreach ($snmp_options as $snmp_option) { + // update $device for later db update via db_update_device_status + $device['snmp_readstring'] = $snmp_option['snmp_readstring']; + $device['snmp_version'] = $snmp_option['snmp_version']; + $device['snmp_username'] = $snmp_option['snmp_username']; + $device['snmp_password'] = $snmp_option['snmp_password']; + $device['snmp_auth_protocol'] = $snmp_option['snmp_auth_protocol']; + $device['snmp_priv_passphrase'] = $snmp_option['snmp_priv_passphrase']; + $device['snmp_priv_protocol'] = $snmp_option['snmp_priv_protocol']; + $device['snmp_context'] = $snmp_option['snmp_context']; + $device['snmp_port'] = $snmp_option['snmp_port']; + $device['snmp_timeout'] = $snmp_option['snmp_timeout']; + $device['snmp_retries'] = $snmp_option['snmp_retries']; + + $snmp_sysObjectID = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.2.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + $snmp_sysObjectID = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('OID: ', '', $snmp_sysObjectID); + $snmp_sysObjectID = str_replace('.iso', '.1', $snmp_sysObjectID); + + if ($snmp_sysObjectID != '' + && $snmp_sysObjectID != 'U' + && (!substr_count($snmp_sysObjectID, 'No Such Object')) + && (!substr_count($snmp_sysObjectID, 'Error In'))) { + $snmp_sysObjectID = trim(str_replace("'", '', $snmp_sysObjectID)); + $device['snmp_readstring'] = $snmp_option['snmp_readstring']; + $device['snmp_status'] = HOST_UP; + $host_up = true; + // update cacti device, if required + sync_mactrack_to_cacti($device); + // update to mactrack itself is done by db_update_device_status in mactrack_scanner.php + // TODO: if db_update_device_status would use api_mactrack_device_save, there would be no need to call sync_mactrack_to_cacti here + // but currently the parameter set doesn't match + mactrack_debug('Result found on Option Set (' . $snmp_option['snmp_id'] . ') Sequence (' . $snmp_option['sequence'] . '): ' . $snmp_sysObjectID); + + break; // no need to continue if we have a match + } + $device['snmp_status'] = HOST_DOWN; + $host_up = false; + } + } + } + + if ($host_up) { + $device['snmp_sysObjectID'] = $snmp_sysObjectID; + + // get system name + $snmp_sysName = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.5.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($snmp_sysName != '') { + $snmp_sysName = trim(strtr($snmp_sysName, '"', ' ')); + $device['snmp_sysName'] = $snmp_sysName; + } + + // get system location + $snmp_sysLocation = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.6.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($snmp_sysLocation != '') { + $snmp_sysLocation = trim(strtr($snmp_sysLocation, '"', ' ')); + $device['snmp_sysLocation'] = $snmp_sysLocation; + } + + // get system contact + $snmp_sysContact = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.4.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($snmp_sysContact != '') { + $snmp_sysContact = trim(strtr($snmp_sysContact, '"', ' ')); + $device['snmp_sysContact'] = $snmp_sysContact; + } + + // get system description + $snmp_sysDescr = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.1.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($snmp_sysDescr != '') { + $snmp_sysDescr = trim(strtr($snmp_sysDescr, '"', ' ')); + $device['snmp_sysDescr'] = $snmp_sysDescr; + } + + // get system uptime + $snmp_sysUptime = @cacti_snmp_get( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.1.3.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + if ($snmp_sysUptime != '') { + $snmp_sysUptime = trim(strtr($snmp_sysUptime, '"', ' ')); + $device['snmp_sysUptime'] = $snmp_sysUptime; + } + } + + return $host_up; } /** @@ -369,79 +369,80 @@ function valid_snmp_device(&$device) * @param mixed $device * @param mixed $device_types */ -function find_scanning_function(&$device, &$device_types) -{ - // scan all device_types to determine the function to call - if (cacti_sizeof($device_types)) { - foreach ($device_types as $device_type) { - // by default none match - $sysDescr_match = false; - $sysObjectID_match = false; - - // search for a matching snmp_sysDescr - if (substr_count($device_type['sysDescr_match'], '*') > 0) { - // need to assume mixed string - $parts = explode('*', $device_type['sysDescr_match']); - if (cacti_sizeof($parts)) { - foreach ($parts as $part) { - if ('' != $part) { - if (substr_count($device['snmp_sysDescr'], $part) > 0) { - $sysDescr_match = true; - } else { - $sysDescr_match = false; - } - } - } - } - } else { - if ('' == $device_type['sysDescr_match']) { - $sysDescr_match = true; - } else { - if (substr_count($device['snmp_sysDescr'], $device_type['sysDescr_match'])) { - $sysDescr_match = true; - } else { - $sysDescr_match = false; - } - } - } - - // search for a matching snmp_sysObjectID - // need to assume mixed string - if (substr_count($device_type['sysObjectID_match'], '*') > 0) { - $parts = explode('*', $device_type['sysObjectID_match']); - if (cacti_sizeof($parts)) { - foreach ($parts as $part) { - if ('' != $part) { - if (substr_count($device['snmp_sysObjectID'], $part) > 0) { - $sysObjectID_match = true; - } else { - $sysObjectID_match = false; - } - } - } - } - } else { - if ('' == $device_type['sysObjectID_match']) { - $sysObjectID_match = true; - } else { - if (substr_count($device['snmp_sysObjectID'], $device_type['sysObjectID_match'])) { - $sysObjectID_match = true; - } else { - $sysObjectID_match = false; - } - } - } - - if ((true == $sysObjectID_match) && (true == $sysDescr_match)) { - $device['device_type_id'] = $device_type['device_type_id']; - $device['scan_type'] = $device_type['device_type']; - - return $device_type; - } - } - } - - return []; +function find_scanning_function(&$device, &$device_types) { + // scan all device_types to determine the function to call + if (cacti_sizeof($device_types)) { + foreach ($device_types as $device_type) { + // by default none match + $sysDescr_match = false; + $sysObjectID_match = false; + + // search for a matching snmp_sysDescr + if (substr_count($device_type['sysDescr_match'], '*') > 0) { + // need to assume mixed string + $parts = explode('*', $device_type['sysDescr_match']); + + if (cacti_sizeof($parts)) { + foreach ($parts as $part) { + if ($part != '') { + if (substr_count($device['snmp_sysDescr'], $part) > 0) { + $sysDescr_match = true; + } else { + $sysDescr_match = false; + } + } + } + } + } else { + if ($device_type['sysDescr_match'] == '') { + $sysDescr_match = true; + } else { + if (substr_count($device['snmp_sysDescr'], $device_type['sysDescr_match'])) { + $sysDescr_match = true; + } else { + $sysDescr_match = false; + } + } + } + + // search for a matching snmp_sysObjectID + // need to assume mixed string + if (substr_count($device_type['sysObjectID_match'], '*') > 0) { + $parts = explode('*', $device_type['sysObjectID_match']); + + if (cacti_sizeof($parts)) { + foreach ($parts as $part) { + if ($part != '') { + if (substr_count($device['snmp_sysObjectID'], $part) > 0) { + $sysObjectID_match = true; + } else { + $sysObjectID_match = false; + } + } + } + } + } else { + if ($device_type['sysObjectID_match'] == '') { + $sysObjectID_match = true; + } else { + if (substr_count($device['snmp_sysObjectID'], $device_type['sysObjectID_match'])) { + $sysObjectID_match = true; + } else { + $sysObjectID_match = false; + } + } + } + + if (($sysObjectID_match == true) && ($sysDescr_match == true)) { + $device['device_type_id'] = $device_type['device_type_id']; + $device['scan_type'] = $device_type['device_type']; + + return $device_type; + } + } + } + + return []; } /** @@ -451,36 +452,35 @@ function find_scanning_function(&$device, &$device_types) * @param mixed $port_list * @param mixed $delimiter */ -function port_list_to_array($port_list, $delimiter = ':') -{ - $port_array = []; - - if ('-1' == read_config_option('mt_ignorePorts_delim')) { - // find the delimiter - $t1 = cacti_sizeof(explode(':', $port_list)); - $t2 = cacti_sizeof(explode('|', $port_list)); - $t3 = cacti_sizeof(explode(' ', $port_list)); - - if ($t1 > $t2 && $t1 > $t3) { - $delimiter = ':'; - } elseif ($t2 > $t1 && $t2 > $t3) { - $delimiter = '|'; - } elseif ($t3 > $t1 && $t3 > $t2) { - $delimiter = ' '; - } - } else { - $delimiter = read_config_option('mt_ignorePorts_delim'); - } - - $ports = explode($delimiter, $port_list); - - if (cacti_sizeof($ports)) { - foreach ($ports as $port) { - array_push($port_array, trim($port)); - } - } - - return $port_array; +function port_list_to_array($port_list, $delimiter = ':') { + $port_array = []; + + if (read_config_option('mt_ignorePorts_delim') == '-1') { + // find the delimiter + $t1 = cacti_sizeof(explode(':', $port_list)); + $t2 = cacti_sizeof(explode('|', $port_list)); + $t3 = cacti_sizeof(explode(' ', $port_list)); + + if ($t1 > $t2 && $t1 > $t3) { + $delimiter = ':'; + } elseif ($t2 > $t1 && $t2 > $t3) { + $delimiter = '|'; + } elseif ($t3 > $t1 && $t3 > $t2) { + $delimiter = ' '; + } + } else { + $delimiter = read_config_option('mt_ignorePorts_delim'); + } + + $ports = explode($delimiter, $port_list); + + if (cacti_sizeof($ports)) { + foreach ($ports as $port) { + array_push($port_array, trim($port)); + } + } + + return $port_array; } /** @@ -490,94 +490,96 @@ function port_list_to_array($port_list, $delimiter = ':') * @param mixed $site * @param mixed $device */ -function get_standard_arp_table($site, &$device) -{ - global $debug, $scan_date; - - $atEntries = []; - - // get the atifIndexes for the device - $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); - if (cacti_sizeof($atifIndexes)) { - mactrack_debug('atifIndexes data collection complete'); - $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device); - mactrack_debug('atPhysAddress data collection complete'); - $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device); - mactrack_debug('atNetAddress data collection complete'); - } else { - // second attempt for Force10 Gear - $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.1', $device); - mactrack_debug('atifIndexes data collection complete'); - $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.2', $device, '', true); - mactrack_debug('atPhysAddress data collection complete'); - $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.3', $device); - mactrack_debug('atNetAddress data collection complete'); - } - - $atifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete. \''.cacti_sizeof($atifNames).'\' rows found!'); - - // convert the mac address if necessary - $keys = array_keys($atPhysAddress); - $i = 0; - if (cacti_sizeof($atPhysAddress)) { - foreach ($atPhysAddress as $atAddress) { - $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); - ++$i; - } - } - mactrack_debug('atPhysAddress MAC Address Conversion Completed'); - - // get the ifNames for the device - $keys = array_keys($atifIndexes); - $i = 0; - if (cacti_sizeof($atifIndexes)) { - foreach ($atifIndexes as $atifIndex) { - $atEntries[$i]['atifName'] = isset($atifNames[$atifIndex]) ? $atifNames[$atifIndex] : ''; - $atEntries[$i]['atPhysAddress'] = isset($atPhysAddress[$keys[$i]]) ? $atPhysAddress[$keys[$i]] : ''; - $atEntries[$i]['atNetAddress'] = isset($atNetAddress[$keys[$i]]) ? xform_net_address($atNetAddress[$keys[$i]]) : ''; - ++$i; - } - } - mactrack_debug('atEntries assembly complete.'); - - // output details to database - if (cacti_sizeof($atEntries)) { - foreach ($atEntries as $atEntry) { - // check the mac_track_arp table if no IP address is found - if ('' == $atEntry['atNetAddress']) { - $atEntry['atNetAddress'] = db_check_for_ip($atEntry['atPhysAddress']); - mactrack_debug('atNetAddress ****:'.$atEntry['atPhysAddress'].'('.$atEntry['atNetAddress'].')'); - } - - db_execute_prepared( - 'REPLACE INTO mac_track_ips +function get_standard_arp_table($site, &$device) { + global $debug, $scan_date; + + $atEntries = []; + + // get the atifIndexes for the device + $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.1', $device); + + if (cacti_sizeof($atifIndexes)) { + mactrack_debug('atifIndexes data collection complete'); + $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.2', $device); + mactrack_debug('atPhysAddress data collection complete'); + $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.3.1.1.3', $device); + mactrack_debug('atNetAddress data collection complete'); + } else { + // second attempt for Force10 Gear + $atifIndexes = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.1', $device); + mactrack_debug('atifIndexes data collection complete'); + $atPhysAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.2', $device, '', true); + mactrack_debug('atPhysAddress data collection complete'); + $atNetAddress = xform_stripped_oid('.1.3.6.1.2.1.4.22.1.3', $device); + mactrack_debug('atNetAddress data collection complete'); + } + + $atifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete. \'' . cacti_sizeof($atifNames) . '\' rows found!'); + + // convert the mac address if necessary + $keys = array_keys($atPhysAddress); + $i = 0; + + if (cacti_sizeof($atPhysAddress)) { + foreach ($atPhysAddress as $atAddress) { + $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); + ++$i; + } + } + mactrack_debug('atPhysAddress MAC Address Conversion Completed'); + + // get the ifNames for the device + $keys = array_keys($atifIndexes); + $i = 0; + + if (cacti_sizeof($atifIndexes)) { + foreach ($atifIndexes as $atifIndex) { + $atEntries[$i]['atifName'] = isset($atifNames[$atifIndex]) ? $atifNames[$atifIndex] : ''; + $atEntries[$i]['atPhysAddress'] = isset($atPhysAddress[$keys[$i]]) ? $atPhysAddress[$keys[$i]] : ''; + $atEntries[$i]['atNetAddress'] = isset($atNetAddress[$keys[$i]]) ? xform_net_address($atNetAddress[$keys[$i]]) : ''; + ++$i; + } + } + mactrack_debug('atEntries assembly complete.'); + + // output details to database + if (cacti_sizeof($atEntries)) { + foreach ($atEntries as $atEntry) { + // check the mac_track_arp table if no IP address is found + if ($atEntry['atNetAddress'] == '') { + $atEntry['atNetAddress'] = db_check_for_ip($atEntry['atPhysAddress']); + mactrack_debug('atNetAddress ****:' . $atEntry['atPhysAddress'] . '(' . $atEntry['atNetAddress'] . ')'); + } + + db_execute_prepared( + 'REPLACE INTO mac_track_ips (site_id, device_id, hostname, device_name, port_number, mac_address, ip_address, scan_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - [ - $device['site_id'], - $device['device_id'], - $device['hostname'], - $device['device_name'], - $atEntry['atifName'], - $atEntry['atPhysAddress'], - $atEntry['atNetAddress'], - $scan_date, - ] - ); - } - } - - // save ip information for the device - $device['ips_total'] = cacti_sizeof($atEntries); - db_execute_prepared( - 'UPDATE mac_track_devices + [ + $device['site_id'], + $device['device_id'], + $device['hostname'], + $device['device_name'], + $atEntry['atifName'], + $atEntry['atPhysAddress'], + $atEntry['atNetAddress'], + $scan_date, + ] + ); + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($atEntries); + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - [$device['ips_total'], $device['device_id']] - ); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug('HOST: '.$device['hostname'].', IP address information collection complete'); + mactrack_debug('HOST: ' . $device['hostname'] . ', IP address information collection complete'); } /** @@ -590,64 +592,65 @@ function get_standard_arp_table($site, &$device) * @param mixed $getLinkPorts * @param mixed $getAlias */ -function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $getAlias = false) -{ - // initialize the interfaces array - $ifInterfaces = []; - - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete. \''.cacti_sizeof($ifIndexes).'\' rows found!'); - - $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); - if (cacti_sizeof($ifTypes)) { - foreach ($ifTypes as $key => $value) { - if (!is_numeric($value)) { - $parts = explode('(', $value); - if (!empty($parts)) { - $piece = $parts[1]; - $ifTypes[$key] = str_replace(')', '', trim($piece)); - } else { - $ifTypes[$key] = 'N/A'; - } - } - } - } - mactrack_debug('ifTypes data collection complete. \''.cacti_sizeof($ifTypes).'\' rows found!'); - - $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); - mactrack_debug('ifNames data collection complete. \''.cacti_sizeof($ifNames).'\' rows found!'); - - // get ports names through use of ifAlias - if ($getAlias) { - $ifAliases = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); - mactrack_debug('ifAlias data collection complete. \''.cacti_sizeof($ifAliases).'\' rows found!'); - } - - // get ports that happen to be link ports - if ($getLinkPorts) { - $link_ports = get_link_port_status($device); - mactrack_debug("ipAddrTable scanning for link ports data collection complete. '".cacti_sizeof($link_ports)."' rows found!"); - } - - // required only for interfaces table - $db_data = db_fetch_assoc("SELECT * FROM mac_track_interfaces WHERE device_id='".$device['device_id']."' ORDER BY ifIndex"); - - if (cacti_sizeof($db_data)) { - foreach ($db_data as $interface) { - $db_interface[$interface['ifIndex']] = $interface; - } - } - - // mark all interfaces as not present - db_execute_prepared( - 'UPDATE mac_track_interfaces +function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $getAlias = false) { + // initialize the interfaces array + $ifInterfaces = []; + + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete. \'' . cacti_sizeof($ifIndexes) . '\' rows found!'); + + $ifTypes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.3', $device); + + if (cacti_sizeof($ifTypes)) { + foreach ($ifTypes as $key => $value) { + if (!is_numeric($value)) { + $parts = explode('(', $value); + + if (!empty($parts)) { + $piece = $parts[1]; + $ifTypes[$key] = str_replace(')', '', trim($piece)); + } else { + $ifTypes[$key] = 'N/A'; + } + } + } + } + mactrack_debug('ifTypes data collection complete. \'' . cacti_sizeof($ifTypes) . '\' rows found!'); + + $ifNames = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.1', $device); + mactrack_debug('ifNames data collection complete. \'' . cacti_sizeof($ifNames) . '\' rows found!'); + + // get ports names through use of ifAlias + if ($getAlias) { + $ifAliases = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.18', $device); + mactrack_debug('ifAlias data collection complete. \'' . cacti_sizeof($ifAliases) . '\' rows found!'); + } + + // get ports that happen to be link ports + if ($getLinkPorts) { + $link_ports = get_link_port_status($device); + mactrack_debug("ipAddrTable scanning for link ports data collection complete. '" . cacti_sizeof($link_ports) . "' rows found!"); + } + + // required only for interfaces table + $db_data = db_fetch_assoc("SELECT * FROM mac_track_interfaces WHERE device_id='" . $device['device_id'] . "' ORDER BY ifIndex"); + + if (cacti_sizeof($db_data)) { + foreach ($db_data as $interface) { + $db_interface[$interface['ifIndex']] = $interface; + } + } + + // mark all interfaces as not present + db_execute_prepared( + 'UPDATE mac_track_interfaces SET present=0 WHERE device_id= ?', - [$device['device_id']] - ); + [$device['device_id']] + ); - $insert_prefix = 'INSERT INTO mac_track_interfaces (site_id, device_id, sysUptime, + $insert_prefix = 'INSERT INTO mac_track_interfaces (site_id, device_id, sysUptime, ifIndex, ifType, ifName, ifAlias, linkPort, vlan_id, vlan_name, vlan_trunk_status, ifSpeed, ifHighSpeed, ifDuplex, ifDescr, ifMtu, ifPhysAddress, ifAdminStatus, ifOperStatus, ifLastChange, @@ -661,7 +664,7 @@ function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $ge int_discards_present, int_errors_present, last_down_time, last_up_time, stateChanges, present) VALUES '; - $insert_suffix = ' ON DUPLICATE KEY UPDATE + $insert_suffix = ' ON DUPLICATE KEY UPDATE sysUptime=VALUES(sysUptime), ifType=VALUES(ifType), ifName=VALUES(ifName), @@ -716,394 +719,395 @@ function build_InterfacesTable(&$device, &$ifIndexes, $getLinkPorts = false, $ge stateChanges=VALUES(stateChanges), present="1"'; - $insert_vals = ''; + $insert_vals = ''; + + $ifSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.5', $device); + mactrack_debug("ifSpeed data collection complete. '" . cacti_sizeof($ifSpeed) . "' rows found!"); - $ifSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.5', $device); - mactrack_debug("ifSpeed data collection complete. '".cacti_sizeof($ifSpeed)."' rows found!"); + $ifHighSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.15', $device); + mactrack_debug("ifHighSpeed data collection complete. '" . cacti_sizeof($ifHighSpeed) . "' rows found!"); - $ifHighSpeed = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.15', $device); - mactrack_debug("ifHighSpeed data collection complete. '".cacti_sizeof($ifHighSpeed)."' rows found!"); + $ifDuplex = xform_standard_indexed_data('.1.3.6.1.2.1.10.7.2.1.19', $device); + mactrack_debug("ifDuplex data collection complete. '" . cacti_sizeof($ifDuplex) . "' rows found!"); - $ifDuplex = xform_standard_indexed_data('.1.3.6.1.2.1.10.7.2.1.19', $device); - mactrack_debug("ifDuplex data collection complete. '".cacti_sizeof($ifDuplex)."' rows found!"); + $ifDescr = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); + mactrack_debug("ifDescr data collection complete. '" . cacti_sizeof($ifDescr) . "' rows found!"); - $ifDescr = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.2', $device); - mactrack_debug("ifDescr data collection complete. '".cacti_sizeof($ifDescr)."' rows found!"); + $ifMtu = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.4', $device); + mactrack_debug("ifMtu data collection complete. '" . cacti_sizeof($ifMtu) . "' rows found!"); - $ifMtu = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.4', $device); - mactrack_debug("ifMtu data collection complete. '".cacti_sizeof($ifMtu)."' rows found!"); + $ifPhysAddress = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.6', $device, '', true); + mactrack_debug("ifPhysAddress data collection complete. '" . cacti_sizeof($ifPhysAddress) . "' rows found!"); - $ifPhysAddress = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.6', $device, '', true); - mactrack_debug("ifPhysAddress data collection complete. '".cacti_sizeof($ifPhysAddress)."' rows found!"); + $ifAdminStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.7', $device); - $ifAdminStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.7', $device); - if (cacti_sizeof($ifAdminStatus)) { - foreach ($ifAdminStatus as $key => $value) { - if (substr_count(strtolower($value), 'up') || ('1' == $value)) { - $ifAdminStatus[$key] = 1; - } else { - $ifAdminStatus[$key] = 0; - } - } - } - mactrack_debug("ifAdminStatus data collection complete. '".cacti_sizeof($ifAdminStatus)."' rows found!"); - - $ifOperStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - if (cacti_sizeof($ifOperStatus)) { - foreach ($ifOperStatus as $key => $value) { - if (substr_count(strtolower($value), 'up') || ('1' == $value)) { - $ifOperStatus[$key] = 1; - } else { - $ifOperStatus[$key] = 0; - } - } - } - mactrack_debug("ifOperStatus data collection complete. '".cacti_sizeof($ifOperStatus)."' rows found!"); - - $ifLastChange = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.9', $device); - mactrack_debug("ifLastChange data collection complete. '".cacti_sizeof($ifLastChange)."' rows found!"); - - // get timing for rate information - $prev_octets_time = strtotime($device['last_rundate']); - $cur_octets_time = time(); - - if (0 == $prev_octets_time) { - $divisor = false; - } else { - $divisor = $cur_octets_time - $prev_octets_time; - } - - // if the device is snmpv2 use high speed and don't bother with the low speed stuff - $ifInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.10', $device); - mactrack_debug("ifInOctets data collection complete. '".cacti_sizeof($ifInOctets)."' rows found!"); - - $ifOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.16', $device); - mactrack_debug("ifOutOctets data collection complete. '".cacti_sizeof($ifOutOctets)."' rows found!"); - - if ($device['snmp_version'] > 1) { - $ifHCInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.6', $device); - mactrack_debug("ifHCInOctets data collection complete. '".cacti_sizeof($ifHCInOctets)."' rows found!"); - - $ifHCOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.10', $device); - mactrack_debug("ifHCOutOctets data collection complete. '".cacti_sizeof($ifHCOutOctets)."' rows found!"); - } - - $ifInMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.2', $device); - mactrack_debug("ifInMulticastPkts data collection complete. '".cacti_sizeof($ifInMulticastPkts)."' rows found!"); - - $ifOutMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.4', $device); - mactrack_debug("ifOutMulticastPkts data collection complete. '".cacti_sizeof($ifOutMulticastPkts)."' rows found!"); - - $ifInBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.3', $device); - mactrack_debug("ifInBroadcastPkts data collection complete. '".cacti_sizeof($ifInBroadcastPkts)."' rows found!"); - - $ifOutBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.5', $device); - mactrack_debug("ifOutBroadcastPkts data collection complete. '".cacti_sizeof($ifOutBroadcastPkts)."' rows found!"); - - $ifInUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.11', $device); - mactrack_debug("ifInUcastPkts data collection complete. '".cacti_sizeof($ifInUcastPkts)."' rows found!"); - - $ifOutUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.17', $device); - mactrack_debug("ifOutUcastPkts data collection complete. '".cacti_sizeof($ifOutUcastPkts)."' rows found!"); - - // get information on error conditions - $ifInDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.13', $device); - mactrack_debug("ifInDiscards data collection complete. '".cacti_sizeof($ifInDiscards)."' rows found!"); - - $ifInErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.14', $device); - mactrack_debug("ifInErrors data collection complete. '".cacti_sizeof($ifInErrors)."' rows found!"); - - $ifInUnknownProtos = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.15', $device); - mactrack_debug("ifInUnknownProtos data collection complete. '".cacti_sizeof($ifInUnknownProtos)."' rows found!"); - - $ifOutDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.19', $device); - mactrack_debug("ifOutDiscards data collection complete. '".cacti_sizeof($ifOutDiscards)."' rows found!"); - - $ifOutErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.20', $device); - mactrack_debug("ifOutErrors data collection complete. '".cacti_sizeof($ifOutErrors)."' rows found!"); - - $vlan_id = ''; - $vlan_name = ''; - $vlan_trunk = ''; - - $i = 0; - foreach ($ifIndexes as $ifIndex) { - $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; - $ifInterfaces[$ifIndex]['ifName'] = (isset($ifNames[$ifIndex]) ? $ifNames[$ifIndex] : ''); - $ifInterfaces[$ifIndex]['ifType'] = (isset($ifTypes[$ifIndex]) ? $ifTypes[$ifIndex] : ''); - - if ($getLinkPorts) { - $ifInterfaces[$ifIndex]['linkPort'] = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); - $linkPort = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); - } else { - $linkPort = 0; - } - - if ($getAlias && cacti_sizeof($ifAliases)) { - $ifInterfaces[$ifIndex]['ifAlias'] = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); - $ifAlias = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); - } else { - $ifAlias = ''; - } - - // update the last up/down status - if (!isset($db_interface[$ifIndex])) { - if (isset($ifOperStatus[$ifIndex]) && 1 == $ifOperStatus[$ifIndex]) { - $last_up_time = date('Y-m-d H:i:s'); - $stateChanges = 0; - $last_down_time = 0; - } else { - $stateChanges = 0; - $last_up_time = 0; - $last_down_time = date('Y-m-d H:i:s'); - } - } else { - $last_up_time = $db_interface[$ifIndex]['last_up_time']; - $last_down_time = $db_interface[$ifIndex]['last_down_time']; - $stateChanges = $db_interface[$ifIndex]['stateChanges']; - - if (0 == $db_interface[$ifIndex]['ifOperStatus']) { // interface previously not up - if (isset($ifOperStatus[$ifIndex]) && 1 == $ifOperStatus[$ifIndex]) { - // the interface just went up, mark the time - $last_up_time = date('Y-m-d H:i:s'); - ++$stateChanges; - - // if the interface has never been marked down before, make it the current time - if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_down_time']) { - $last_down_time = $last_up_time; - } - } else { - // if the interface has never been down, make the current time - $last_down_time = date('Y-m-d H:i:s'); - - // if the interface stayed down, set the last up time if not set before - if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_up_time']) { - $last_up_time = date('Y-m-d H:i:s'); - } - } - } else { - if (isset($ifOperStatus[$ifIndex]) && 0 == $ifOperStatus[$ifIndex]) { - // the interface just went down, mark the time - $last_down_time = date('Y-m-d H:i:s'); - ++$stateChanges; - - // if the interface has never been up before, mark it the current time - if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_up_time']) { - $last_up_time = date('Y-m-d H:i:s'); - } - } else { - $last_up_time = date('Y-m-d H:i:s'); - - if ('0000-00-00 00:00:00' == $db_interface[$ifIndex]['last_down_time']) { - $last_down_time = date('Y-m-d H:i:s'); - } - } - } - } - - // do the in octets - $int_ifInOctets = get_link_int_value('ifInOctets', $ifIndex, $ifInOctets, $db_interface, $divisor, 'traffic'); - - // do the out octets - $int_ifOutOctets = get_link_int_value('ifOutOctets', $ifIndex, $ifOutOctets, $db_interface, $divisor, 'traffic'); - - if ($device['snmp_version'] > 1) { - // do the in octets - $int_ifHCInOctets = get_link_int_value('ifHCInOctets', $ifIndex, $ifHCInOctets, $db_interface, $divisor, 'traffic', '64'); - - // do the out octets - $int_ifHCOutOctets = get_link_int_value('ifHCOutOctets', $ifIndex, $ifHCOutOctets, $db_interface, $divisor, 'traffic', '64'); - } - - // accommodate values in high speed octets for interfaces that don't support 64 bit - if (isset($ifInOctets[$ifIndex])) { - if (!isset($ifHCInOctets[$ifIndex])) { - $ifHCInOctets[$ifIndex] = isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : ''; - $int_ifHCInOctets = $int_ifInOctets; - } - } - - if (isset($ifOutOctets[$ifIndex])) { - if (!isset($ifHCOutOctets[$ifIndex])) { - $ifHCOutOctets[$ifIndex] = isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : ''; - $int_ifHCOutOctets = $int_ifOutOctets; - } - } - - $int_ifInMulticastPkts = get_link_int_value('ifInMulticastPkts', $ifIndex, $ifInMulticastPkts, $db_interface, $divisor, 'traffic'); - $int_ifOutMulticastPkts = get_link_int_value('ifOutMulticastPkts', $ifIndex, $ifOutMulticastPkts, $db_interface, $divisor, 'traffic'); - $int_ifInBroadcastPkts = get_link_int_value('ifInBroadcastPkts', $ifIndex, $ifInBroadcastPkts, $db_interface, $divisor, 'traffic'); - $int_ifOutBroadcastPkts = get_link_int_value('ifOutBroadcastPkts', $ifIndex, $ifOutBroadcastPkts, $db_interface, $divisor, 'traffic'); - $int_ifInUcastPkts = get_link_int_value('ifInUcastPkts', $ifIndex, $ifInUcastPkts, $db_interface, $divisor, 'traffic'); - $int_ifOutUcastPkts = get_link_int_value('ifOutUcastPkts', $ifIndex, $ifOutUcastPkts, $db_interface, $divisor, 'traffic'); - - // see if in error's have been increasing - $int_ifInErrors = get_link_int_value('ifInErrors', $ifIndex, $ifInErrors, $db_interface, $divisor, 'errors'); - - // see if out error's have been increasing - $int_ifOutErrors = get_link_int_value('ifOutErrors', $ifIndex, $ifOutErrors, $db_interface, $divisor, 'errors'); - - if ($int_ifInErrors > 0 || $int_ifOutErrors > 0) { - $int_errors_present = true; - } else { - $int_errors_present = false; - } - - // see if in discards's have been increasing - $int_ifInDiscards = get_link_int_value('ifInDiscards', $ifIndex, $ifInDiscards, $db_interface, $divisor, 'errors'); - - // see if out discards's have been increasing - $int_ifOutDiscards = get_link_int_value('ifOutDiscards', $ifIndex, $ifOutDiscards, $db_interface, $divisor, 'errors'); - - if ($int_ifInDiscards > 0 || $int_ifOutDiscards > 0) { - $int_discards_present = true; - } else { - $int_discards_present = false; - } - - // see if in discards's have been increasing - $int_ifInUnknownProtos = get_link_int_value('ifInUnknownProtos', $ifIndex, $ifInUnknownProtos, $db_interface, $divisor, 'errors'); - - // format the update packet - if (0 == $i) { - $insert_vals .= ' '; - } else { - $insert_vals .= ','; - } - - if (isset($ifTypes[$ifIndex])) { - $type = $ifTypes[$ifIndex]; - } else { - $type = 'Undefined'; - } - - if (isset($ifNames[$ifIndex])) { - $name = $ifNames[$ifIndex]; - } else { - $name = 'Undefined'; - } - - if (isset($ifSpeed[$ifIndex])) { - $speed = $ifSpeed[$ifIndex]; - } else { - $speed = 0; - } - - if (isset($ifDescr[$ifIndex])) { - $desc = $ifDescr[$ifIndex]; - } else { - $desc = ''; - } - - if (isset($ifLastChange[$ifIndex]) && false !== strpos($ifLastChange[$ifIndex], ':')) { - $ifLastChange[$ifIndex] = mactrack_timetics_to_seconds($ifLastChange[$ifIndex]); - } - - $mac_address = isset($ifPhysAddress[$ifIndex]) ? xform_mac_address($ifPhysAddress[$ifIndex]) : ''; - - $insert_vals .= "('" - .$device['site_id']."', '".$device['device_id']."', '" - .$device['snmp_sysUptime']."', '".$ifIndex."', " - .db_qstr($type).', '.db_qstr($name).', ' - .db_qstr($ifAlias).", '".$linkPort."', '" - .$vlan_id."', ".db_qstr($vlan_name).", '" - .$vlan_trunk."', '".$speed."', '" - .(isset($ifHighSpeed[$ifIndex]) ? $ifHighSpeed[$ifIndex] : '')."', '" - .(isset($ifDuplex[$ifIndex]) ? $ifDuplex[$ifIndex] : '')."', " - .db_qstr($desc).", '" - .(isset($ifMtu[$ifIndex]) ? $ifMtu[$ifIndex] : '')."', '" - .$mac_address."', '" - .(isset($ifAdminStatus[$ifIndex]) ? $ifAdminStatus[$ifIndex] : '')."', '" - .(isset($ifOperStatus[$ifIndex]) ? $ifOperStatus[$ifIndex] : '')."', '" - .(isset($ifLastChange[$ifIndex]) ? $ifLastChange[$ifIndex] : '')."', '" - .(isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : '')."', '" - .(isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : '')."', '" - .(isset($ifHCInOctets[$ifIndex]) ? $ifHCInOctets[$ifIndex] : '')."', '" - .(isset($ifHCOutOctets[$ifIndex]) ? $ifHCOutOctets[$ifIndex] : '')."', '" - .(isset($ifInUcastPkts[$ifIndex]) ? $ifInUcastPkts[$ifIndex] : '')."', '" - .(isset($ifOutUcastPkts[$ifIndex]) ? $ifOutUcastPkts[$ifIndex] : '')."', '" - .(isset($ifInDiscards[$ifIndex]) ? $ifInDiscards[$ifIndex] : '')."', '" - .(isset($ifInErrors[$ifIndex]) ? $ifInErrors[$ifIndex] : '')."', '" - .(isset($ifInUnknownProtos[$ifIndex]) ? $ifInUnknownProtos[$ifIndex] : '')."', '" - .(isset($ifOutDiscards[$ifIndex]) ? $ifOutDiscards[$ifIndex] : '')."', '" - .(isset($ifOutErrors[$ifIndex]) ? $ifOutErrors[$ifIndex] : '')."', '" - .(isset($ifInMulticastPkts[$ifIndex]) ? $ifInMulticastPkts[$ifIndex] : '')."', '" - .(isset($ifOutMulticastPkts[$ifIndex]) ? $ifOutMulticastPkts[$ifIndex] : '')."', '" - .(isset($ifInBroadcastPkts[$ifIndex]) ? $ifInBroadcastPkts[$ifIndex] : '')."', '" - .(isset($ifOutBroadcastPkts[$ifIndex]) ? $ifOutBroadcastPkts[$ifIndex] : '')."', '" - .@$int_ifInOctets."', '".@$int_ifOutOctets."', '" - .@$int_ifHCInOctets."', '".@$int_ifHCOutOctets."', '" - .@$int_ifInMulticastPkts."', '".@$int_ifOutMulticastPkts."', '" - .@$int_ifInBroadcastPkts."', '".@$int_ifOutBroadcastPkts."', '" - .@$int_ifInUcastPkts."', '".@$int_ifOutUcastPkts."', '" - .@$int_ifInDiscards."', '".@$int_ifInErrors."', '" - .@$int_ifInUnknownProtos."', '".@$int_ifOutDiscards."', '" - .@$int_ifOutErrors."', '".@$int_discards_present."', '" - .$int_errors_present."', '".$last_down_time."', '" - .$last_up_time."', '".$stateChanges."', '1')"; - - ++$i; - } - - mactrack_debug('ifInterfaces assembly complete: '.strlen($insert_prefix.$insert_vals.$insert_suffix)); - - if ('' != $insert_vals) { - // add/update records in the database - db_execute($insert_prefix.$insert_vals.$insert_suffix); - - // remove all obsolete records from the database - db_execute_prepared( - 'DELETE FROM mac_track_interfaces + if (cacti_sizeof($ifAdminStatus)) { + foreach ($ifAdminStatus as $key => $value) { + if (substr_count(strtolower($value), 'up') || ($value == '1')) { + $ifAdminStatus[$key] = 1; + } else { + $ifAdminStatus[$key] = 0; + } + } + } + mactrack_debug("ifAdminStatus data collection complete. '" . cacti_sizeof($ifAdminStatus) . "' rows found!"); + + $ifOperStatus = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + + if (cacti_sizeof($ifOperStatus)) { + foreach ($ifOperStatus as $key => $value) { + if (substr_count(strtolower($value), 'up') || ($value == '1')) { + $ifOperStatus[$key] = 1; + } else { + $ifOperStatus[$key] = 0; + } + } + } + mactrack_debug("ifOperStatus data collection complete. '" . cacti_sizeof($ifOperStatus) . "' rows found!"); + + $ifLastChange = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.9', $device); + mactrack_debug("ifLastChange data collection complete. '" . cacti_sizeof($ifLastChange) . "' rows found!"); + + // get timing for rate information + $prev_octets_time = strtotime($device['last_rundate']); + $cur_octets_time = time(); + + if ($prev_octets_time == 0) { + $divisor = false; + } else { + $divisor = $cur_octets_time - $prev_octets_time; + } + + // if the device is snmpv2 use high speed and don't bother with the low speed stuff + $ifInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.10', $device); + mactrack_debug("ifInOctets data collection complete. '" . cacti_sizeof($ifInOctets) . "' rows found!"); + + $ifOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.16', $device); + mactrack_debug("ifOutOctets data collection complete. '" . cacti_sizeof($ifOutOctets) . "' rows found!"); + + if ($device['snmp_version'] > 1) { + $ifHCInOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.6', $device); + mactrack_debug("ifHCInOctets data collection complete. '" . cacti_sizeof($ifHCInOctets) . "' rows found!"); + + $ifHCOutOctets = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.10', $device); + mactrack_debug("ifHCOutOctets data collection complete. '" . cacti_sizeof($ifHCOutOctets) . "' rows found!"); + } + + $ifInMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.2', $device); + mactrack_debug("ifInMulticastPkts data collection complete. '" . cacti_sizeof($ifInMulticastPkts) . "' rows found!"); + + $ifOutMulticastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.4', $device); + mactrack_debug("ifOutMulticastPkts data collection complete. '" . cacti_sizeof($ifOutMulticastPkts) . "' rows found!"); + + $ifInBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.3', $device); + mactrack_debug("ifInBroadcastPkts data collection complete. '" . cacti_sizeof($ifInBroadcastPkts) . "' rows found!"); + + $ifOutBroadcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.31.1.1.1.5', $device); + mactrack_debug("ifOutBroadcastPkts data collection complete. '" . cacti_sizeof($ifOutBroadcastPkts) . "' rows found!"); + + $ifInUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.11', $device); + mactrack_debug("ifInUcastPkts data collection complete. '" . cacti_sizeof($ifInUcastPkts) . "' rows found!"); + + $ifOutUcastPkts = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.17', $device); + mactrack_debug("ifOutUcastPkts data collection complete. '" . cacti_sizeof($ifOutUcastPkts) . "' rows found!"); + + // get information on error conditions + $ifInDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.13', $device); + mactrack_debug("ifInDiscards data collection complete. '" . cacti_sizeof($ifInDiscards) . "' rows found!"); + + $ifInErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.14', $device); + mactrack_debug("ifInErrors data collection complete. '" . cacti_sizeof($ifInErrors) . "' rows found!"); + + $ifInUnknownProtos = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.15', $device); + mactrack_debug("ifInUnknownProtos data collection complete. '" . cacti_sizeof($ifInUnknownProtos) . "' rows found!"); + + $ifOutDiscards = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.19', $device); + mactrack_debug("ifOutDiscards data collection complete. '" . cacti_sizeof($ifOutDiscards) . "' rows found!"); + + $ifOutErrors = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.20', $device); + mactrack_debug("ifOutErrors data collection complete. '" . cacti_sizeof($ifOutErrors) . "' rows found!"); + + $vlan_id = ''; + $vlan_name = ''; + $vlan_trunk = ''; + + $i = 0; + + foreach ($ifIndexes as $ifIndex) { + $ifInterfaces[$ifIndex]['ifIndex'] = $ifIndex; + $ifInterfaces[$ifIndex]['ifName'] = (isset($ifNames[$ifIndex]) ? $ifNames[$ifIndex] : ''); + $ifInterfaces[$ifIndex]['ifType'] = (isset($ifTypes[$ifIndex]) ? $ifTypes[$ifIndex] : ''); + + if ($getLinkPorts) { + $ifInterfaces[$ifIndex]['linkPort'] = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); + $linkPort = (isset($link_ports[$ifIndex]) ? $link_ports[$ifIndex] : ''); + } else { + $linkPort = 0; + } + + if ($getAlias && cacti_sizeof($ifAliases)) { + $ifInterfaces[$ifIndex]['ifAlias'] = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); + $ifAlias = (isset($ifAliases[$ifIndex]) ? $ifAliases[$ifIndex] : ''); + } else { + $ifAlias = ''; + } + + // update the last up/down status + if (!isset($db_interface[$ifIndex])) { + if (isset($ifOperStatus[$ifIndex]) && $ifOperStatus[$ifIndex] == 1) { + $last_up_time = date('Y-m-d H:i:s'); + $stateChanges = 0; + $last_down_time = 0; + } else { + $stateChanges = 0; + $last_up_time = 0; + $last_down_time = date('Y-m-d H:i:s'); + } + } else { + $last_up_time = $db_interface[$ifIndex]['last_up_time']; + $last_down_time = $db_interface[$ifIndex]['last_down_time']; + $stateChanges = $db_interface[$ifIndex]['stateChanges']; + + if ($db_interface[$ifIndex]['ifOperStatus'] == 0) { // interface previously not up + if (isset($ifOperStatus[$ifIndex]) && $ifOperStatus[$ifIndex] == 1) { + // the interface just went up, mark the time + $last_up_time = date('Y-m-d H:i:s'); + ++$stateChanges; + + // if the interface has never been marked down before, make it the current time + if ($db_interface[$ifIndex]['last_down_time'] == '0000-00-00 00:00:00') { + $last_down_time = $last_up_time; + } + } else { + // if the interface has never been down, make the current time + $last_down_time = date('Y-m-d H:i:s'); + + // if the interface stayed down, set the last up time if not set before + if ($db_interface[$ifIndex]['last_up_time'] == '0000-00-00 00:00:00') { + $last_up_time = date('Y-m-d H:i:s'); + } + } + } else { + if (isset($ifOperStatus[$ifIndex]) && $ifOperStatus[$ifIndex] == 0) { + // the interface just went down, mark the time + $last_down_time = date('Y-m-d H:i:s'); + ++$stateChanges; + + // if the interface has never been up before, mark it the current time + if ($db_interface[$ifIndex]['last_up_time'] == '0000-00-00 00:00:00') { + $last_up_time = date('Y-m-d H:i:s'); + } + } else { + $last_up_time = date('Y-m-d H:i:s'); + + if ($db_interface[$ifIndex]['last_down_time'] == '0000-00-00 00:00:00') { + $last_down_time = date('Y-m-d H:i:s'); + } + } + } + } + + // do the in octets + $int_ifInOctets = get_link_int_value('ifInOctets', $ifIndex, $ifInOctets, $db_interface, $divisor, 'traffic'); + + // do the out octets + $int_ifOutOctets = get_link_int_value('ifOutOctets', $ifIndex, $ifOutOctets, $db_interface, $divisor, 'traffic'); + + if ($device['snmp_version'] > 1) { + // do the in octets + $int_ifHCInOctets = get_link_int_value('ifHCInOctets', $ifIndex, $ifHCInOctets, $db_interface, $divisor, 'traffic', '64'); + + // do the out octets + $int_ifHCOutOctets = get_link_int_value('ifHCOutOctets', $ifIndex, $ifHCOutOctets, $db_interface, $divisor, 'traffic', '64'); + } + + // accommodate values in high speed octets for interfaces that don't support 64 bit + if (isset($ifInOctets[$ifIndex])) { + if (!isset($ifHCInOctets[$ifIndex])) { + $ifHCInOctets[$ifIndex] = isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : ''; + $int_ifHCInOctets = $int_ifInOctets; + } + } + + if (isset($ifOutOctets[$ifIndex])) { + if (!isset($ifHCOutOctets[$ifIndex])) { + $ifHCOutOctets[$ifIndex] = isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : ''; + $int_ifHCOutOctets = $int_ifOutOctets; + } + } + + $int_ifInMulticastPkts = get_link_int_value('ifInMulticastPkts', $ifIndex, $ifInMulticastPkts, $db_interface, $divisor, 'traffic'); + $int_ifOutMulticastPkts = get_link_int_value('ifOutMulticastPkts', $ifIndex, $ifOutMulticastPkts, $db_interface, $divisor, 'traffic'); + $int_ifInBroadcastPkts = get_link_int_value('ifInBroadcastPkts', $ifIndex, $ifInBroadcastPkts, $db_interface, $divisor, 'traffic'); + $int_ifOutBroadcastPkts = get_link_int_value('ifOutBroadcastPkts', $ifIndex, $ifOutBroadcastPkts, $db_interface, $divisor, 'traffic'); + $int_ifInUcastPkts = get_link_int_value('ifInUcastPkts', $ifIndex, $ifInUcastPkts, $db_interface, $divisor, 'traffic'); + $int_ifOutUcastPkts = get_link_int_value('ifOutUcastPkts', $ifIndex, $ifOutUcastPkts, $db_interface, $divisor, 'traffic'); + + // see if in error's have been increasing + $int_ifInErrors = get_link_int_value('ifInErrors', $ifIndex, $ifInErrors, $db_interface, $divisor, 'errors'); + + // see if out error's have been increasing + $int_ifOutErrors = get_link_int_value('ifOutErrors', $ifIndex, $ifOutErrors, $db_interface, $divisor, 'errors'); + + if ($int_ifInErrors > 0 || $int_ifOutErrors > 0) { + $int_errors_present = true; + } else { + $int_errors_present = false; + } + + // see if in discards's have been increasing + $int_ifInDiscards = get_link_int_value('ifInDiscards', $ifIndex, $ifInDiscards, $db_interface, $divisor, 'errors'); + + // see if out discards's have been increasing + $int_ifOutDiscards = get_link_int_value('ifOutDiscards', $ifIndex, $ifOutDiscards, $db_interface, $divisor, 'errors'); + + if ($int_ifInDiscards > 0 || $int_ifOutDiscards > 0) { + $int_discards_present = true; + } else { + $int_discards_present = false; + } + + // see if in discards's have been increasing + $int_ifInUnknownProtos = get_link_int_value('ifInUnknownProtos', $ifIndex, $ifInUnknownProtos, $db_interface, $divisor, 'errors'); + + // format the update packet + if ($i == 0) { + $insert_vals .= ' '; + } else { + $insert_vals .= ','; + } + + if (isset($ifTypes[$ifIndex])) { + $type = $ifTypes[$ifIndex]; + } else { + $type = 'Undefined'; + } + + if (isset($ifNames[$ifIndex])) { + $name = $ifNames[$ifIndex]; + } else { + $name = 'Undefined'; + } + + if (isset($ifSpeed[$ifIndex])) { + $speed = $ifSpeed[$ifIndex]; + } else { + $speed = 0; + } + + if (isset($ifDescr[$ifIndex])) { + $desc = $ifDescr[$ifIndex]; + } else { + $desc = ''; + } + + if (isset($ifLastChange[$ifIndex]) && strpos($ifLastChange[$ifIndex], ':') !== false) { + $ifLastChange[$ifIndex] = mactrack_timetics_to_seconds($ifLastChange[$ifIndex]); + } + + $mac_address = isset($ifPhysAddress[$ifIndex]) ? xform_mac_address($ifPhysAddress[$ifIndex]) : ''; + + $insert_vals .= "('" + . $device['site_id'] . "', '" . $device['device_id'] . "', '" + . $device['snmp_sysUptime'] . "', '" . $ifIndex . "', " + . db_qstr($type) . ', ' . db_qstr($name) . ', ' + . db_qstr($ifAlias) . ", '" . $linkPort . "', '" + . $vlan_id . "', " . db_qstr($vlan_name) . ", '" + . $vlan_trunk . "', '" . $speed . "', '" + . (isset($ifHighSpeed[$ifIndex]) ? $ifHighSpeed[$ifIndex] : '') . "', '" + . (isset($ifDuplex[$ifIndex]) ? $ifDuplex[$ifIndex] : '') . "', " + . db_qstr($desc) . ", '" + . (isset($ifMtu[$ifIndex]) ? $ifMtu[$ifIndex] : '') . "', '" + . $mac_address . "', '" + . (isset($ifAdminStatus[$ifIndex]) ? $ifAdminStatus[$ifIndex] : '') . "', '" + . (isset($ifOperStatus[$ifIndex]) ? $ifOperStatus[$ifIndex] : '') . "', '" + . (isset($ifLastChange[$ifIndex]) ? $ifLastChange[$ifIndex] : '') . "', '" + . (isset($ifInOctets[$ifIndex]) ? $ifInOctets[$ifIndex] : '') . "', '" + . (isset($ifOutOctets[$ifIndex]) ? $ifOutOctets[$ifIndex] : '') . "', '" + . (isset($ifHCInOctets[$ifIndex]) ? $ifHCInOctets[$ifIndex] : '') . "', '" + . (isset($ifHCOutOctets[$ifIndex]) ? $ifHCOutOctets[$ifIndex] : '') . "', '" + . (isset($ifInUcastPkts[$ifIndex]) ? $ifInUcastPkts[$ifIndex] : '') . "', '" + . (isset($ifOutUcastPkts[$ifIndex]) ? $ifOutUcastPkts[$ifIndex] : '') . "', '" + . (isset($ifInDiscards[$ifIndex]) ? $ifInDiscards[$ifIndex] : '') . "', '" + . (isset($ifInErrors[$ifIndex]) ? $ifInErrors[$ifIndex] : '') . "', '" + . (isset($ifInUnknownProtos[$ifIndex]) ? $ifInUnknownProtos[$ifIndex] : '') . "', '" + . (isset($ifOutDiscards[$ifIndex]) ? $ifOutDiscards[$ifIndex] : '') . "', '" + . (isset($ifOutErrors[$ifIndex]) ? $ifOutErrors[$ifIndex] : '') . "', '" + . (isset($ifInMulticastPkts[$ifIndex]) ? $ifInMulticastPkts[$ifIndex] : '') . "', '" + . (isset($ifOutMulticastPkts[$ifIndex]) ? $ifOutMulticastPkts[$ifIndex] : '') . "', '" + . (isset($ifInBroadcastPkts[$ifIndex]) ? $ifInBroadcastPkts[$ifIndex] : '') . "', '" + . (isset($ifOutBroadcastPkts[$ifIndex]) ? $ifOutBroadcastPkts[$ifIndex] : '') . "', '" + . @$int_ifInOctets . "', '" . @$int_ifOutOctets . "', '" + . @$int_ifHCInOctets . "', '" . @$int_ifHCOutOctets . "', '" + . @$int_ifInMulticastPkts . "', '" . @$int_ifOutMulticastPkts . "', '" + . @$int_ifInBroadcastPkts . "', '" . @$int_ifOutBroadcastPkts . "', '" + . @$int_ifInUcastPkts . "', '" . @$int_ifOutUcastPkts . "', '" + . @$int_ifInDiscards . "', '" . @$int_ifInErrors . "', '" + . @$int_ifInUnknownProtos . "', '" . @$int_ifOutDiscards . "', '" + . @$int_ifOutErrors . "', '" . @$int_discards_present . "', '" + . $int_errors_present . "', '" . $last_down_time . "', '" + . $last_up_time . "', '" . $stateChanges . "', '1')"; + + ++$i; + } + + mactrack_debug('ifInterfaces assembly complete: ' . strlen($insert_prefix . $insert_vals . $insert_suffix)); + + if ($insert_vals != '') { + // add/update records in the database + db_execute($insert_prefix . $insert_vals . $insert_suffix); + + // remove all obsolete records from the database + db_execute_prepared( + 'DELETE FROM mac_track_interfaces WHERE present=0 AND device_id = ?', - [$device['device_id']] - ); + [$device['device_id']] + ); - // set the percent utilized fields, you can't do this for vlans - db_execute_prepared( - 'UPDATE mac_track_interfaces + // set the percent utilized fields, you can't do this for vlans + db_execute_prepared( + 'UPDATE mac_track_interfaces SET inBound=(int_ifHCInOctets*8)/(ifHighSpeed*10000), outBound=(int_ifHCOutOctets*8)/(ifHighSpeed*10000) WHERE ifHighSpeed>0 AND ifName NOT LIKE "Vl%" AND device_id = ?', - [$device['device_id']] - ); + [$device['device_id']] + ); - mactrack_debug('Adding IfInterfaces Records'); - } + mactrack_debug('Adding IfInterfaces Records'); + } - if ($device['host_id'] > 0) { - mactrack_find_host_graphs($device['device_id'], $device['host_id']); - } + if ($device['host_id'] > 0) { + mactrack_find_host_graphs($device['device_id'], $device['host_id']); + } - return $ifInterfaces; + return $ifInterfaces; } -function mactrack_timetics_to_seconds($timetics) -{ - $time = 0; - $parts = explode(':', $timetics); +function mactrack_timetics_to_seconds($timetics) { + $time = 0; + $parts = explode(':', $timetics); - if (4 == cacti_sizeof($parts)) { - $time += $parts[0] * 86400; - $time += $parts[1] * 3600; - $time += $parts[2] * 60; - $time += round($parts[3], 0); - } elseif (3 == cacti_sizeof($parts)) { - $time += $parts[0] * 3600; - $time += $parts[1] * 60; - $time += round($parts[2], 0); - } + if (cacti_sizeof($parts) == 4) { + $time += $parts[0] * 86400; + $time += $parts[1] * 3600; + $time += $parts[2] * 60; + $time += round($parts[3], 0); + } elseif (cacti_sizeof($parts) == 3) { + $time += $parts[0] * 3600; + $time += $parts[1] * 60; + $time += round($parts[2], 0); + } - return $time; + return $time; } -function mactrack_find_host_graphs($device_id, $host_id) -{ - $field_name = 'ifName'; +function mactrack_find_host_graphs($device_id, $host_id) { + $field_name = 'ifName'; - $local_data_ids = db_fetch_assoc_prepared( - 'SELECT dl.*, + $local_data_ids = db_fetch_assoc_prepared( + 'SELECT dl.*, hsc.field_name, hsc.field_value FROM data_local AS dl INNER JOIN data_template_data AS dtd @@ -1119,15 +1123,16 @@ function mactrack_find_host_graphs($device_id, $host_id) WHERE dl.id=dtd.local_data_id AND hsc.host_id = ? AND field_name = ?', - [$host_id, $field_name] - ); - - $output_array = []; - if (cacti_sizeof($local_data_ids)) { - foreach ($local_data_ids as $local_data_id) { - $local_graph_ids = array_rekey( - db_fetch_assoc_prepared( - 'SELECT DISTINCT gtg.local_graph_id AS id, gtg.graph_template_id + [$host_id, $field_name] + ); + + $output_array = []; + + if (cacti_sizeof($local_data_ids)) { + foreach ($local_data_ids as $local_data_id) { + $local_graph_ids = array_rekey( + db_fetch_assoc_prepared( + 'SELECT DISTINCT gtg.local_graph_id AS id, gtg.graph_template_id FROM graph_templates_graph AS gtg INNER JOIN graph_templates_item AS gti ON gtg.local_graph_id=gti.local_graph_id @@ -1135,63 +1140,64 @@ function mactrack_find_host_graphs($device_id, $host_id) ON gti.task_item_id=dtr.id WHERE gtg.local_graph_id>0 AND dtr.local_data_id = ?', - [$local_data_id['id']] - ), - 'id', - 'graph_template_id' - ); - - if (cacti_sizeof($local_graph_ids)) { - foreach ($local_graph_ids as $local_graph_id => $graph_template_id) { - $output_array[$local_data_id['field_value']][$local_graph_id] = [$graph_template_id, $local_data_id['snmp_query_id']]; - } - } - } - } - - $sql = ''; - $found = 0; - if (cacti_sizeof($output_array)) { - $interfaces = array_rekey( - db_fetch_assoc("SELECT device_id, ifIndex, {$field_name} + [$local_data_id['id']] + ), + 'id', + 'graph_template_id' + ); + + if (cacti_sizeof($local_graph_ids)) { + foreach ($local_graph_ids as $local_graph_id => $graph_template_id) { + $output_array[$local_data_id['field_value']][$local_graph_id] = [$graph_template_id, $local_data_id['snmp_query_id']]; + } + } + } + } + + $sql = ''; + $found = 0; + + if (cacti_sizeof($output_array)) { + $interfaces = array_rekey( + db_fetch_assoc("SELECT device_id, ifIndex, {$field_name} FROM mac_track_interfaces WHERE device_id={$device_id}"), - $field_name, - ['device_id', 'ifIndex'] - ); - - if (cacti_sizeof($interfaces)) { - foreach ($interfaces as $key => $data) { - if (isset($output_array[$key])) { - foreach ($output_array[$key] as $local_graph_id => $graph_details) { - $sql .= ('' != $sql ? ', (' : '(') - .$data['ifIndex'].",'" - .$key."'," - .$local_graph_id.',' - .$device_id.',' - .$host_id.',' - .$graph_details[0].',' - .$graph_details[1].",'" - .$key."','".$field_name."', 1)"; - - ++$found; - } - } - } - } - } - - if ($found) { - // let's make sure we mark everything gone first - db_execute_prepared( - 'UPDATE mac_track_interface_graphs + $field_name, + ['device_id', 'ifIndex'] + ); + + if (cacti_sizeof($interfaces)) { + foreach ($interfaces as $key => $data) { + if (isset($output_array[$key])) { + foreach ($output_array[$key] as $local_graph_id => $graph_details) { + $sql .= ($sql != '' ? ', (' : '(') + . $data['ifIndex'] . ",'" + . $key . "'," + . $local_graph_id . ',' + . $device_id . ',' + . $host_id . ',' + . $graph_details[0] . ',' + . $graph_details[1] . ",'" + . $key . "','" . $field_name . "', 1)"; + + ++$found; + } + } + } + } + } + + if ($found) { + // let's make sure we mark everything gone first + db_execute_prepared( + 'UPDATE mac_track_interface_graphs SET present = 0 WHERE device_id = ? AND host_id = ?', - [$device_id, $host_id] - ); + [$device_id, $host_id] + ); - db_execute("INSERT INTO mac_track_interface_graphs + db_execute("INSERT INTO mac_track_interface_graphs (ifIndex, ifName, local_graph_id, device_id, host_id, snmp_query_id, graph_template_id, field_value, field_name, present) VALUES {$sql} ON DUPLICATE KEY UPDATE @@ -1201,82 +1207,82 @@ function mactrack_find_host_graphs($device_id, $host_id) field_name=VALUES(field_name), present=VALUES(present)"); - db_execute_prepared( - 'DELETE FROM mac_track_interface_graphs + db_execute_prepared( + 'DELETE FROM mac_track_interface_graphs WHERE present = 0 AND device_id = ? AND host_id = ?', - [$device_id, $host_id] - ); - } -} - -function get_link_int_value($snmp_oid, $ifIndex, &$snmp_array, &$db_interface, $divisor, $type = 'errors', $bits = '32') -{ - // 32bit and 64bit Integer Overflow Value - if ('32' == $bits) { - $overflow = 4294967295; - // fudge factor - $fudge = 3000000001; - } else { - $overflow = 18446744065119617025; - // fudge factor - $fudge = 300000000001; - } - - // see if values have been increasing - $int_value = 0; - if (!isset($db_interface[$ifIndex][$snmp_oid])) { - $int_value = 0; - } elseif (!isset($snmp_array[$ifIndex])) { - $int_value = 0; - } elseif ($snmp_array[$ifIndex] != $db_interface[$ifIndex][$snmp_oid]) { - // account for 2E32 rollover - // there are two types of rollovers one rolls to 0 - // the other counts backwards. let's make an educated guess - if ($db_interface[$ifIndex][$snmp_oid] > $snmp_array[$ifIndex]) { - // errors count backwards from overflow - if ('errors' == $type) { - if (($overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]) < $fudge) { - $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; - } else { - $int_value = $db_interface[$ifIndex][$snmp_oid] - $snmp_array[$ifIndex]; - } - } else { - $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; - } - } else { - $int_value = $snmp_array[$ifIndex] - $db_interface[$ifIndex][$snmp_oid]; - } - - // account for counter resets - $frequency = 0; - $timing = read_config_option('mt_collection_timing'); - - if ('disabled' != $timing) { - $frequency = $timing * 60; - } - - if ($frequency > 0) { - if ($db_interface[$ifIndex]['ifHighSpeed'] > 0) { - if ($int_value > ($db_interface[$ifIndex]['ifHighSpeed'] * 1000000 * $frequency * 1.1)) { - $int_value = $snmp_array[$ifIndex]; - } - } else { - if ($int_value > ($db_interface[$ifIndex]['ifSpeed'] * $frequency * 1.1 / 8)) { - $int_value = $snmp_array[$ifIndex]; - } - } - } - } else { - $int_value = 0; - } - - if (!$divisor) { - return 0; - } - - return $int_value / $divisor; + [$device_id, $host_id] + ); + } +} + +function get_link_int_value($snmp_oid, $ifIndex, &$snmp_array, &$db_interface, $divisor, $type = 'errors', $bits = '32') { + // 32bit and 64bit Integer Overflow Value + if ($bits == '32') { + $overflow = 4294967295; + // fudge factor + $fudge = 3000000001; + } else { + $overflow = 18446744065119617025; + // fudge factor + $fudge = 300000000001; + } + + // see if values have been increasing + $int_value = 0; + + if (!isset($db_interface[$ifIndex][$snmp_oid])) { + $int_value = 0; + } elseif (!isset($snmp_array[$ifIndex])) { + $int_value = 0; + } elseif ($snmp_array[$ifIndex] != $db_interface[$ifIndex][$snmp_oid]) { + // account for 2E32 rollover + // there are two types of rollovers one rolls to 0 + // the other counts backwards. let's make an educated guess + if ($db_interface[$ifIndex][$snmp_oid] > $snmp_array[$ifIndex]) { + // errors count backwards from overflow + if ($type == 'errors') { + if (($overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]) < $fudge) { + $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; + } else { + $int_value = $db_interface[$ifIndex][$snmp_oid] - $snmp_array[$ifIndex]; + } + } else { + $int_value = $overflow - $db_interface[$ifIndex][$snmp_oid] + $snmp_array[$ifIndex]; + } + } else { + $int_value = $snmp_array[$ifIndex] - $db_interface[$ifIndex][$snmp_oid]; + } + + // account for counter resets + $frequency = 0; + $timing = read_config_option('mt_collection_timing'); + + if ($timing != 'disabled') { + $frequency = $timing * 60; + } + + if ($frequency > 0) { + if ($db_interface[$ifIndex]['ifHighSpeed'] > 0) { + if ($int_value > ($db_interface[$ifIndex]['ifHighSpeed'] * 1000000 * $frequency * 1.1)) { + $int_value = $snmp_array[$ifIndex]; + } + } else { + if ($int_value > ($db_interface[$ifIndex]['ifSpeed'] * $frequency * 1.1 / 8)) { + $int_value = $snmp_array[$ifIndex]; + } + } + } + } else { + $int_value = 0; + } + + if (!$divisor) { + return 0; + } + + return $int_value / $divisor; } /** @@ -1290,24 +1296,23 @@ function get_link_int_value($snmp_oid, $ifIndex, &$snmp_array, &$db_interface, $ * @param mixed $lowPort * @param mixed $highPort */ -function get_generic_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; +function get_generic_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /** @@ -1321,24 +1326,23 @@ function get_generic_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) * @param mixed $lowPort * @param mixed $highPort */ -function get_generic_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; +function get_generic_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, true, false); - get_base_dot1qTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_dot1qTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /** @@ -1352,24 +1356,23 @@ function get_generic_dot1q_switch_ports($site, &$device, $lowPort = 0, $highPort * @param mixed $lowPort * @param mixed $highPort */ -function get_generic_wireless_ports($site, &$device, $lowPort = 0, $highPort = 0) -{ - global $debug, $scan_date; +function get_generic_wireless_ports($site, &$device, $lowPort = 0, $highPort = 0) { + global $debug, $scan_date; - // initialize port counters - $device['ports_total'] = 0; - $device['ports_active'] = 0; - $device['ports_trunk'] = 0; + // initialize port counters + $device['ports_total'] = 0; + $device['ports_active'] = 0; + $device['ports_trunk'] = 0; - // get the ifIndexes for the device - $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); - mactrack_debug('ifIndexes data collection complete'); + // get the ifIndexes for the device + $ifIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.1', $device); + mactrack_debug('ifIndexes data collection complete'); - $ifInterfaces = build_InterfacesTable($device, $ifIndexes, false, false); + $ifInterfaces = build_InterfacesTable($device, $ifIndexes, false, false); - get_base_wireless_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); + get_base_wireless_dot1dTpFdbEntry_ports($site, $device, $ifInterfaces, '', true, $lowPort, $highPort); - return $device; + return $device; } /** @@ -1385,231 +1388,233 @@ function get_generic_wireless_ports($site, &$device, $lowPort = 0, $highPort = 0 * @param mixed $lowPort * @param mixed $highPort */ -function get_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // cisco uses a hybrid read string, if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - if (isset($indexes[$i], $ifInterfaces[$indexes[$i]]['ifType'])) { - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) - || (53 == $ifInterfaces[$indexes[$i]]['ifType']) // vlan - || (161 == $ifInterfaces[$indexes[$i]]['ifType']) // port-channel - || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { - if (1 == $port_info) { - ++$ports_active; - } - } - ++$ports_total; - } - - ++$i; - } - } - $device['ports_active'] = $ports_active; - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - // get bridge port to ifIndex mapping - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - - // get device active port numbers - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort))) { - if (!in_array($port_number, $ignore_ports)) { - if ((isset($port_status[$key]) && '3' == $port_status[$key]) - || (isset($port_status[$key]) && '5' == $port_status[$key])) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - ++$i; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes)) { - /* some hubs do not always return a port number in the bridge table. - test for it by isset and substitute the port number from the ifTable - if it isnt in the bridge table - */ - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; - } else { - $brPortIfIndex = @$port_key['port_number']; - } - $brPortIfType = (isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''); - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; - } - - if ((($brPortIfType >= 6 && $brPortIfType <= 9) - || 53 == $brPortIfType || 161 == $brPortIfType) - && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - ++$i; - } - } - } - } - mactrack_debug('Port number information collected.'); - - // map mac address - // only continue if there were user ports defined - if (cacti_sizeof($new_port_key_array)) { - // get the bridges active MAC addresses - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - if (cacti_sizeof($port_macs)) { - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - } - - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = (isset($port_macs[$port_key['key']]) ? $port_macs[$port_key['key']] : ''); - mactrack_debug("INDEX: '".$key."' MAC ADDRESS: ".$new_port_key_array[$key]['mac_address']); - } - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array)) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_base_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + + if (isset($indexes[$i], $ifInterfaces[$indexes[$i]]['ifType'])) { + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || ($ifInterfaces[$indexes[$i]]['ifType'] == 53) // vlan + || ($ifInterfaces[$indexes[$i]]['ifType'] == 161) // port-channel + || ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { + if ($port_info == 1) { + ++$ports_active; + } + } + ++$ports_total; + } + + ++$i; + } + } + $device['ports_active'] = $ports_active; + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort))) { + if (!in_array($port_number, $ignore_ports, true)) { + if ((isset($port_status[$key]) && $port_status[$key] == '3') + || (isset($port_status[$key]) && $port_status[$key] == '5')) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes)) { + /* some hubs do not always return a port number in the bridge table. + test for it by isset and substitute the port number from the ifTable + if it isnt in the bridge table + */ + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; + } else { + $brPortIfIndex = @$port_key['port_number']; + } + $brPortIfType = (isset($ifInterfaces[$brPortIfIndex]['ifType']) ? $ifInterfaces[$brPortIfIndex]['ifType'] : ''); + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; + } + + if ((($brPortIfType >= 6 && $brPortIfType <= 9) + || $brPortIfType == 53 || $brPortIfType == 161) + && (!isset($ifInterfaces[$brPortIfIndex]['portLink']))) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + if (cacti_sizeof($port_macs)) { + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + } + + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = (isset($port_macs[$port_key['key']]) ? $port_macs[$port_key['key']] : ''); + mactrack_debug("INDEX: '" . $key . "' MAC ADDRESS: " . $new_port_key_array[$key]['mac_address']); + } + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array)) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /* get_ios_vrf_arp_table - obtains arp associations for cisco Catalyst Switches. - At this stage only tested on 6800 series + obtains arp associations for cisco Catalyst Switches. + At this stage only tested on 6800 series */ -function get_ios_vrf_arp_table($oid, &$device, $snmp_readstring = '', $hex = false) -{ - $return_array = []; - - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - if ('3' == $device['snmp_version'] && substr_count($snmp_readstring, 'vlan-')) { - $snmp_context = $snmp_readstring; - } else { - $snmp_context = $device['snmp_context']; - } - - $walk_array = cacti_snmp_walk( - $device['hostname'], - $snmp_readstring, - $oid, - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $snmp_context, - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'], - SNMP_POLLER, - $device['snmp_engine_id'], - $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS - ); - - $i = 0; - - if (cacti_sizeof($walk_array)) { - foreach ($walk_array as $walk_item) { - $key = $walk_item['oid']; - $key = preg_replace('/'.$oid.'\.[0-9]+\.1\./', '', $key); - $return_array[$i]['key'] = $key; - $return_array[$i]['value'] = str_replace(' ', ':', $walk_item['value']); - - ++$i; - } - } - - return $return_array; +function get_ios_vrf_arp_table($oid, &$device, $snmp_readstring = '', $hex = false) { + $return_array = []; + + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + if ($device['snmp_version'] == '3' && substr_count($snmp_readstring, 'vlan-')) { + $snmp_context = $snmp_readstring; + } else { + $snmp_context = $device['snmp_context']; + } + + $walk_array = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + $oid, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $snmp_context, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $i = 0; + + if (cacti_sizeof($walk_array)) { + foreach ($walk_array as $walk_item) { + $key = $walk_item['oid']; + $key = preg_replace('/' . $oid . '\.[0-9]+\.1\./', '', $key); + $return_array[$i]['key'] = $key; + $return_array[$i]['value'] = str_replace(' ', ':', $walk_item['value']); + + ++$i; + } + } + + return $return_array; } /** @@ -1625,178 +1630,181 @@ function get_ios_vrf_arp_table($oid, &$device, $snmp_readstring = '', $hex = fal * @param mixed $lowPort * @param mixed $highPort */ -function get_base_wireless_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // cisco uses a hybrid read string, if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) - || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - } - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_active'] = $ports_active; - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - // get bridge port to ifIndex mapping - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); - - // get device active port numbers - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - // get the bridge root port so we don't capture active ports on it - $bridge_root_port = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.2.7.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort) - && ($bridge_root_port != $port_number))) { - if (!in_array($port_number, $ignore_ports)) { - if (('3' == @$port_status[$key]) || ('5' == @$port_status[$key])) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - ++$i; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes)) { - $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; - $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; - } else { - $brPortIfIndex = $port_key['port_number']; - $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; - } - - if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || (71 == $brPortIfType)) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - ++$i; - } - } - } - } - mactrack_debug('Port number information collected.'); - - // map mac address - // only continue if there were user ports defined - if (cacti_sizeof($new_port_key_array)) { - // get the bridges active MAC addresses - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); - - if (cacti_sizeof($port_macs)) { - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - } - - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_key) { - $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; - mactrack_debug("INDEX: '".$key."' MAC ADDRESS: ".$new_port_key_array[$key]['mac_address']); - } - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array)) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_base_wireless_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_active'] = $ports_active; + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // get the bridge root port so we don't capture active ports on it + $bridge_root_port = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.2.7.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort) + && ($bridge_root_port != $port_number))) { + if (!in_array($port_number, $ignore_ports, true)) { + if ((@$port_status[$key] == '3') || (@$port_status[$key] == '5')) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes)) { + $brPortIfIndex = @$bridgePortIfIndexes[$port_key['port_number']]; + $brPortIfType = @$ifInterfaces[$brPortIfIndex]['ifType']; + } else { + $brPortIfIndex = $port_key['port_number']; + $brPortIfType = @$ifInterfaces[$port_key['port_number']]['ifType']; + } + + if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || ($brPortIfType == 71)) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.4.3.1.1', $device, $snmp_readstring, true); + + if (cacti_sizeof($port_macs)) { + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + } + + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_key) { + $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; + mactrack_debug("INDEX: '" . $key . "' MAC ADDRESS: " . $new_port_key_array[$key]['mac_address']); + } + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array)) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /** @@ -1812,188 +1820,193 @@ function get_base_wireless_dot1dTpFdbEntry_ports($site, &$device, &$ifInterfaces * @param mixed $lowPort * @param mixed $highPort */ -function get_base_dot1qTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) -{ - global $debug, $scan_date; - - // initialize variables - $port_keys = []; - $return_array = []; - $new_port_key_array = []; - $port_key_array = []; - $port_number = 0; - $ports_active = 0; - $active_ports = 0; - $ports_total = 0; - - // cisco uses a hybrid read string, if one is not defined, use the default - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // get the operational status of the ports - $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); - $indexes = array_keys($active_ports_array); - - $i = 0; - if (cacti_sizeof($active_ports_array)) { - foreach ($active_ports_array as $port_info) { - $port_info = mactrack_strip_alpha($port_info); - if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) - && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) - || (71 == $ifInterfaces[$indexes[$i]]['ifType'])) { - if (1 == $port_info) { - ++$ports_active; - } - ++$ports_total; - } - ++$i; - } - } - $device['ports_active'] = $ports_active; - - if ($store_to_db) { - mactrack_debug('INFO: HOST: '.$device['hostname'].', TYPE: '.substr($device['snmp_sysDescr'], 0, 40).', TOTAL PORTS: '.$ports_total.', OPER PORTS: '.$ports_active); - - $device['ports_total'] = $ports_total; - $device['macs_active'] = 0; - } - - if ($ports_active > 0) { - // get bridge port to ifIndex mapping - $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); - - $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); - - // get device active port numbers - $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); - - // get the ignore ports list from device - $ignore_ports = port_list_to_array($device['ignorePorts']); - - // get the bridge root port so we don't capture active ports on it - $bridge_root_port = @cacti_snmp_get( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.2.7.0', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'] - ); - - /* determine user ports for this device and transfer user ports to - a new array. - */ - $i = 0; - if (cacti_sizeof($port_numbers)) { - foreach ($port_numbers as $key => $port_number) { - if ((0 == $highPort) - || (($port_number >= $lowPort) - && ($port_number <= $highPort) - && ($bridge_root_port != $port_number))) { - if (!in_array($port_number, $ignore_ports)) { - if ((isset($port_status[$key]) && '3' == $port_status[$key]) || (isset($port_status[$key]) && '5' == $port_status[$key])) { - $port_key_array[$i]['key'] = $key; - $port_key_array[$i]['port_number'] = $port_number; - - ++$i; - } - } - } - } - } - - /* compare the user ports to the bridge port data, store additional - relevant data about the port. - */ - $i = 0; - if (cacti_sizeof($port_key_array)) { - foreach ($port_key_array as $port_key) { - // map bridge port to interface port and check type - if ($port_key['port_number'] > 0) { - if (cacti_sizeof($bridgePortIfIndexes)) { - if (isset($bridgePortIfIndexes[$port_key['port_number']])) { - $brPortIfIndex = $bridgePortIfIndexes[$port_key['port_number']]; - } - if (isset($ifInterfaces[$brPortIfIndex]['ifType'])) { - $brPortIfType = $ifInterfaces[$brPortIfIndex]['ifType']; - } - } else { - $brPortIfIndex = $port_key['port_number']; - if (isset($ifInterfaces[$port_key['port_number']]['ifType'])) { - $brPortIfType = $ifInterfaces[$port_key['port_number']]['ifType']; - } - } - - if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || (71 == $brPortIfType)) { - // set some defaults - $new_port_key_array[$i]['vlan_id'] = 'N/A'; - $new_port_key_array[$i]['vlan_name'] = 'N/A'; - $new_port_key_array[$i]['mac_address'] = 'NOT USER'; - $new_port_key_array[$i]['port_number'] = 'NOT USER'; - $new_port_key_array[$i]['port_name'] = 'N/A'; - - // now set the real data - $new_port_key_array[$i]['key'] = $port_key['key']; - $new_port_key_array[$i]['port_number'] = $port_key['port_number']; - ++$i; - } - } - } - } - mactrack_debug('Port number information collected.'); - - // map mac address - // only continue if there were user ports defined - if (cacti_sizeof($new_port_key_array)) { - // get the bridges active MAC addresses - $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.1', $device, $snmp_readstring, true); - - if (cacti_sizeof($port_macs)) { - foreach ($port_macs as $key => $port_mac) { - $port_macs[$key] = xform_mac_address($port_mac); - } - } - - if (cacti_sizeof($new_port_key_array)) { - foreach ($new_port_key_array as $key => $port_key) { - if (isset($port_macs[$port_key['key']])) { - $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; - mactrack_debug("INDEX: '".$key."' MAC ADDRESS: ".$new_port_key_array[$key]['mac_address']); - } else { - mactrack_debug("INDEX: '".$key."' not found in port_macs array, skipping"); - } - } - } - - mactrack_debug('Port mac address information collected.'); - } else { - mactrack_debug('No user ports on this network.'); - } - } else { - mactrack_debug('No user ports on this network.'); - } - - if ($store_to_db) { - if ($ports_active <= 0) { - $device['last_runmessage'] = 'Data collection completed ok'; - } elseif (cacti_sizeof($new_port_key_array)) { - $device['last_runmessage'] = 'Data collection completed ok'; - $device['macs_active'] = cacti_sizeof($new_port_key_array); - db_store_device_port_results($device, $new_port_key_array, $scan_date); - } else { - $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; - } - } else { - return $new_port_key_array; - } +function get_base_dot1qTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_readstring = '', $store_to_db = true, $lowPort = 1, $highPort = 9999) { + global $debug, $scan_date; + + // initialize variables + $port_keys = []; + $return_array = []; + $new_port_key_array = []; + $port_key_array = []; + $port_number = 0; + $ports_active = 0; + $active_ports = 0; + $ports_total = 0; + + // cisco uses a hybrid read string, if one is not defined, use the default + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // get the operational status of the ports + $active_ports_array = xform_standard_indexed_data('.1.3.6.1.2.1.2.2.1.8', $device); + $indexes = array_keys($active_ports_array); + + $i = 0; + + if (cacti_sizeof($active_ports_array)) { + foreach ($active_ports_array as $port_info) { + $port_info = mactrack_strip_alpha($port_info); + + if ((($ifInterfaces[$indexes[$i]]['ifType'] >= 6) + && ($ifInterfaces[$indexes[$i]]['ifType'] <= 9)) + || ($ifInterfaces[$indexes[$i]]['ifType'] == 71)) { + if ($port_info == 1) { + ++$ports_active; + } + ++$ports_total; + } + ++$i; + } + } + $device['ports_active'] = $ports_active; + + if ($store_to_db) { + mactrack_debug('INFO: HOST: ' . $device['hostname'] . ', TYPE: ' . substr($device['snmp_sysDescr'], 0, 40) . ', TOTAL PORTS: ' . $ports_total . ', OPER PORTS: ' . $ports_active); + + $device['ports_total'] = $ports_total; + $device['macs_active'] = 0; + } + + if ($ports_active > 0) { + // get bridge port to ifIndex mapping + $bridgePortIfIndexes = xform_standard_indexed_data('.1.3.6.1.2.1.17.1.4.1.2', $device, $snmp_readstring); + + $port_status = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.3', $device, $snmp_readstring); + + // get device active port numbers + $port_numbers = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.2', $device, $snmp_readstring); + + // get the ignore ports list from device + $ignore_ports = port_list_to_array($device['ignorePorts']); + + // get the bridge root port so we don't capture active ports on it + $bridge_root_port = @cacti_snmp_get( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.2.7.0', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'] + ); + + /* determine user ports for this device and transfer user ports to + a new array. + */ + $i = 0; + + if (cacti_sizeof($port_numbers)) { + foreach ($port_numbers as $key => $port_number) { + if (($highPort == 0) + || (($port_number >= $lowPort) + && ($port_number <= $highPort) + && ($bridge_root_port != $port_number))) { + if (!in_array($port_number, $ignore_ports, true)) { + if ((isset($port_status[$key]) && $port_status[$key] == '3') || (isset($port_status[$key]) && $port_status[$key] == '5')) { + $port_key_array[$i]['key'] = $key; + $port_key_array[$i]['port_number'] = $port_number; + + ++$i; + } + } + } + } + } + + /* compare the user ports to the bridge port data, store additional + relevant data about the port. + */ + $i = 0; + + if (cacti_sizeof($port_key_array)) { + foreach ($port_key_array as $port_key) { + // map bridge port to interface port and check type + if ($port_key['port_number'] > 0) { + if (cacti_sizeof($bridgePortIfIndexes)) { + if (isset($bridgePortIfIndexes[$port_key['port_number']])) { + $brPortIfIndex = $bridgePortIfIndexes[$port_key['port_number']]; + } + + if (isset($ifInterfaces[$brPortIfIndex]['ifType'])) { + $brPortIfType = $ifInterfaces[$brPortIfIndex]['ifType']; + } + } else { + $brPortIfIndex = $port_key['port_number']; + + if (isset($ifInterfaces[$port_key['port_number']]['ifType'])) { + $brPortIfType = $ifInterfaces[$port_key['port_number']]['ifType']; + } + } + + if ((($brPortIfType >= 6) && ($brPortIfType <= 9)) || ($brPortIfType == 71)) { + // set some defaults + $new_port_key_array[$i]['vlan_id'] = 'N/A'; + $new_port_key_array[$i]['vlan_name'] = 'N/A'; + $new_port_key_array[$i]['mac_address'] = 'NOT USER'; + $new_port_key_array[$i]['port_number'] = 'NOT USER'; + $new_port_key_array[$i]['port_name'] = 'N/A'; + + // now set the real data + $new_port_key_array[$i]['key'] = $port_key['key']; + $new_port_key_array[$i]['port_number'] = $port_key['port_number']; + ++$i; + } + } + } + } + mactrack_debug('Port number information collected.'); + + // map mac address + // only continue if there were user ports defined + if (cacti_sizeof($new_port_key_array)) { + // get the bridges active MAC addresses + $port_macs = xform_stripped_oid('.1.3.6.1.2.1.17.7.1.2.2.1.1', $device, $snmp_readstring, true); + + if (cacti_sizeof($port_macs)) { + foreach ($port_macs as $key => $port_mac) { + $port_macs[$key] = xform_mac_address($port_mac); + } + } + + if (cacti_sizeof($new_port_key_array)) { + foreach ($new_port_key_array as $key => $port_key) { + if (isset($port_macs[$port_key['key']])) { + $new_port_key_array[$key]['mac_address'] = @$port_macs[$port_key['key']]; + mactrack_debug("INDEX: '" . $key . "' MAC ADDRESS: " . $new_port_key_array[$key]['mac_address']); + } else { + mactrack_debug("INDEX: '" . $key . "' not found in port_macs array, skipping"); + } + } + } + + mactrack_debug('Port mac address information collected.'); + } else { + mactrack_debug('No user ports on this network.'); + } + } else { + mactrack_debug('No user ports on this network.'); + } + + if ($store_to_db) { + if ($ports_active <= 0) { + $device['last_runmessage'] = 'Data collection completed ok'; + } elseif (cacti_sizeof($new_port_key_array)) { + $device['last_runmessage'] = 'Data collection completed ok'; + $device['macs_active'] = cacti_sizeof($new_port_key_array); + db_store_device_port_results($device, $new_port_key_array, $scan_date); + } else { + $device['last_runmessage'] = 'WARNING: Poller did not find active ports on this device.'; + } + } else { + return $new_port_key_array; + } } /** @@ -2004,247 +2017,241 @@ function get_base_dot1qTpFdbEntry_ports($site, &$device, &$ifInterfaces, $snmp_r * @param mixed $dns * @param mixed $timeout */ -function mactrack_get_dns_from_ip($ip, $dns, $timeout = 1000) -{ - // random transaction number (for routers etc to get the reply back) - $data = rand(10, 99); - - // trim it to 2 bytes - $data = substr($data, 0, 2); - - // create request header - $data .= "\1\0\0\1\0\0\0\0\0\0"; - - // split IP into octets - $octets = explode('.', $ip); +function mactrack_get_dns_from_ip($ip, $dns, $timeout = 1000) { + // random transaction number (for routers etc to get the reply back) + $data = rand(10, 99); - // perform a quick error check - if (4 != count($octets)) { - return 'ERROR'; - } + // trim it to 2 bytes + $data = substr($data, 0, 2); - // needs a byte to indicate the length of each segment of the request - for ($x = 3; $x >= 0; --$x) { - switch (strlen($octets[$x])) { - case 1: // 1 byte long segment - $data .= "\1"; + // create request header + $data .= "\1\0\0\1\0\0\0\0\0\0"; - break; + // split IP into octets + $octets = explode('.', $ip); - case 2: // 2 byte long segment - $data .= "\2"; + // perform a quick error check + if (count($octets) != 4) { + return 'ERROR'; + } - break; + // needs a byte to indicate the length of each segment of the request + for ($x = 3; $x >= 0; --$x) { + switch (strlen($octets[$x])) { + case 1: // 1 byte long segment + $data .= "\1"; - case 3: // 3 byte long segment - $data .= "\3"; + break; + case 2: // 2 byte long segment + $data .= "\2"; - break; + break; + case 3: // 3 byte long segment + $data .= "\3"; - default: // segment is too big, invalid IP - return 'ERROR'; - } + break; + default: // segment is too big, invalid IP + return 'ERROR'; + } - // and the segment itself - $data .= $octets[$x]; - } + // and the segment itself + $data .= $octets[$x]; + } - // and the final bit of the request - $data .= "\7in-addr\4arpa\0\0\x0C\0\1"; + // and the final bit of the request + $data .= "\7in-addr\4arpa\0\0\x0C\0\1"; - // create UDP socket - $handle = @fsockopen("udp://{$dns}", 53); + // create UDP socket + $handle = @fsockopen("udp://{$dns}", 53); - @stream_set_timeout($handle, floor($timeout / 1000), ($timeout * 1000) % 1000000); - @stream_set_blocking($handle, 1); + @stream_set_timeout($handle, floor($timeout / 1000), ($timeout * 1000) % 1000000); + @stream_set_blocking($handle, 1); - // send our request (and store request size so we can cheat later) - $requestsize = @fwrite($handle, $data); + // send our request (and store request size so we can cheat later) + $requestsize = @fwrite($handle, $data); - // get the response - $response = @fread($handle, 1000); + // get the response + $response = @fread($handle, 1000); - // check to see if it timed out - $info = stream_get_meta_data($handle); + // check to see if it timed out + $info = stream_get_meta_data($handle); - // close the socket - @fclose($handle); + // close the socket + @fclose($handle); - if ($info['timed_out']) { - return 'timed_out'; - } + if ($info['timed_out']) { + return 'timed_out'; + } - // more error handling - if ('' == $response) { - return $ip; - } + // more error handling + if ($response == '') { + return $ip; + } - // parse the response and find the response type - $type = @unpack('s', substr($response, $requestsize + 2)); + // parse the response and find the response type + $type = @unpack('s', substr($response, $requestsize + 2)); - if (0x0C00 == $type[1]) { - // set up our variables - $host = ''; - $len = 0; + if ($type[1] == 0x0C00) { + // set up our variables + $host = ''; + $len = 0; - /* set our pointer at the beginning of the hostname uses the request - size from earlier rather than work it out. - */ - $position = $requestsize + 12; + /* set our pointer at the beginning of the hostname uses the request + size from earlier rather than work it out. + */ + $position = $requestsize + 12; - // reconstruct the hostname - do { - // get segment size - $len = unpack('c', substr($response, $position)); + // reconstruct the hostname + do { + // get segment size + $len = unpack('c', substr($response, $position)); - // null terminated string, so length 0 = finished - if (0 == $len[1]) { - // return the hostname, without the trailing '.' - return substr($host, 0, strlen($host) - 1); - } + // null terminated string, so length 0 = finished + if ($len[1] == 0) { + // return the hostname, without the trailing '.' + return substr($host, 0, strlen($host) - 1); + } - // add the next segment to our host - $host .= substr($response, $position + 1, $len[1]).'.'; + // add the next segment to our host + $host .= substr($response, $position + 1, $len[1]) . '.'; - // move pointer on to the next segment - $position += $len[1] + 1; - } while (0 != $len); + // move pointer on to the next segment + $position += $len[1] + 1; + } while ($len != 0); - // error - return the hostname we constructed (without the . on the end) - return $ip; - } + // error - return the hostname we constructed (without the . on the end) + return $ip; + } - // error - return the hostname - return $ip; + // error - return the hostname + return $ip; } /* get_link_port_status - This function walks an the ip mib for ifIndexes with ip addresses aka link ports and then returns that list if ifIndexes with a true array value if an IP exists on that ifIndex. */ -function get_link_port_status(&$device) -{ - $return_array = []; - - $walk_array = cacti_snmp_walk( - $device['hostname'], - $device['snmp_readstring'], - '.1.3.6.1.2.1.4.20.1.2', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'] - ); - - if (cacti_sizeof($walk_array)) { - foreach ($walk_array as $walk_item) { - $return_array[$walk_item['value']] = true; - } - } - - return $return_array; +function get_link_port_status(&$device) { + $return_array = []; + + $walk_array = cacti_snmp_walk( + $device['hostname'], + $device['snmp_readstring'], + '.1.3.6.1.2.1.4.20.1.2', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + if (cacti_sizeof($walk_array)) { + foreach ($walk_array as $walk_item) { + $return_array[$walk_item['value']] = true; + } + } + + return $return_array; } /* xform_stripped_oid - This function walks an OID and then strips the seed OID from the complete oid. It returns the stripped oid as the key and the return value as the value of the resulting array */ -function xform_stripped_oid($oid, &$device, $snmp_readstring = '', $hex = false) -{ - $return_array = []; - - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - if ('3' == $device['snmp_version'] && substr_count($snmp_readstring, 'vlan-')) { - $snmp_context = $snmp_readstring; - } else { - $snmp_context = $device['snmp_context']; - } - - $walk_array = cacti_snmp_walk( - $device['hostname'], - $snmp_readstring, - $oid, - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $snmp_context, - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'], - SNMP_POLLER, - $device['snmp_engine_id'], - $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS - ); - - $oid = preg_replace('/^\./', '', $oid); - - $i = 0; - - if (cacti_sizeof($walk_array)) { - foreach ($walk_array as $walk_item) { - $key = $walk_item['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace($oid.'.', '', $key); - $return_array[$i]['key'] = $key; - $return_array[$i]['value'] = $walk_item['value']; - - ++$i; - } - } - - return array_rekey($return_array, 'key', 'value'); +function xform_stripped_oid($oid, &$device, $snmp_readstring = '', $hex = false) { + $return_array = []; + + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + if ($device['snmp_version'] == '3' && substr_count($snmp_readstring, 'vlan-')) { + $snmp_context = $snmp_readstring; + } else { + $snmp_context = $device['snmp_context']; + } + + $walk_array = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + $oid, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $snmp_context, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $oid = preg_replace('/^\./', '', $oid); + + $i = 0; + + if (cacti_sizeof($walk_array)) { + foreach ($walk_array as $walk_item) { + $key = $walk_item['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace($oid . '.', '', $key); + $return_array[$i]['key'] = $key; + $return_array[$i]['value'] = $walk_item['value']; + + ++$i; + } + } + + return array_rekey($return_array, 'key', 'value'); } /* xform_net_address - This function will return the IP address. If the agent or snmp returns a differently formatted IP address, then this function will convert it to dotted decimal notation and return. */ -function xform_net_address($ip_address) -{ - $ip_address = trim($ip_address); - - if (substr_count($ip_address, 'Network Address:')) { - $ip_address = trim(str_replace('Network Address:', '', $ip_address)); - } - - // Handle the binary format first - $length = strlen($ip_address); - if (4 == $length or 16 == $length) { - return inet_ntop(pack('A'.$length, $ip_address)); - } - // Adjust for HEX IP in form "0A 09 15 72" - $ip_address = str_replace(' ', ':', $ip_address); - - if (0 != substr_count($ip_address, ':')) { - if (strlen($ip_address) > 11) { - // ipv6, don't alter - } else { - $newaddr = ''; - $address = explode(':', $ip_address); - - foreach ($address as $index => $part) { - $newaddr .= (0 == $index ? '' : '.').hexdec($part); - } +function xform_net_address($ip_address) { + $ip_address = trim($ip_address); + + if (substr_count($ip_address, 'Network Address:')) { + $ip_address = trim(str_replace('Network Address:', '', $ip_address)); + } + + // Handle the binary format first + $length = strlen($ip_address); + + if ($length == 4 || $length == 16) { + return inet_ntop(pack('A' . $length, $ip_address)); + } + // Adjust for HEX IP in form "0A 09 15 72" + $ip_address = str_replace(' ', ':', $ip_address); + + if (substr_count($ip_address, ':') != 0) { + if (strlen($ip_address) > 11) { + // ipv6, don't alter + } else { + $newaddr = ''; + $address = explode(':', $ip_address); + + foreach ($address as $index => $part) { + $newaddr .= ($index == 0 ? '' : '.') . hexdec($part); + } - $ip_address = $newaddr; - } - } + $ip_address = $newaddr; + } + } - return $ip_address; + return $ip_address; } /** xform_mac_address - This function will take a variable that is either formatted as @@ -2253,31 +2260,30 @@ function xform_net_address($ip_address) * * @param mixed $mac_address */ -function xform_mac_address($mac_address) -{ - $max_address = trim($mac_address); +function xform_mac_address($mac_address) { + $max_address = trim($mac_address); - if ('' == $mac_address) { - $mac_address = 'NOT USER'; - } elseif (strlen($mac_address) > 10) { // return is in ascii - $max_address = str_replace( - ['HEX-00:', 'HEX-:', 'HEX-', '"', ' ', '-'], - ['', '', '', '', ':', ':'], - $mac_address - ); - } else { // return is hex - $mac = ''; + if ($mac_address == '') { + $mac_address = 'NOT USER'; + } elseif (strlen($mac_address) > 10) { // return is in ascii + $max_address = str_replace( + ['HEX-00:', 'HEX-:', 'HEX-', '"', ' ', '-'], + ['', '', '', '', ':', ':'], + $mac_address + ); + } else { // return is hex + $mac = ''; - for ($j = 0; $j < strlen($mac_address); ++$j) { - $mac .= bin2hex($mac_address[$j]).':'; - } + for ($j = 0; $j < strlen($mac_address); ++$j) { + $mac .= bin2hex($mac_address[$j]) . ':'; + } - $mac_address = $mac; - } + $mac_address = $mac; + } - $mac_address = str_replace(':', '', $max_address); + $mac_address = str_replace(':', '', $max_address); - return strtoupper($mac_address); + return strtoupper($mac_address); } /** @@ -2290,51 +2296,50 @@ function xform_mac_address($mac_address) * @param mixed $snmp_readstring * @param mixed $hex */ -function xform_standard_indexed_data($xformOID, &$device, $snmp_readstring = '', $hex = false) -{ - // get raw index data - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - if ('3' == $device['snmp_version'] && substr_count($snmp_readstring, 'vlan-')) { - $snmp_context = $snmp_readstring; - } else { - $snmp_context = $device['snmp_context']; - } - - $xformArray = cacti_snmp_walk( - $device['hostname'], - $snmp_readstring, - $xformOID, - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $snmp_context, - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'], - SNMP_POLLER, - $device['snmp_engine_id'], - $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS - ); - - $i = 0; - - if (cacti_sizeof($xformArray)) { - foreach ($xformArray as $xformItem) { - $perPos = strrpos($xformItem['oid'], '.'); - $xformItemID = substr($xformItem['oid'], $perPos + 1); - $xformArray[$i]['oid'] = $xformItemID; - ++$i; - } - } - - return array_rekey($xformArray, 'oid', 'value'); +function xform_standard_indexed_data($xformOID, &$device, $snmp_readstring = '', $hex = false) { + // get raw index data + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + if ($device['snmp_version'] == '3' && substr_count($snmp_readstring, 'vlan-')) { + $snmp_context = $snmp_readstring; + } else { + $snmp_context = $device['snmp_context']; + } + + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + $xformOID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $snmp_context, + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $i = 0; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + $perPos = strrpos($xformItem['oid'], '.'); + $xformItemID = substr($xformItem['oid'], $perPos + 1); + $xformArray[$i]['oid'] = $xformItemID; + ++$i; + } + } + + return array_rekey($xformArray, 'oid', 'value'); } /** @@ -2345,54 +2350,53 @@ function xform_standard_indexed_data($xformOID, &$device, $snmp_readstring = '', * @param mixed $device * @param mixed $snmp_readstring */ -function xform_dot1q_vlan_associations(&$device, $snmp_readstring = '') -{ - // get raw index data - if ('' == $snmp_readstring) { - $snmp_readstring = $device['snmp_readstring']; - } - - // initialize the output array - $output_array = []; - - // obtain vlan associations - $xformArray = cacti_snmp_walk( - $device['hostname'], - $snmp_readstring, - '.1.3.6.1.2.1.17.7.1.2.2.1.2', - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'] - ); - - $i = 0; - - if (cacti_sizeof($xformArray)) { - foreach ($xformArray as $xformItem) { - // peel off the beginning of the OID - $key = $xformItem['oid']; - $key = str_replace('iso', '1', $key); - $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); - - // now grab the VLAN - $perPos = strpos($key, '.'); - $output_array[$i]['vlan_id'] = substr($key, 0, $perPos); - - // save the key for association with the dot1d table - $output_array[$i]['key'] = substr($key, $perPos + 1); - ++$i; - } - } - - return array_rekey($output_array, 'key', 'vlan_id'); +function xform_dot1q_vlan_associations(&$device, $snmp_readstring = '') { + // get raw index data + if ($snmp_readstring == '') { + $snmp_readstring = $device['snmp_readstring']; + } + + // initialize the output array + $output_array = []; + + // obtain vlan associations + $xformArray = cacti_snmp_walk( + $device['hostname'], + $snmp_readstring, + '.1.3.6.1.2.1.17.7.1.2.2.1.2', + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + $i = 0; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + // peel off the beginning of the OID + $key = $xformItem['oid']; + $key = str_replace('iso', '1', $key); + $key = str_replace('1.3.6.1.2.1.17.7.1.2.2.1.2.', '', $key); + + // now grab the VLAN + $perPos = strpos($key, '.'); + $output_array[$i]['vlan_id'] = substr($key, 0, $perPos); + + // save the key for association with the dot1d table + $output_array[$i]['key'] = substr($key, $perPos + 1); + ++$i; + } + } + + return array_rekey($output_array, 'key', 'vlan_id'); } /** @@ -2403,42 +2407,41 @@ function xform_dot1q_vlan_associations(&$device, $snmp_readstring = '') * @param mixed $xformOID * @param mixed $device */ -function xform_cisco_workgroup_port_data($xformOID, &$device) -{ - // get raw index data - $xformArray = cacti_snmp_walk( - $device['hostname'], - $device['snmp_readstring'], - $xformOID, - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'] - ); - - $i = 0; - - if (cacti_sizeof($xformArray)) { - foreach ($xformArray as $xformItem) { - $perPos = strrpos($xformItem['oid'], '.'); - $xformItem_piece1 = substr($xformItem['oid'], $perPos + 1); - $xformItem_remainder = substr($xformItem['oid'], 0, $perPos); - $perPos = strrpos($xformItem_remainder, '.'); - $xformItem_piece2 = substr($xformItem_remainder, $perPos + 1); - $xformArray[$i]['oid'] = $xformItem_piece2.'/'.$xformItem_piece1; - - ++$i; - } - } - - return array_rekey($xformArray, 'oid', 'value'); +function xform_cisco_workgroup_port_data($xformOID, &$device) { + // get raw index data + $xformArray = cacti_snmp_walk( + $device['hostname'], + $device['snmp_readstring'], + $xformOID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'] + ); + + $i = 0; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + $perPos = strrpos($xformItem['oid'], '.'); + $xformItem_piece1 = substr($xformItem['oid'], $perPos + 1); + $xformItem_remainder = substr($xformItem['oid'], 0, $perPos); + $perPos = strrpos($xformItem_remainder, '.'); + $xformItem_piece2 = substr($xformItem_remainder, $perPos + 1); + $xformArray[$i]['oid'] = $xformItem_piece2 . '/' . $xformItem_piece1; + + ++$i; + } + } + + return array_rekey($xformArray, 'oid', 'value'); } /** @@ -2452,59 +2455,61 @@ function xform_cisco_workgroup_port_data($xformOID, &$device) * @param mixed $xformLevel * @param mixed $hex */ -function xform_indexed_data($xformOID, &$device, $xformLevel = 1, $hex = false) -{ - // get raw index data - $xformArray = cacti_snmp_walk( - $device['hostname'], - $device['snmp_readstring'], - $xformOID, - $device['snmp_version'], - $device['snmp_username'], - $device['snmp_password'], - $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], - $device['snmp_priv_protocol'], - $device['snmp_context'], - $device['snmp_port'], - $device['snmp_timeout'], - $device['snmp_retries'], - $device['max_oids'], - SNMP_POLLER, - $device['snmp_engine_id'], - $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS - ); - - $i = 0; - $output_array = []; - - if (cacti_sizeof($xformArray)) { - foreach ($xformArray as $xformItem) { - // break down key - $OID = $xformItem['oid']; - for ($j = 0; $j < $xformLevel; ++$j) { - $perPos = strrpos($OID, '.'); - $xformItem_piece[$j] = substr($OID, $perPos + 1); - $OID = substr($OID, 0, $perPos); - } - - // reassemble key - $key = ''; - for ($j = $xformLevel - 1; $j >= 0; --$j) { - $key .= $xformItem_piece[$j]; - if ($j > 0) { - $key .= '.'; - } - } - - $output_array[$i]['key'] = $key; - $output_array[$i]['value'] = $xformItem['value']; - - ++$i; - } - } - - return array_rekey($output_array, 'key', 'value'); +function xform_indexed_data($xformOID, &$device, $xformLevel = 1, $hex = false) { + // get raw index data + $xformArray = cacti_snmp_walk( + $device['hostname'], + $device['snmp_readstring'], + $xformOID, + $device['snmp_version'], + $device['snmp_username'], + $device['snmp_password'], + $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], + $device['snmp_priv_protocol'], + $device['snmp_context'], + $device['snmp_port'], + $device['snmp_timeout'], + $device['snmp_retries'], + $device['max_oids'], + SNMP_POLLER, + $device['snmp_engine_id'], + $hex ? SNMP_STRING_OUTPUT_HEX : SNMP_STRING_OUTPUT_GUESS + ); + + $i = 0; + $output_array = []; + + if (cacti_sizeof($xformArray)) { + foreach ($xformArray as $xformItem) { + // break down key + $OID = $xformItem['oid']; + + for ($j = 0; $j < $xformLevel; ++$j) { + $perPos = strrpos($OID, '.'); + $xformItem_piece[$j] = substr($OID, $perPos + 1); + $OID = substr($OID, 0, $perPos); + } + + // reassemble key + $key = ''; + + for ($j = $xformLevel - 1; $j >= 0; --$j) { + $key .= $xformItem_piece[$j]; + + if ($j > 0) { + $key .= '.'; + } + } + + $output_array[$i]['key'] = $key; + $output_array[$i]['value'] = $xformItem['value']; + + ++$i; + } + } + + return array_rekey($output_array, 'key', 'value'); } /** @@ -2514,22 +2519,21 @@ function xform_indexed_data($xformOID, &$device, $xformLevel = 1, $hex = false) * @param mixed $device_id * @param mixed $storepid */ -function db_process_add($device_id, $storepid = false) -{ - // store the PID if required - if ($storepid) { - $pid = getmypid(); - } else { - $pid = 0; - } - - // store pseudo process id in the database - db_execute_prepared( - 'REPLACE INTO mac_track_processes +function db_process_add($device_id, $storepid = false) { + // store the PID if required + if ($storepid) { + $pid = getmypid(); + } else { + $pid = 0; + } + + // store pseudo process id in the database + db_execute_prepared( + 'REPLACE INTO mac_track_processes (device_id, process_id, status, start_date) VALUES (?, ?, "Running", NOW())', - [$device_id, $pid] - ); + [$device_id, $pid] + ); } /** @@ -2538,13 +2542,12 @@ function db_process_add($device_id, $storepid = false) * * @param mixed $device_id */ -function db_process_remove($device_id) -{ - db_execute_prepared( - 'DELETE FROM mac_track_processes +function db_process_remove($device_id) { + db_execute_prepared( + 'DELETE FROM mac_track_processes WHERE device_id = ?', - [$device_id] - ); + [$device_id] + ); } /** @@ -2556,16 +2559,15 @@ function db_process_remove($device_id) * @param mixed $scan_date * @param mixed $start_time */ -function db_update_device_status(&$device, $host_up, $scan_date, $start_time) -{ - global $debug; +function db_update_device_status(&$device, $host_up, $scan_date, $start_time) { + global $debug; - $end_time = microtime(true); - $runduration = $end_time - $start_time; + $end_time = microtime(true); + $runduration = $end_time - $start_time; - if (true == $host_up) { - db_execute_prepared( - 'UPDATE mac_track_devices + if ($host_up == true) { + db_execute_prepared( + 'UPDATE mac_track_devices SET ports_total = ?, device_type_id = ?, scan_type = ?, vlans_total = ?, ports_active = ?, ports_trunk = ?, macs_active = ?, snmp_version = ?, snmp_readstring = ?, snmp_port = ?, snmp_timeout = ?, snmp_retries = ?, @@ -2575,34 +2577,34 @@ function db_update_device_status(&$device, $host_up, $scan_date, $start_time) snmp_sysUptime = ?, snmp_status = ?, last_runmessage = ?, last_rundate = ?, last_runduration = ? WHERE device_id = ?', - [ - $device['ports_total'], $device['device_type_id'], $device['scan_type'], $device['vlans_total'], - $device['ports_active'], $device['ports_trunk'], $device['macs_active'], $device['snmp_version'], - $device['snmp_readstring'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], - $device['max_oids'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], - $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_sysName'], - $device['snmp_sysLocation'], $device['snmp_sysContact'], $device['snmp_sysObjectID'], $device['snmp_sysDescr'], - $device['snmp_sysUptime'], $device['snmp_status'], $device['last_runmessage'], $scan_date, - round($runduration, 4), $device['device_id'], - ] - ); - } else { - db_execute_prepared( - 'UPDATE mac_track_devices + [ + $device['ports_total'], $device['device_type_id'], $device['scan_type'], $device['vlans_total'], + $device['ports_active'], $device['ports_trunk'], $device['macs_active'], $device['snmp_version'], + $device['snmp_readstring'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], + $device['max_oids'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], + $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_sysName'], + $device['snmp_sysLocation'], $device['snmp_sysContact'], $device['snmp_sysObjectID'], $device['snmp_sysDescr'], + $device['snmp_sysUptime'], $device['snmp_status'], $device['last_runmessage'], $scan_date, + round($runduration, 4), $device['device_id'], + ] + ); + } else { + db_execute_prepared( + 'UPDATE mac_track_devices SET snmp_status = ?, device_type_id = ?, scan_type = ?, vlans_total = 0, ports_active = 0, ports_trunk = 0, macs_active = 0, last_runmessage = "Device Unreachable", last_rundate = ?, last_runduration = ? WHERE device_id =?', - [ - $device['snmp_status'], - $device['device_type_id'], - $device['scan_type'], - $scan_date, - round($runduration, 4), - $device['device_id'], - ] - ); - } + [ + $device['snmp_status'], + $device['device_type_id'], + $device['scan_type'], + $scan_date, + round($runduration, 4), + $device['device_id'], + ] + ); + } } /** @@ -2614,1307 +2616,1300 @@ function db_update_device_status(&$device, $host_up, $scan_date, $start_time) * @param mixed $port_array * @param mixed $scan_date */ -function db_store_device_port_results(&$device, $port_array, $scan_date) -{ - global $debug; - - // output details to database - if (cacti_sizeof($port_array)) { - foreach ($port_array as $port_value) { - if ('NOT USER' != $port_value['port_number'] && 'NOT USER' != $port_value['mac_address'] && '' != $port_value['mac_address']) { - $mac_authorized = db_check_auth($port_value['mac_address']); - - mactrack_debug('MAC Address \''.$port_value['mac_address'].'\' on device \''.$device['device_name'].'\' is '.('' != $mac_authorized ? '' : 'NOT ').'Authorized'); - - if ('' != $mac_authorized) { - $authorized_mac = 1; - } else { - $authorized_mac = 0; - } - - if (!isset($port_value['vlan_id'])) { - $port_value['vlan_id'] = 'N/A'; - } - - if (!isset($port_value['vlan_name'])) { - $port_value['vlan_name'] = 'N/A'; - } - - db_execute_prepared( - 'REPLACE INTO mac_track_temp_ports +function db_store_device_port_results(&$device, $port_array, $scan_date) { + global $debug; + + // output details to database + if (cacti_sizeof($port_array)) { + foreach ($port_array as $port_value) { + if ($port_value['port_number'] != 'NOT USER' && $port_value['mac_address'] != 'NOT USER' && $port_value['mac_address'] != '') { + $mac_authorized = db_check_auth($port_value['mac_address']); + + mactrack_debug('MAC Address \'' . $port_value['mac_address'] . '\' on device \'' . $device['device_name'] . '\' is ' . ($mac_authorized != '' ? '' : 'NOT ') . 'Authorized'); + + if ($mac_authorized != '') { + $authorized_mac = 1; + } else { + $authorized_mac = 0; + } + + if (!isset($port_value['vlan_id'])) { + $port_value['vlan_id'] = 'N/A'; + } + + if (!isset($port_value['vlan_name'])) { + $port_value['vlan_name'] = 'N/A'; + } + + db_execute_prepared( + 'REPLACE INTO mac_track_temp_ports (site_id,device_id,hostname,device_name,vlan_id,vlan_name, mac_address,port_number,port_name,scan_date,authorized) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', - [ - $device['site_id'], - $device['device_id'], - $device['hostname'], - $device['device_name'], - $port_value['vlan_id'], - $port_value['vlan_name'], - $port_value['mac_address'], - $port_value['port_number'], - $port_value['port_name'], - $scan_date, - $authorized_mac, - ] - ); - } - } - } + [ + $device['site_id'], + $device['device_id'], + $device['hostname'], + $device['device_name'], + $port_value['vlan_id'], + $port_value['vlan_name'], + $port_value['mac_address'], + $port_value['port_number'], + $port_value['port_name'], + $scan_date, + $authorized_mac, + ] + ); + } + } + } } // db_check_auth - This function checks whether the mac address exists in the mac_track+macauth table -function db_check_auth($mac_address) -{ - return db_fetch_cell_prepared( - 'SELECT mac_id +function db_check_auth($mac_address) { + return db_fetch_cell_prepared( + 'SELECT mac_id FROM mac_track_macauth WHERE mac_address LIKE ?', - ['%'.$mac_address.'%'] - ); + ['%' . $mac_address . '%'] + ); } // db_check_for_ip - This function checks whether the mac address has a matching IP address in the mac_track_arp table -function db_check_for_ip($mac_address) -{ - return db_fetch_cell_prepared( - 'SELECT ip_address +function db_check_for_ip($mac_address) { + return db_fetch_cell_prepared( + 'SELECT ip_address FROM mac_track_arp WHERE mac_address LIKE ?', - ['%'.$mac_address.'%'] - ); + ['%' . $mac_address . '%'] + ); } /** * perform_mactrack_db_maint - This utility removes stale records from the database. */ -function perform_mactrack_db_maint() -{ - global $database_default; - - // remove stale records from the poller database - $retention = read_config_option('mt_data_retention'); - if (is_numeric($retention)) { - $retention_date = date('Y-m-d H:i:s', time() - ($retention * 86400)); - $days = $retention; - } else { - switch ($retention) { - case '2days': - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); - - break; - - case '5days': - $retention_date = date('Y-m-d H:i:s', strtotime('-5 Days')); - - break; - - case '1week': - $retention_date = date('Y-m-d H:i:s', strtotime('-1 Week')); - - break; - - case '2weeks': - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Week')); - - break; - - case '3weeks': - $retention_date = date('Y-m-d H:i:s', strtotime('-3 Week')); - - break; - - case '1month': - $retention_date = date('Y-m-d H:i:s', strtotime('-1 Month')); - - break; - - case '2months': - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Months')); - - break; - - default: - $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); - } - - $days = ceil((time() - strtotime($retention_date)) / 86400); - } - - set_config_option('mt_data_retention', $days); - - mactrack_debug('Started deleting old records from the main database.'); - - $syntax = db_fetch_row('SHOW CREATE TABLE mac_track_ports'); - if (substr_count($syntax['Create Table'], 'PARTITION')) { - $partitioned = true; - } else { - $partitioned = false; - } - - // delete old syslog and syslog soft messages - if ($retention > 0 || $partitioned) { - if (!$partitioned) { - db_execute_prepared('DELETE QUICK FROM mac_track_ports WHERE scan_date < ?', [$retention_date]); - db_execute('OPTIMIZE TABLE mac_track_ports'); - } else { - $syslog_deleted = 0; - $number_of_partitions = db_fetch_assoc_prepared( - 'SELECT * +function perform_mactrack_db_maint() { + global $database_default; + + // remove stale records from the poller database + $retention = read_config_option('mt_data_retention'); + + if (is_numeric($retention)) { + $retention_date = date('Y-m-d H:i:s', time() - ($retention * 86400)); + $days = $retention; + } else { + switch ($retention) { + case '2days': + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); + + break; + case '5days': + $retention_date = date('Y-m-d H:i:s', strtotime('-5 Days')); + + break; + case '1week': + $retention_date = date('Y-m-d H:i:s', strtotime('-1 Week')); + + break; + case '2weeks': + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Week')); + + break; + case '3weeks': + $retention_date = date('Y-m-d H:i:s', strtotime('-3 Week')); + + break; + case '1month': + $retention_date = date('Y-m-d H:i:s', strtotime('-1 Month')); + + break; + case '2months': + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Months')); + + break; + default: + $retention_date = date('Y-m-d H:i:s', strtotime('-2 Days')); + } + + $days = ceil((time() - strtotime($retention_date)) / 86400); + } + + set_config_option('mt_data_retention', $days); + + mactrack_debug('Started deleting old records from the main database.'); + + $syntax = db_fetch_row('SHOW CREATE TABLE mac_track_ports'); + + if (substr_count($syntax['Create Table'], 'PARTITION')) { + $partitioned = true; + } else { + $partitioned = false; + } + + // delete old syslog and syslog soft messages + if ($retention > 0 || $partitioned) { + if (!$partitioned) { + db_execute_prepared('DELETE QUICK FROM mac_track_ports WHERE scan_date < ?', [$retention_date]); + db_execute('OPTIMIZE TABLE mac_track_ports'); + } else { + $syslog_deleted = 0; + $number_of_partitions = db_fetch_assoc_prepared( + 'SELECT * FROM `information_schema`.`partitions` WHERE table_schema = ? AND table_name="mac_track_ports" ORDER BY partition_ordinal_position', - [$database_default] - ); - - /* - $time = time(); - $now = date('Y-m-d', $time); - $format = date('Ymd', $time); - $cur_day = db_fetch_row("SELECT TO_DAYS('$now') AS today"); - $cur_day = $cur_day['today']; - - $lday_ts = read_config_option('mactrack_lastday_timestamp'); - $lnow = date('Y-m-d', $lday_ts); - $lformat = date('Ymd', $lday_ts); - $last_day = db_fetch_row("SELECT TO_DAYS('$lnow') AS today"); - $last_day = $last_day['today']; - */ - - $tday_ts = strtotime('Today'); - $tday = date('Y-m-d', $tday_ts); - $tdformat = date('Ymd', $tday_ts); - $cur_day = db_fetch_row("SELECT TO_DAYS('{$tday}') AS today"); - $cur_day = $cur_day['today']; - - $lday_ts = strtotime('Yesterday'); - $lday = date('Y-m-d', $lday_ts); - $ldformat = date('Ymd', $lday_ts); - $last_day = db_fetch_row("SELECT TO_DAYS('{$lday}') AS today"); - $last_day = $last_day['today']; - - mactrack_debug("There are currently '".cacti_sizeof($number_of_partitions)."' Mactrack Partitions, We will keep '{$days}' of them."); - mactrack_debug("The current day is '{$tday}({$cur_day})', the last day is '{$lday}({$last_day})'"); - - if ($cur_day != $last_day) { - // set_config_option('mactrack_lastday_timestamp', $time); //no use - - if ('' != $lday_ts) { - cacti_log("MACTRACK: Creating new partition 'd".$ldformat."'", false, 'SYSTEM'); - mactrack_debug("Creating new partition 'd".$ldformat."'"); - db_execute('ALTER TABLE mac_track_ports REORGANIZE PARTITION dMaxValue INTO ( - PARTITION d'.$ldformat." VALUES LESS THAN ({$cur_day}), + [$database_default] + ); + + /* + $time = time(); + $now = date('Y-m-d', $time); + $format = date('Ymd', $time); + $cur_day = db_fetch_row("SELECT TO_DAYS('$now') AS today"); + $cur_day = $cur_day['today']; + + $lday_ts = read_config_option('mactrack_lastday_timestamp'); + $lnow = date('Y-m-d', $lday_ts); + $lformat = date('Ymd', $lday_ts); + $last_day = db_fetch_row("SELECT TO_DAYS('$lnow') AS today"); + $last_day = $last_day['today']; + */ + + $tday_ts = strtotime('Today'); + $tday = date('Y-m-d', $tday_ts); + $tdformat = date('Ymd', $tday_ts); + $cur_day = db_fetch_row("SELECT TO_DAYS('{$tday}') AS today"); + $cur_day = $cur_day['today']; + + $lday_ts = strtotime('Yesterday'); + $lday = date('Y-m-d', $lday_ts); + $ldformat = date('Ymd', $lday_ts); + $last_day = db_fetch_row("SELECT TO_DAYS('{$lday}') AS today"); + $last_day = $last_day['today']; + + mactrack_debug("There are currently '" . cacti_sizeof($number_of_partitions) . "' Mactrack Partitions, We will keep '{$days}' of them."); + mactrack_debug("The current day is '{$tday}({$cur_day})', the last day is '{$lday}({$last_day})'"); + + if ($cur_day != $last_day) { + // set_config_option('mactrack_lastday_timestamp', $time); //no use + + if ($lday_ts != '') { + cacti_log("MACTRACK: Creating new partition 'd" . $ldformat . "'", false, 'SYSTEM'); + mactrack_debug("Creating new partition 'd" . $ldformat . "'"); + db_execute('ALTER TABLE mac_track_ports REORGANIZE PARTITION dMaxValue INTO ( + PARTITION d' . $ldformat . " VALUES LESS THAN ({$cur_day}), PARTITION dMaxValue VALUES LESS THAN MAXVALUE)"); - if ($days > 0) { - /* - $user_partitions = cacti_sizeof($number_of_partitions) - 1; - if ($user_partitions >= $days) { - $i = 0; - while ($user_partitions > $days) { - $oldest = $number_of_partitions[$i]; - cacti_log("MACTRACK: Removing old partition 'd" . $oldest["PARTITION_NAME"] . "'", false, "SYSTEM"); - mactrack_debug("Removing partition '" . $oldest['PARTITION_NAME'] . "'"); - db_execute("ALTER TABLE mac_track_ports DROP PARTITION " . $oldest['PARTITION_NAME']); - $i++; - $user_partitions--; - $mactrack_deleted++; - } - } - */ - - $old_day = date('Ymd', strtotime("- {$days} Days")); - $old_partitions = db_fetch_assoc_prepared( - 'SELECT PARTITION_NAME + if ($days > 0) { + /* + $user_partitions = cacti_sizeof($number_of_partitions) - 1; + if ($user_partitions >= $days) { + $i = 0; + while ($user_partitions > $days) { + $oldest = $number_of_partitions[$i]; + cacti_log("MACTRACK: Removing old partition 'd" . $oldest["PARTITION_NAME"] . "'", false, "SYSTEM"); + mactrack_debug("Removing partition '" . $oldest['PARTITION_NAME'] . "'"); + db_execute("ALTER TABLE mac_track_ports DROP PARTITION " . $oldest['PARTITION_NAME']); + $i++; + $user_partitions--; + $mactrack_deleted++; + } + } + */ + + $old_day = date('Ymd', strtotime("- {$days} Days")); + $old_partitions = db_fetch_assoc_prepared( + 'SELECT PARTITION_NAME FROM `information_schema`.`partitions` WHERE table_schema = ? AND table_name="mac_track_ports" AND partition_name < ? ORDER BY partition_ordinal_position', - [$database_default, 'd'.$old_day] - ); - - if (cacti_sizeof($old_partitions) > 0) { - foreach ($old_partitions as $old_partition) { - cacti_log("MACTRACK: Removing old partition '".$old_partition['PARTITION_NAME']."'", false, 'SYSTEM'); - mactrack_debug("Removing partition '".$old_partition['PARTITION_NAME']."'"); - db_execute('ALTER TABLE mac_track_ports DROP PARTITION '.$old_partition['PARTITION_NAME']); - } - } - } - } - } - } - } - - db_execute_prepared( - 'DELETE FROM mac_track_ips + [$database_default, 'd' . $old_day] + ); + + if (cacti_sizeof($old_partitions) > 0) { + foreach ($old_partitions as $old_partition) { + cacti_log("MACTRACK: Removing old partition '" . $old_partition['PARTITION_NAME'] . "'", false, 'SYSTEM'); + mactrack_debug("Removing partition '" . $old_partition['PARTITION_NAME'] . "'"); + db_execute('ALTER TABLE mac_track_ports DROP PARTITION ' . $old_partition['PARTITION_NAME']); + } + } + } + } + } + } + } + + db_execute_prepared( + 'DELETE FROM mac_track_ips WHERE scan_date < DATE_FORMAT(CURDATE() - ?,"%Y-%m-%d")', - [read_config_option('mt_data_retention_ip')] - ); - db_execute('OPTIMIZE TABLE mac_track_ips'); + [read_config_option('mt_data_retention_ip')] + ); + db_execute('OPTIMIZE TABLE mac_track_ips'); - db_execute('REPLACE INTO mac_track_scan_dates + db_execute('REPLACE INTO mac_track_scan_dates (SELECT DISTINCT scan_date FROM mac_track_ports)'); - db_execute('DELETE FROM mac_track_scan_dates + db_execute('DELETE FROM mac_track_scan_dates WHERE scan_date NOT IN ( SELECT DISTINCT scan_date FROM mac_track_ports )'); - mactrack_debug('Finished deleting old records from the main database.'); -} - -function import_oui_database($type = 'ui', $oui_file = 'http://standards-oui.ieee.org/oui.txt') -{ - $oui_alternate = 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-L&format=txt'; - if ('ui' != $type) { - html_start_box(__('Mactrack Device Tracking OUI Database Import Results', 'mactrack'), '100%', '', '1', 'center', ''); - echo ''.__('Getting OUI Database from IEEE', 'mactrack').''; - } else { - echo __('Getting OUI Database from the IEEE', 'mactrack').PHP_EOL; - } - - $proxy = read_config_option('settings_proxy_server'); - $proxy_user = read_config_option('settings_proxy_user'); - $proxy_password = read_config_option('settings_proxy_password'); - - if ('' != $proxy) { - $default_opts = [ - 'http' => [ - 'proxy' => $proxy, - 'method' => 'GET', - ], - ]; - - if ('' != $proxy_user) { - $default_opts = [ - 'http' => [ - 'header' => 'Proxy-Authorization: Basic '.base64_encode("{$proxy_user}:{$proxy_password}"), - ], - ]; - } - - $default = stream_context_set_default($default_opts); - } - - $oui_database = file($oui_file); - - if ('ui' != $type) { - echo ''; - } - - if (is_array($oui_database)) { - echo __('OUI Database Download from IEEE Complete', 'mactrack').PHP_EOL; - } else { - echo __('OUI Database Download from IEEE FAILED', 'mactrack').PHP_EOL; - } - - if ('ui' != $type) { - echo ''; - } - - if (is_array($oui_database)) { - db_execute('UPDATE mac_track_oui_database SET present=0'); - - // initialize some variables - $begin_vendor = false; - $vendor_mac = ''; - $vendor_name = ''; - $vendor_address = ''; - $i = 0; - $sql = ''; - - if ('ui' != $type) { - echo ''; - } - - if (cacti_sizeof($oui_database)) { - foreach ($oui_database as $row) { - $row = str_replace("\t", ' ', $row); - if ($begin_vendor && '' == trim($row)) { - if (',' == substr($vendor_address, 0, 1)) { - $vendor_address = substr($vendor_address, 1); - } - if (',' == substr($vendor_name, 0, 1)) { - $vendor_name = substr($vendor_name, 1); - } - - $sql .= ('' != $sql ? ',' : '') - .'(' - .db_qstr($vendor_mac).', ' - .db_qstr(ucwords(strtolower($vendor_name))).', ' - .db_qstr(str_replace("\n", ', ', ucwords(strtolower(trim($vendor_address))))).', 1)'; - - // let the user know you are working - if ((($i % 1000) == 0) && ('ui' == $type)) { - echo '.'; - - db_execute('REPLACE INTO mac_track_oui_database + mactrack_debug('Finished deleting old records from the main database.'); +} + +function import_oui_database($type = 'ui', $oui_file = 'http://standards-oui.ieee.org/oui.txt') { + $oui_alternate = 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-L&format=txt'; + + if ($type != 'ui') { + html_start_box(__('Mactrack Device Tracking OUI Database Import Results', 'mactrack'), '100%', '', '1', 'center', ''); + print '' . __('Getting OUI Database from IEEE', 'mactrack') . ''; + } else { + print __('Getting OUI Database from the IEEE', 'mactrack') . PHP_EOL; + } + + $proxy = read_config_option('settings_proxy_server'); + $proxy_user = read_config_option('settings_proxy_user'); + $proxy_password = read_config_option('settings_proxy_password'); + + if ($proxy != '') { + $default_opts = [ + 'http' => [ + 'proxy' => $proxy, + 'method' => 'GET', + ], + ]; + + if ($proxy_user != '') { + $default_opts = [ + 'http' => [ + 'header' => 'Proxy-Authorization: Basic ' . base64_encode("{$proxy_user}:{$proxy_password}"), + ], + ]; + } + + $default = stream_context_set_default($default_opts); + } + + $oui_database = file($oui_file); + + if ($type != 'ui') { + print ''; + } + + if (is_array($oui_database)) { + print __('OUI Database Download from IEEE Complete', 'mactrack') . PHP_EOL; + } else { + print __('OUI Database Download from IEEE FAILED', 'mactrack') . PHP_EOL; + } + + if ($type != 'ui') { + print ''; + } + + if (is_array($oui_database)) { + db_execute('UPDATE mac_track_oui_database SET present=0'); + + // initialize some variables + $begin_vendor = false; + $vendor_mac = ''; + $vendor_name = ''; + $vendor_address = ''; + $i = 0; + $sql = ''; + + if ($type != 'ui') { + print ''; + } + + if (cacti_sizeof($oui_database)) { + foreach ($oui_database as $row) { + $row = str_replace("\t", ' ', $row); + + if ($begin_vendor && trim($row) == '') { + if (substr($vendor_address, 0, 1) == ',') { + $vendor_address = substr($vendor_address, 1); + } + + if (substr($vendor_name, 0, 1) == ',') { + $vendor_name = substr($vendor_name, 1); + } + + $sql .= ($sql != '' ? ',' : '') + . '(' + . db_qstr($vendor_mac) . ', ' + . db_qstr(ucwords(strtolower($vendor_name))) . ', ' + . db_qstr(str_replace("\n", ', ', ucwords(strtolower(trim($vendor_address))))) . ', 1)'; + + // let the user know you are working + if ((($i % 1000) == 0) && ($type == 'ui')) { + print '.'; + + db_execute('REPLACE INTO mac_track_oui_database (vendor_mac, vendor_name, vendor_address, present) - VALUES '.$sql); - - $sql = ''; - } - - ++$i; - - // reinitialize variables - $begin_vendor = false; - $vendor_mac = ''; - $vendor_name = ''; - $vendor_address = ''; - } else { - if ($begin_vendor) { - if (strpos($row, '(base 16)')) { - $address_start = strpos($row, '(base 16)') + 10; - $vendor_address .= trim(substr($row, $address_start))."\n"; - } else { - $vendor_address .= trim($row)."\n"; - } - } else { - $vendor_address = ''; - } - } - - if (substr_count($row, '(hex)')) { - $begin_vendor = true; - $vendor_mac = str_replace('-', '', substr(trim($row), 0, 8)); - $hex_end = strpos($row, '(hex)') + 5; - $vendor_name = trim(substr($row, $hex_end)); - } - } - } - - if ('' != $sql) { - db_execute('REPLACE INTO mac_track_oui_database + VALUES ' . $sql); + + $sql = ''; + } + + ++$i; + + // reinitialize variables + $begin_vendor = false; + $vendor_mac = ''; + $vendor_name = ''; + $vendor_address = ''; + } else { + if ($begin_vendor) { + if (strpos($row, '(base 16)')) { + $address_start = strpos($row, '(base 16)') + 10; + $vendor_address .= trim(substr($row, $address_start)) . "\n"; + } else { + $vendor_address .= trim($row) . "\n"; + } + } else { + $vendor_address = ''; + } + } + + if (substr_count($row, '(hex)')) { + $begin_vendor = true; + $vendor_mac = str_replace('-', '', substr(trim($row), 0, 8)); + $hex_end = strpos($row, '(hex)') + 5; + $vendor_name = trim(substr($row, $hex_end)); + } + } + } + + if ($sql != '') { + db_execute('REPLACE INTO mac_track_oui_database (vendor_mac, vendor_name, vendor_address, present) - VALUES '.$sql); - } - - if ('ui' != $type) { - echo ''; - } - - // count bogus records - $j = db_fetch_cell('SELECT count(*) FROM mac_track_oui_database WHERE present=0'); - - // get rid of old records - db_execute('DELETE FROM mac_track_oui_database WHERE present=0'); - - // set correct format - db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); - - // report some information - if ('ui' != $type) { - echo ''; - } - echo PHP_EOL.__('There were \'%d\' Entries Added/Updated in the database.', $i, 'mactrack'); - if ('ui' != $type) { - echo ''; - } - echo PHP_EOL.__('There were \'%d\' Records Removed from the database.', $j, 'mactrack').PHP_EOL; - if ('ui' != $type) { - echo ''; - } - - if ('ui' != $type) { - html_end_box(); - } - } -} - -function get_netscreen_arp_table($site, &$device) -{ - global $debug, $scan_date; - - // get the atifIndexes for the device - $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.3.1.1.1', $device, 6); - - if (cacti_sizeof($atifIndexes)) { - $ifIntcount = 1; - } else { - $ifIntcount = 0; - } - - if (0 != $ifIntcount) { - $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.4.22.1.1', $device, 5); - } - mactrack_debug(__('atifIndexes data collection complete', 'mactrack')); - - // get the atPhysAddress for the device - if (0 != $ifIntcount) { - $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.2', $device, 5, true); - } else { - $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.2', $device, 6, true); - } - - // convert the mac address if necessary - $keys = array_keys($atPhysAddress); - $i = 0; - if (cacti_sizeof($atPhysAddress)) { - foreach ($atPhysAddress as $atAddress) { - $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); - ++$i; - } - } - mactrack_debug(__('atPhysAddress data collection complete', 'mactrack')); - - // get the atPhysAddress for the device - if (0 != $ifIntcount) { - $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.3', $device, 5); - } else { - $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.3', $device, 6); - } - mactrack_debug(__('atNetAddress data collection complete', 'mactrack')); - - // get the ifNames for the device - $keys = array_keys($atifIndexes); - $i = 0; - if (cacti_sizeof($atifIndexes)) { - foreach ($atifIndexes as $atifIndex) { - $atEntries[$i]['atifIndex'] = $atifIndex; - $atEntries[$i]['atPhysAddress'] = $atPhysAddress[$keys[$i]]; - $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$keys[$i]]); - ++$i; - } - } - mactrack_debug(__('atEntries assembly complete.', 'mactrack')); - - // output details to database - if (cacti_sizeof($atEntries)) { - foreach ($atEntries as $atEntry) { - db_execute_prepared( - 'REPLACE INTO mac_track_ips + VALUES ' . $sql); + } + + if ($type != 'ui') { + print ''; + } + + // count bogus records + $j = db_fetch_cell('SELECT count(*) FROM mac_track_oui_database WHERE present=0'); + + // get rid of old records + db_execute('DELETE FROM mac_track_oui_database WHERE present=0'); + + // set correct format + db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); + + // report some information + if ($type != 'ui') { + print ''; + } + print PHP_EOL . __('There were \'%d\' Entries Added/Updated in the database.', $i, 'mactrack'); + + if ($type != 'ui') { + print ''; + } + print PHP_EOL . __('There were \'%d\' Records Removed from the database.', $j, 'mactrack') . PHP_EOL; + + if ($type != 'ui') { + print ''; + } + + if ($type != 'ui') { + html_end_box(); + } + } +} + +function get_netscreen_arp_table($site, &$device) { + global $debug, $scan_date; + + // get the atifIndexes for the device + $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.3.1.1.1', $device, 6); + + if (cacti_sizeof($atifIndexes)) { + $ifIntcount = 1; + } else { + $ifIntcount = 0; + } + + if ($ifIntcount != 0) { + $atifIndexes = xform_indexed_data('.1.3.6.1.2.1.4.22.1.1', $device, 5); + } + mactrack_debug(__('atifIndexes data collection complete', 'mactrack')); + + // get the atPhysAddress for the device + if ($ifIntcount != 0) { + $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.2', $device, 5, true); + } else { + $atPhysAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.2', $device, 6, true); + } + + // convert the mac address if necessary + $keys = array_keys($atPhysAddress); + $i = 0; + + if (cacti_sizeof($atPhysAddress)) { + foreach ($atPhysAddress as $atAddress) { + $atPhysAddress[$keys[$i]] = xform_mac_address($atAddress); + ++$i; + } + } + mactrack_debug(__('atPhysAddress data collection complete', 'mactrack')); + + // get the atPhysAddress for the device + if ($ifIntcount != 0) { + $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.4.22.1.3', $device, 5); + } else { + $atNetAddress = xform_indexed_data('.1.3.6.1.2.1.3.1.1.3', $device, 6); + } + mactrack_debug(__('atNetAddress data collection complete', 'mactrack')); + + // get the ifNames for the device + $keys = array_keys($atifIndexes); + $i = 0; + + if (cacti_sizeof($atifIndexes)) { + foreach ($atifIndexes as $atifIndex) { + $atEntries[$i]['atifIndex'] = $atifIndex; + $atEntries[$i]['atPhysAddress'] = $atPhysAddress[$keys[$i]]; + $atEntries[$i]['atNetAddress'] = xform_net_address($atNetAddress[$keys[$i]]); + ++$i; + } + } + mactrack_debug(__('atEntries assembly complete.', 'mactrack')); + + // output details to database + if (cacti_sizeof($atEntries)) { + foreach ($atEntries as $atEntry) { + db_execute_prepared( + 'REPLACE INTO mac_track_ips (site_id,device_id,hostname,device_name,port_number, mac_address,ip_address,scan_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - [ - $device['site_id'], - $device['device_id'], - $device['hostname'], - $device['device_name'], - $atEntry['atifIndex'], - $atEntry['atPhysAddress'], - $atEntry['atNetAddress'], - $scan_date, - ] - ); - } - } - - // save ip information for the device - $device['ips_total'] = cacti_sizeof($atEntries); - - db_execute_prepared( - 'UPDATE mac_track_devices + [ + $device['site_id'], + $device['device_id'], + $device['hostname'], + $device['device_name'], + $atEntry['atifIndex'], + $atEntry['atPhysAddress'], + $atEntry['atNetAddress'], + $scan_date, + ] + ); + } + } + + // save ip information for the device + $device['ips_total'] = cacti_sizeof($atEntries); + + db_execute_prepared( + 'UPDATE mac_track_devices SET ips_total = ? WHERE device_id = ?', - [$device['ips_total'], $device['device_id']] - ); + [$device['ips_total'], $device['device_id']] + ); - mactrack_debug(__('HOST: %s, IP address information collection complete', $device['hostname'], 'mactrack')); + mactrack_debug(__('HOST: %s, IP address information collection complete', $device['hostname'], 'mactrack')); } -function mactrack_interface_actions($device_id, $ifIndex, $show_rescan = true) -{ - global $config; +function mactrack_interface_actions($device_id, $ifIndex, $show_rescan = true) { + global $config; - $row = ''; - $rescan = ''; + $row = ''; + $rescan = ''; - $device = db_fetch_row_prepared( - 'SELECT host_id, disabled + $device = db_fetch_row_prepared( + 'SELECT host_id, disabled FROM mac_track_devices WHERE device_id = ?', - [$device_id] - ); - - if ($show_rescan) { - if (api_user_realm_auth('mactrack_sites.php')) { - if ('' == $device['disabled']) { - $rescan = ""; - } - } - } - - if (0 != $device['host_id']) { - // get non-interface graphs - $graphs = db_fetch_assoc_prepared( - 'SELECT DISTINCT gl.id AS local_graph_id + [$device_id] + ); + + if ($show_rescan) { + if (api_user_realm_auth('mactrack_sites.php')) { + if ($device['disabled'] == '') { + $rescan = ""; + } + } + } + + if ($device['host_id'] != 0) { + // get non-interface graphs + $graphs = db_fetch_assoc_prepared( + 'SELECT DISTINCT gl.id AS local_graph_id FROM mac_track_interface_graphs AS mtig RIGHT JOIN graph_local AS gl ON gl.host_id=mtig.host_id AND gl.id=mtig.local_graph_id WHERE gl.host_id = ? AND mtig.device_id IS NULL', - [$device['host_id']] - ); - - if (cacti_sizeof($graphs)) { - $url = $config['url_path'].'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; - $list = ''; - foreach ($graphs as $graph) { - $list .= ('' != $list ? ',' : '').$graph['local_graph_id']; - } - - $row .= ""; - } else { - $row .= ""; - } - - // get interface graphs - $graphs = db_fetch_assoc_prepared( - 'SELECT local_graph_id + [$device['host_id']] + ); + + if (cacti_sizeof($graphs)) { + $url = $config['url_path'] . 'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; + $list = ''; + + foreach ($graphs as $graph) { + $list .= ($list != '' ? ',' : '') . $graph['local_graph_id']; + } + + $row .= ""; + } else { + $row .= ""; + } + + // get interface graphs + $graphs = db_fetch_assoc_prepared( + 'SELECT local_graph_id FROM mac_track_interface_graphs WHERE host_id = ? AND ifIndex = ?', - [$device['host_id'], $ifIndex] - ); - - if (cacti_sizeof($graphs)) { - $url = $config['url_path'].'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; - $list = ''; - foreach ($graphs as $graph) { - $list .= ('' != $list ? ',' : '').$graph['local_graph_id']; - } - - $row .= ""; - } else { - $row .= ""; - } - } - - $row .= $rescan; - - return $row; -} - -function mactrack_format_interface_row($stat) -{ - global $config; - - // we will make a row string - $row = ''; - - // calculate a human readable uptime - if (0 == $stat['ifLastChange']) { - $upTime = __('Since Restart', 'mactrack'); - } else { - if ($stat['ifLastChange'] > $stat['sysUptime']) { - $upTime = __('Since Restart', 'mactrack'); - } else { - $time = $stat['sysUptime'] - $stat['ifLastChange']; - $days = intval($time / (60 * 60 * 24 * 100)); - $remainder = $time % (60 * 60 * 24 * 100); - $hours = intval($remainder / (60 * 60 * 100)); - $remainder = $remainder % (60 * 60 * 100); - $minutes = intval($remainder / (60 * 100)); - $upTime = $days.'d:'.$hours.'h:'.$minutes.'m'; - } - } - - ob_start(); - - form_selectable_cell(mactrack_interface_actions($stat['device_id'], $stat['ifIndex']), $stat['device_id']); - form_selectable_cell($stat['device_name'], $stat['device_id']); - form_selectable_cell(strtoupper($stat['device_type']), $stat['device_id']); - form_selectable_cell($stat['ifName'], $stat['device_id']); - form_selectable_cell($stat['ifDescr'], $stat['device_id']); - form_selectable_cell($stat['ifAlias'], $stat['device_id']); - form_selectable_cell(round($stat['inBound'], 1).' %', $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['outBound'], 1).' %', $stat['device_id'], '', 'right'); - form_selectable_cell(mactrack_display_Octets($stat['int_ifHCInOctets']), $stat['device_id'], '', 'right'); - form_selectable_cell(mactrack_display_Octets($stat['int_ifHCOutOctets']), $stat['device_id'], '', 'right'); - - if ('true' == get_request_var('totals') || 'on' == get_request_var('totals')) { - form_selectable_cell($stat['ifInErrors'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifInDiscards'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifInUnknownProtos'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifOutErrors'], $stat['device_id'], '', 'right'); - form_selectable_cell($stat['ifOutDiscards'], $stat['device_id'], '', 'right'); - } else { - form_selectable_cell(round($stat['int_ifInErrors'], 1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifInDiscards'], 1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifInUnknownProtos'], 1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifOutErrors'], 1), $stat['device_id'], '', 'right'); - form_selectable_cell(round($stat['int_ifOutDiscards'], 1), $stat['device_id'], '', 'right'); - } - - form_selectable_cell(1 == $stat['ifOperStatus'] ? __('Up', 'mactrack') : __('Down', 'mactrack'), $stat['device_id'], '', 'right'); - form_selectable_cell($upTime, $stat['device_id'], '', 'right'); - form_selectable_cell(mactrack_date($stat['last_rundate']), $stat['device_id'], '', 'right'); - - return ob_get_clean(); -} - -function mactrack_format_dot1x_row($port_result) -{ - global $config,$mactrack_device_status; - - // we will make a row string - $row = ''; - - if (3 != get_request_var('scan_date')) { - $scan_date = $port_result['scan_date']; - } else { - $scan_date = $port_result['max_scan_date']; - } - - $status = 'Unknown'; - if (array_key_exists($port_result['status'], $mactrack_device_status)) { - $status = $mactrack_device_status[$port_result['status']]; - } - - $row .= "".mactrack_interface_actions($port_result['device_id'], $port_result['port_number']).''; - $row .= ''.$port_result['device_name'].''; - $row .= ''.$port_result['hostname'].''; - $row .= ''.$port_result['username'].''; - $row .= ''.$port_result['ip_address'].''; + [$device['host_id'], $ifIndex] + ); + + if (cacti_sizeof($graphs)) { + $url = $config['url_path'] . 'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list='; + $list = ''; + + foreach ($graphs as $graph) { + $list .= ($list != '' ? ',' : '') . $graph['local_graph_id']; + } - if ('' != read_config_option('mt_reverse_dns')) { - $row .= ''.$port_result['dns_hostname'].''; - } + $row .= ""; + } else { + $row .= ""; + } + } + + $row .= $rescan; + + return $row; +} + +function mactrack_format_interface_row($stat) { + global $config; + + // we will make a row string + $row = ''; + + // calculate a human readable uptime + if ($stat['ifLastChange'] == 0) { + $upTime = __('Since Restart', 'mactrack'); + } else { + if ($stat['ifLastChange'] > $stat['sysUptime']) { + $upTime = __('Since Restart', 'mactrack'); + } else { + $time = $stat['sysUptime'] - $stat['ifLastChange']; + $days = intval($time / (60 * 60 * 24 * 100)); + $remainder = $time % (60 * 60 * 24 * 100); + $hours = intval($remainder / (60 * 60 * 100)); + $remainder = $remainder % (60 * 60 * 100); + $minutes = intval($remainder / (60 * 100)); + $upTime = $days . 'd:' . $hours . 'h:' . $minutes . 'm'; + } + } + + ob_start(); + + form_selectable_cell(mactrack_interface_actions($stat['device_id'], $stat['ifIndex']), $stat['device_id']); + form_selectable_cell($stat['device_name'], $stat['device_id']); + form_selectable_cell(strtoupper($stat['device_type']), $stat['device_id']); + form_selectable_cell($stat['ifName'], $stat['device_id']); + form_selectable_cell($stat['ifDescr'], $stat['device_id']); + form_selectable_cell($stat['ifAlias'], $stat['device_id']); + form_selectable_cell(round($stat['inBound'], 1) . ' %', $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['outBound'], 1) . ' %', $stat['device_id'], '', 'right'); + form_selectable_cell(mactrack_display_Octets($stat['int_ifHCInOctets']), $stat['device_id'], '', 'right'); + form_selectable_cell(mactrack_display_Octets($stat['int_ifHCOutOctets']), $stat['device_id'], '', 'right'); - $row .= ''.mactrack_format_mac($port_result['mac_address']).''; - $row .= ''.$port_result['ifName'].''; - $row .= ''.(2 == $port_result['domain'] ? __('Data', 'mactrack') : __('Voice', 'mactrack')).''; - $row .= ''.$status.''; - $row .= "".$scan_date.''; + if (get_request_var('totals') == 'true' || get_request_var('totals') == 'on') { + form_selectable_cell($stat['ifInErrors'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifInDiscards'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifInUnknownProtos'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifOutErrors'], $stat['device_id'], '', 'right'); + form_selectable_cell($stat['ifOutDiscards'], $stat['device_id'], '', 'right'); + } else { + form_selectable_cell(round($stat['int_ifInErrors'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifInDiscards'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifInUnknownProtos'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifOutErrors'], 1), $stat['device_id'], '', 'right'); + form_selectable_cell(round($stat['int_ifOutDiscards'], 1), $stat['device_id'], '', 'right'); + } - return $row; + form_selectable_cell($stat['ifOperStatus'] == 1 ? __('Up', 'mactrack') : __('Down', 'mactrack'), $stat['device_id'], '', 'right'); + form_selectable_cell($upTime, $stat['device_id'], '', 'right'); + form_selectable_cell(mactrack_date($stat['last_rundate']), $stat['device_id'], '', 'right'); + + return ob_get_clean(); } -function mactrack_display_Octets($octets) -{ - $suffix = ''; - while ($octets > 1024) { - $octets = $octets / 1024; - - switch ($suffix) { - case '': - $suffix = 'k'; - - break; - - case 'k': - $suffix = 'm'; - - break; - - case 'M': - $suffix = 'G'; +function mactrack_format_dot1x_row($port_result) { + global $config,$mactrack_device_status; - break; + // we will make a row string + $row = ''; - case 'G': - $suffix = 'P'; + if (get_request_var('scan_date') != 3) { + $scan_date = $port_result['scan_date']; + } else { + $scan_date = $port_result['max_scan_date']; + } - break 2; + $status = 'Unknown'; - default: - $suffix = ''; + if (array_key_exists($port_result['status'], $mactrack_device_status)) { + $status = $mactrack_device_status[$port_result['status']]; + } - break 2; - } - } + $row .= "" . mactrack_interface_actions($port_result['device_id'], $port_result['port_number']) . ''; + $row .= '' . $port_result['device_name'] . ''; + $row .= '' . $port_result['hostname'] . ''; + $row .= '' . $port_result['username'] . ''; + $row .= '' . $port_result['ip_address'] . ''; - $octets = round($octets, 4); - $octets = substr($octets, 0, 5); + if (read_config_option('mt_reverse_dns') != '') { + $row .= '' . $port_result['dns_hostname'] . ''; + } - return $octets.' '.$suffix; + $row .= '' . mactrack_format_mac($port_result['mac_address']) . ''; + $row .= '' . $port_result['ifName'] . ''; + $row .= '' . ($port_result['domain'] == 2 ? __('Data', 'mactrack') : __('Voice', 'mactrack')) . ''; + $row .= '' . $status . ''; + $row .= "" . $scan_date . ''; + + return $row; } -function mactrack_rescan($web = false) -{ - global $config; +function mactrack_display_Octets($octets) { + $suffix = ''; + + while ($octets > 1024) { + $octets = $octets / 1024; + + switch ($suffix) { + case '': + $suffix = 'k'; + + break; + case 'k': + $suffix = 'm'; + + break; + case 'M': + $suffix = 'G'; + + break; + case 'G': + $suffix = 'P'; + + break 2; + default: + $suffix = ''; + + break 2; + } + } + + $octets = round($octets, 4); + $octets = substr($octets, 0, 5); + + return $octets . ' ' . $suffix; +} - $device_id = get_request_var('device_id'); - $ifIndex = get_request_var('ifIndex'); +function mactrack_rescan($web = false) { + global $config; - $dbinfo = db_fetch_row_prepared( - 'SELECT * + $device_id = get_request_var('device_id'); + $ifIndex = get_request_var('ifIndex'); + + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mac_track_devices WHERE device_id = ?', - [$device_id] - ); + [$device_id] + ); - $data = []; + $data = []; - if (cacti_sizeof($dbinfo)) { - if ('' == $dbinfo['disabled']) { - // log the transaction to the database - mactrack_log_action(__('Device Rescan \'%s\'', $dbinfo['hostname'], 'mactrack')); + if (cacti_sizeof($dbinfo)) { + if ($dbinfo['disabled'] == '') { + // log the transaction to the database + mactrack_log_action(__('Device Rescan \'%s\'', $dbinfo['hostname'], 'mactrack')); - // create the command script - $command_string = $config['base_path'].'/plugins/mactrack/mactrack_scanner.php'; - $extra_args = ' -id='.$dbinfo['device_id'].($web ? ' --web' : ''); + // create the command script + $command_string = $config['base_path'] . '/plugins/mactrack/mactrack_scanner.php'; + $extra_args = ' -id=' . $dbinfo['device_id'] . ($web ? ' --web' : ''); - // print out the type, and device_id - $data['device_id'] = get_request_var('device_id'); - $data['ifIndex'] = $ifIndex; + // print out the type, and device_id + $data['device_id'] = get_request_var('device_id'); + $data['ifIndex'] = $ifIndex; - // add the cacti header - ob_start(); + // add the cacti header + ob_start(); - // execute the command, and show the results - $command = read_config_option('path_php_binary').' -q '.$command_string.$extra_args; - passthru($command); + // execute the command, and show the results + $command = read_config_option('path_php_binary') . ' -q ' . $command_string . $extra_args; + passthru($command); - $data['content'] = ob_get_clean(); - } - } + $data['content'] = ob_get_clean(); + } + } - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - echo json_encode($data); + print json_encode($data); } -function mactrack_site_scan($web = false) -{ - global $config, $web; +function mactrack_site_scan($web = false) { + global $config, $web; - $site_id = get_request_var('site_id'); + $site_id = get_request_var('site_id'); - $dbinfo = db_fetch_row_prepared( - 'SELECT * + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mac_track_sites WHERE site_id = ?', - [$site_id] - ); + [$site_id] + ); - $data = []; + $data = []; - if (cacti_sizeof($dbinfo)) { - // log the transaction to the database - mactrack_log_action(__('Site scan \'%s\'', $dbinfo['site_name'], 'mactrack')); + if (cacti_sizeof($dbinfo)) { + // log the transaction to the database + mactrack_log_action(__('Site scan \'%s\'', $dbinfo['site_name'], 'mactrack')); - // create the command script - $command_string = $config['base_path'].'/plugins/mactrack/poller_mactrack.php'; - $extra_args = ' --web -sid='.$dbinfo['site_id']; + // create the command script + $command_string = $config['base_path'] . '/plugins/mactrack/poller_mactrack.php'; + $extra_args = ' --web -sid=' . $dbinfo['site_id']; - // print out the type, and device_id - $data['site_id'] = $site_id; + // print out the type, and device_id + $data['site_id'] = $site_id; - // add the cacti header - ob_start(); + // add the cacti header + ob_start(); - // execute the command, and show the results - $command = read_config_option('path_php_binary').' -q '.$command_string.$extra_args; - passthru($command); + // execute the command, and show the results + $command = read_config_option('path_php_binary') . ' -q ' . $command_string . $extra_args; + passthru($command); - $data['content'] = ob_get_clean(); - } + $data['content'] = ob_get_clean(); + } - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - echo json_encode($data); + print json_encode($data); } -function mactrack_enable() -{ - // ================= input validation ================= - get_filter_request_var('device_id'); - // ==================================================== +function mactrack_enable() { + // ================= input validation ================= + get_filter_request_var('device_id'); + // ==================================================== - $dbinfo = db_fetch_row_prepared( - 'SELECT * + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mac_track_devices WHERE device_id = ?', - [get_request_var('device_id')] - ); + [get_request_var('device_id')] + ); - $data = []; + $data = []; - // log the transaction to the database - mactrack_log_action(__('Device Enable \'%s\'', $dbinfo['hostname'], 'mactrack')); + // log the transaction to the database + mactrack_log_action(__('Device Enable \'%s\'', $dbinfo['hostname'], 'mactrack')); - db_execute_prepared( - 'UPDATE mac_track_devices + db_execute_prepared( + 'UPDATE mac_track_devices SET disabled = "" WHERE device_id = ?', - [get_request_var('device_id')] - ); + [get_request_var('device_id')] + ); - // get the new html - $html = mactrack_format_device_row($dbinfo); + // get the new html + $html = mactrack_format_device_row($dbinfo); - // send the response back to the browser - $data['device_id'] = get_request_var('device_id'); - $data['content'] = $html; + // send the response back to the browser + $data['device_id'] = get_request_var('device_id'); + $data['content'] = $html; - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - echo json_encode($data); + print json_encode($data); } -function mactrack_disable() -{ - // ================= input validation ================= - get_filter_request_var('device_id'); - // ==================================================== +function mactrack_disable() { + // ================= input validation ================= + get_filter_request_var('device_id'); + // ==================================================== - $dbinfo = db_fetch_row_prepared( - 'SELECT * + $dbinfo = db_fetch_row_prepared( + 'SELECT * FROM mactrack_devices WHERE device_id = ?', - [get_request_var('device_id')] - ); + [get_request_var('device_id')] + ); - $data = []; + $data = []; - // log the transaction to the database - mactrack_log_action(__('Device Disable \'%d\'', $dbinfo['hostname'], 'mactrack')); + // log the transaction to the database + mactrack_log_action(__('Device Disable \'%d\'', $dbinfo['hostname'], 'mactrack')); - db_execute_prepared( - 'UPDATE mactack_devices + db_execute_prepared( + 'UPDATE mactack_devices SET disabled="on" WHERE device_id = ?', - [get_request_var('device_id')] - ); + [get_request_var('device_id')] + ); - // get the new html - $html = mactrack_format_device_row($stat); + // get the new html + $html = mactrack_format_device_row($stat); - // send the response back to the browser - $data['device_id'] = get_request_var('device_id'); - $data['content'] = $html; + // send the response back to the browser + $data['device_id'] = get_request_var('device_id'); + $data['content'] = $html; - header('Content-Type: application/json; charset=utf-8'); + header('Content-Type: application/json; charset=utf-8'); - echo json_encode($data); + print json_encode($data); } -function mactrack_log_action($message) -{ - $user = db_fetch_row_prepared( - 'SELECT username, full_name +function mactrack_log_action($message) { + $user = db_fetch_row_prepared( + 'SELECT username, full_name FROM user_auth WHERE id = ?', - [$_SESSION['sess_user_id']] - ); - - cacti_log('MACTRACK: '.$message.", by '".$user['full_name'].'('.$user['username'].")'", false, 'SYSTEM'); -} - -function mactrack_date($date) -{ - $year = date('Y'); - - return substr_count($date, $year) ? substr($date, 5) : $date; -} - -function mactrack_int_row_class($stat) -{ - if ('1' == $stat['int_errors_present']) { - return 'int_errors'; - } - if ('1' == $stat['int_discards_present']) { - return 'int_discards'; - } - if ('1' == $stat['ifOperStatus'] && '' == $stat['ifAlias']) { - return 'int_up_wo_alias'; - } - if ('0' == $stat['ifOperStatus']) { - return 'int_down'; - } - - return 'int_up'; -} - -function mactrack_dot1x_row_class($port_result) -{ - if ('7' == $port_result['status']) { - return 'dot1x_authn_failed'; - } - if ('5' == $port_result['status']) { - return 'dot1x_auth_failed'; - } - if ('3' == $port_result['status']) { - return 'dot1x_auth_no_method'; - } - if ('2' == $port_result['status']) { - return 'dot1x_running'; - } - if ('1' == $port_result['status']) { - return 'dot1x_idle'; - } - if ('4' == $port_result['status']) { - return 'dot1x_auth_success'; - } - - return 'dot1x_authn_success'; -} - -/* mactrack_create_sql_filter - this routine will take a filter string and process it into a - sql where clause that will be returned to the caller with a formatted SQL where clause - that can then be integrated into the overall where clause. - The filter takes the following forms. The default is to find occurrence that match "all" - Any string prefixed by a "-" will mean "exclude" this search string. Boolean expressions - are currently not supported. + [$_SESSION['sess_user_id']] + ); + + cacti_log('MACTRACK: ' . $message . ", by '" . $user['full_name'] . '(' . $user['username'] . ")'", false, 'SYSTEM'); +} + +function mactrack_date($date) { + $year = date('Y'); + + return substr_count($date, $year) ? substr($date, 5) : $date; +} + +function mactrack_int_row_class($stat) { + if ($stat['int_errors_present'] == '1') { + return 'int_errors'; + } + + if ($stat['int_discards_present'] == '1') { + return 'int_discards'; + } + + if ($stat['ifOperStatus'] == '1' && $stat['ifAlias'] == '') { + return 'int_up_wo_alias'; + } + + if ($stat['ifOperStatus'] == '0') { + return 'int_down'; + } + + return 'int_up'; +} + +function mactrack_dot1x_row_class($port_result) { + if ($port_result['status'] == '7') { + return 'dot1x_authn_failed'; + } + + if ($port_result['status'] == '5') { + return 'dot1x_auth_failed'; + } + + if ($port_result['status'] == '3') { + return 'dot1x_auth_no_method'; + } + + if ($port_result['status'] == '2') { + return 'dot1x_running'; + } + + if ($port_result['status'] == '1') { + return 'dot1x_idle'; + } + + if ($port_result['status'] == '4') { + return 'dot1x_auth_success'; + } + + return 'dot1x_authn_success'; +} + +/** mactrack_create_sql_filter - this routine will take a filter string and process it into a + sql where clause that will be returned to the caller with a formatted SQL where clause + that can then be integrated into the overall where clause. + The filter takes the following forms. The default is to find occurrence that match "all" + Any string prefixed by a "-" will mean "exclude" this search string. Boolean expressions + are currently not supported. @arg $filter - (string) The filter provided by the user @arg $fields - (array) A list of field names to include in the where clause. They can also - contain the table name in cases where joins are important. + contain the table name in cases where joins are important. + * @param mixed $filter + * @param mixed $fields @returns - (string) The formatted SQL syntax */ -function mactrack_create_sql_filter($filter, $fields) -{ - $query = ''; - - // field names are required - if (!cacti_sizeof($fields)) { - return; - } - - // the filter must be non-blank - if ('' == $filter) { - return; - } - - $elements = explode(' ', $filter); - - foreach ($elements as $element) { - if ('-' == substr($element, 0, 1)) { - $filter = substr($element, 1); - $type = 'NOT'; - $operator = 'AND'; - } else { - $filter = $element; - $type = ''; - $operator = 'OR'; - } - - $field_no = 1; - foreach ($fields as $field) { - if (1 == $field_no && '' != $query) { - $query .= ') AND ('; - } elseif (1 == $field_no) { - $query .= '('; - } - - $query .= (1 == $field_no ? '' : " {$operator} ")."({$field} {$type} LIKE '%".$filter."%')"; - - ++$field_no; - } - } - - return $query.')'; -} - -function mactrack_display_hours($value) -{ - if ('' == $value || 'disabled' == $value) { - return __('N/A', 'mactrack'); - } - if ($value < 60) { - return __('%d Minutes', round($value, 0), 'mactrack'); - } - $value = $value / 60; - if ($value < 24) { - return __('%d Hours', round($value, 0), 'mactrack'); - } - $value = $value / 24; - if ($value < 7) { - return __('%d Days', round($value, 0), 'mactrack'); - } - $value = $value / 7; - - return __('%d Weeks', round($value, 0), 'mactrack'); -} - -function mactrack_display_stats() -{ - // check if scanning is running - $processes = db_fetch_cell('SELECT COUNT(*) FROM mac_track_processes'); - $timing = read_config_option('mt_collection_timing', true); - $frequency = 0; - - if ('disabled' != $timing) { - $frequency = $timing * 60; - } - - $mactrack_stats = read_config_option('stats_mactrack', true); - - $time = __('Not Recorded', 'mactrack'); - $proc = __('N/A', 'mactrack'); - $devs = __('N/A', 'mactrack'); - if ('' != $mactrack_stats) { - $stats = explode(' ', $mactrack_stats); - - if (cacti_sizeof(3 == $stats)) { - $time = explode(':', $stats[0]); - $time = $time[1]; - $time = round($time, 1); - - $proc = explode(':', $stats[1]); - $proc = $proc[1]; - - $devs = explode(':', $stats[2]); - $devs = $devs[1]; - } - } - - if ($processes > 0) { - $message = __('Status: Running, Processes: %d, Progress: %s, LastRuntime: %2.1f', $processes, read_config_option('mactrack_process_status', true), $time, 'mactrack'); - } else { - $message = __( - 'Status: Idle, LastRuntime: %2.1f seconds, Processes: %d processes, Devices: %d, Next Run Time: %s', - $time, - $proc, - $devs, - 'disabled' != $timing ? date('Y-m-d H:i:s', strtotime(read_config_option('mt_scan_date', true)) + $frequency) : __('Disabled', 'mactrack'), - 'mactrack' - ); - } - - html_start_box('', '100%', '', '3', 'center', ''); - - echo ''; - echo ''.__('Scanning Rate: Every %s', mactrack_display_hours(read_config_option('mt_collection_timing')), 'mactrack').', '.$message.''; - echo ''; - - html_end_box(); -} - -function mactrack_legend_row($class, $text) -{ - echo "{$text}"; -} - -function mactrack_format_device_row($device, $actions = false) -{ - global $config, $mactrack_device_types; - - // viewer level - if ($actions) { - $row = ""; - - // admin level - if (api_user_realm_auth('mactrack_sites.php')) { - if ('' == $device['disabled']) { - $row .= ""; - } else { - $row .= ""; - } - } - - echo "".$row.''; - } - - form_selectable_cell(filter_value($device['device_name'], get_request_var('filter'), 'mactrack_devices.php?action=edit&device_id='.$device['device_id']), $device['device_id']); - form_selectable_cell($device['site_name'], $device['device_id']); - form_selectable_cell(get_colored_device_status('on' == $device['disabled'] ? true : false, $device['snmp_status']), $device['device_id']); - form_selectable_cell(filter_value($device['hostname'], get_request_var('filter')), $device['device_id']); - form_selectable_cell('' == $device['device_type'] ? __('Not Detected', 'mactrack') : $device['device_type'], $device['device_id']); - form_selectable_cell('1' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ips_total'], -1), $device['device_id'], '', 'right'); - form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ports_total'], -1), $device['device_id'], '', 'right'); - form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ports_active'], -1), $device['device_id'], '', 'right'); - form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['ports_trunk'], -1), $device['device_id'], '', 'right'); - form_selectable_cell('3' == $device['scan_type'] ? __('N/A', 'mactrack') : number_format_i18n($device['macs_active'], -1), $device['device_id'], '', 'right'); - form_selectable_cell(number_format($device['last_runduration'], 1), $device['device_id'], '', 'right'); - form_checkbox_cell($device['device_name'], $device['device_id']); - form_end_row(); -} - -function mactrack_mail($to, $fromemail, $fromname, $subject, $message, $headers = '') -{ - global $config; - - $v = plugin_mactrack_version(); - $headers = [ - 'X-Mailer' => 'Cacti-MacTrack-v'.$v['version'], - 'User-Agent' => 'Cacti-MacTrack-v'.$v['version'], - ]; - - $from[0]['email'] = $fromemail; - $from[0]['name'] = $fromname; - - if (false !== strpos($to, ';')) { - $to = explode(';', $to); - } - - mailer($from, $to, '', '', '', $subject, $message, '', '', $headers); -} - -function mactrack_sanitize_load_report() -{ - if (!isset_request_var('report')) { - if (isset($_SESSION['sess_mt_tab']) && '' != $_SESSION['sess_mt_tab']) { - set_request_var('report', $_SESSION['sess_mt_tab']); - } else { - set_request_var('report', read_user_setting('default_mactrack_tab')); - } - - if ('' == get_request_var('report')) { - set_request_var('report', 'sites'); - } - } else { - set_request_var('report', sanitize_search_string(get_nfilter_request_var('report'))); - } - - $_SESSION['sess_mt_tab'] = get_request_var('report'); +function mactrack_create_sql_filter($filter, $fields) { + $query = ''; + + // field names are required + if (!cacti_sizeof($fields)) { + return; + } + + // the filter must be non-blank + if ($filter == '') { + return; + } + + $elements = explode(' ', $filter); + + foreach ($elements as $element) { + if (substr($element, 0, 1) == '-') { + $filter = substr($element, 1); + $type = 'NOT'; + $operator = 'AND'; + } else { + $filter = $element; + $type = ''; + $operator = 'OR'; + } + + $field_no = 1; + + foreach ($fields as $field) { + if ($field_no == 1 && $query != '') { + $query .= ') AND ('; + } elseif ($field_no == 1) { + $query .= '('; + } + + $query .= ($field_no == 1 ? '' : " {$operator} ") . "({$field} {$type} LIKE '%" . $filter . "%')"; + + ++$field_no; + } + } + + return $query . ')'; +} + +function mactrack_display_hours($value) { + if ($value == '' || $value == 'disabled') { + return __('N/A', 'mactrack'); + } + + if ($value < 60) { + return __('%d Minutes', round($value, 0), 'mactrack'); + } + $value = $value / 60; + + if ($value < 24) { + return __('%d Hours', round($value, 0), 'mactrack'); + } + $value = $value / 24; + + if ($value < 7) { + return __('%d Days', round($value, 0), 'mactrack'); + } + $value = $value / 7; + + return __('%d Weeks', round($value, 0), 'mactrack'); +} + +function mactrack_display_stats() { + // check if scanning is running + $processes = db_fetch_cell('SELECT COUNT(*) FROM mac_track_processes'); + $timing = read_config_option('mt_collection_timing', true); + $frequency = 0; + + if ($timing != 'disabled') { + $frequency = $timing * 60; + } + + $mactrack_stats = read_config_option('stats_mactrack', true); + + $time = __('Not Recorded', 'mactrack'); + $proc = __('N/A', 'mactrack'); + $devs = __('N/A', 'mactrack'); + + if ($mactrack_stats != '') { + $stats = explode(' ', $mactrack_stats); + + if (cacti_sizeof($stats == 3)) { + $time = explode(':', $stats[0]); + $time = $time[1]; + $time = round($time, 1); + + $proc = explode(':', $stats[1]); + $proc = $proc[1]; + + $devs = explode(':', $stats[2]); + $devs = $devs[1]; + } + } + + if ($processes > 0) { + $message = __('Status: Running, Processes: %d, Progress: %s, LastRuntime: %2.1f', $processes, read_config_option('mactrack_process_status', true), $time, 'mactrack'); + } else { + $message = __( + 'Status: Idle, LastRuntime: %2.1f seconds, Processes: %d processes, Devices: %d, Next Run Time: %s', + $time, + $proc, + $devs, + $timing != 'disabled' ? date('Y-m-d H:i:s', strtotime(read_config_option('mt_scan_date', true)) + $frequency) : __('Disabled', 'mactrack'), + 'mactrack' + ); + } + + html_start_box('', '100%', '', '3', 'center', ''); + + print ''; + print '' . __('Scanning Rate: Every %s', mactrack_display_hours(read_config_option('mt_collection_timing')), 'mactrack') . ', ' . $message . ''; + print ''; + + html_end_box(); } -function mactrack_tabs() -{ - global $config; - - // present a tabbed interface - $tabs_mactrack = [ - 'sites' => __('Sites', 'mactrack'), - 'devices' => __('Devices', 'mactrack'), - 'ips' => __('IP Ranges', 'mactrack'), - 'arp' => __('IP Address', 'mactrack'), - 'macs' => __('MAC Address', 'mactrack'), - 'interfaces' => __('Interfaces', 'mactrack'), - 'dot1x' => __('Dot1x', 'mactrack'), - 'graphs' => __('Graphs', 'mactrack'), - ]; +function mactrack_legend_row($class, $text) { + print "{$text}"; +} - mactrack_sanitize_load_report(); +function mactrack_format_device_row($device, $actions = false) { + global $config, $mactrack_device_types; - // set the default tab - $current_tab = get_nfilter_request_var('report'); + // viewer level + if ($actions) { + $row = ""; - // draw the tabs - echo "
'; -} + print "" . $row . ''; + } -function mactrack_get_vendor_name($mac) -{ - $vendor_mac = substr($mac, 0, 8); + form_selectable_cell(filter_value($device['device_name'], get_request_var('filter'), 'mactrack_devices.php?action=edit&device_id=' . $device['device_id']), $device['device_id']); + form_selectable_cell($device['site_name'], $device['device_id']); + form_selectable_cell(get_colored_device_status($device['disabled'] == 'on' ? true : false, $device['snmp_status']), $device['device_id']); + form_selectable_cell(filter_value($device['hostname'], get_request_var('filter')), $device['device_id']); + form_selectable_cell($device['device_type'] == '' ? __('Not Detected', 'mactrack') : $device['device_type'], $device['device_id']); + form_selectable_cell($device['scan_type'] == '1' ? __('N/A', 'mactrack') : number_format_i18n($device['ips_total'], -1), $device['device_id'], '', 'right'); + form_selectable_cell($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['ports_total'], -1), $device['device_id'], '', 'right'); + form_selectable_cell($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['ports_active'], -1), $device['device_id'], '', 'right'); + form_selectable_cell($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['ports_trunk'], -1), $device['device_id'], '', 'right'); + form_selectable_cell($device['scan_type'] == '3' ? __('N/A', 'mactrack') : number_format_i18n($device['macs_active'], -1), $device['device_id'], '', 'right'); + form_selectable_cell(number_format($device['last_runduration'], 1), $device['device_id'], '', 'right'); + form_checkbox_cell($device['device_name'], $device['device_id']); + form_end_row(); +} - $vendor_name = db_fetch_cell_prepared('SELECT vendor_name FROM mac_track_oui_database WHERE vendor_mac = ?', [$vendor_mac]); +function mactrack_mail($to, $fromemail, $fromname, $subject, $message, $headers = '') { + global $config; - if ('' != $vendor_name) { - return $vendor_name; - } + $v = plugin_mactrack_version(); + $headers = [ + 'X-Mailer' => 'Cacti-MacTrack-v' . $v['version'], + 'User-Agent' => 'Cacti-MacTrack-v' . $v['version'], + ]; - return __('Unknown', 'mactrack'); + $from[0]['email'] = $fromemail; + $from[0]['name'] = $fromname; + + if (strpos($to, ';') !== false) { + $to = explode(';', $to); + } + + mailer($from, $to, '', '', '', $subject, $message, '', '', $headers); } -function mactrack_site_filter($page = 'mactrack_sites.php') -{ - global $item_rows; +function mactrack_sanitize_load_report() { + if (!isset_request_var('report')) { + if (isset($_SESSION['sess_mt_tab']) && $_SESSION['sess_mt_tab'] != '') { + set_request_var('report', $_SESSION['sess_mt_tab']); + } else { + set_request_var('report', read_user_setting('default_mactrack_tab')); + } + + if (get_request_var('report') == '') { + set_request_var('report', 'sites'); + } + } else { + set_request_var('report', sanitize_search_string(get_nfilter_request_var('report'))); + } + + $_SESSION['sess_mt_tab'] = get_request_var('report'); +} + +function mactrack_tabs() { + global $config; + + // present a tabbed interface + $tabs_mactrack = [ + 'sites' => __('Sites', 'mactrack'), + 'devices' => __('Devices', 'mactrack'), + 'ips' => __('IP Ranges', 'mactrack'), + 'arp' => __('IP Address', 'mactrack'), + 'macs' => __('MAC Address', 'mactrack'), + 'interfaces' => __('Interfaces', 'mactrack'), + 'dot1x' => __('Dot1x', 'mactrack'), + 'graphs' => __('Graphs', 'mactrack'), + ]; + + mactrack_sanitize_load_report(); + + // set the default tab + $current_tab = get_nfilter_request_var('report'); - ?> + // draw the tabs + print "
'; +} + +function mactrack_get_vendor_name($mac) { + $vendor_mac = substr($mac, 0, 8); + + $vendor_name = db_fetch_cell_prepared('SELECT vendor_name FROM mac_track_oui_database WHERE vendor_mac = ?', [$vendor_mac]); + + if ($vendor_name != '') { + return $vendor_name; + } + + return __('Unknown', 'mactrack'); +} + +function mactrack_site_filter($page = 'mactrack_sites.php') { + global $item_rows; + + ?> + if (!(get_request_var('detail') == 'false')) { ?>
- + - '> + '> - + - onClick='applyFilter()'> - + - - - + + +
- + - +
+ if (get_request_var('detail') == 'false') { ?> @@ -3922,7 +3917,7 @@ function mactrack_site_filter($page = 'mactrack_sites.php') ".__('You must select at least one SNMP Option.', 'mactrack')."\n"; - $save_html = ''; - } else { - $save_html = "'; + if (!isset($mactrack_array)) { + print "" . __('You must select at least one SNMP Option.', 'mactrack') . "\n"; + $save_html = ''; + } else { + $save_html = "'; - if ('1' == get_nfilter_request_var('drp_action')) { // delete - echo " + if (get_nfilter_request_var('drp_action') == '1') { // delete + print " -

".__('Click \'Continue\' to delete the following SNMP Option(s).', 'mactrack')."

+

" . __('Click \'Continue\' to delete the following SNMP Option(s).', 'mactrack') . "

    {$snmp_groups}
"; - } elseif ('2' == get_nfilter_request_var('drp_action')) { // duplicate - echo " + } elseif (get_nfilter_request_var('drp_action') == '2') { // duplicate + print " -

".__('Click \'Continue\' to duplicate the following SNMP Option(s). You can optionally change the title format for the new SNMP Options.', 'mactrack')."

+

" . __('Click \'Continue\' to duplicate the following SNMP Option(s). You can optionally change the title format for the new SNMP Options.', 'mactrack') . "

    {$snmp_groups}
-

".__('Name Format:', 'mactrack').'
'; - form_text_box('name_format', __(' (1)', 'mactrack'), '', '255', '30', 'text'); - echo '

+

" . __('Name Format:', 'mactrack') . '
'; + form_text_box('name_format', __(' (1)', 'mactrack'), '', '255', '30', 'text'); + print '

'; - } - } + } + } - echo " + print " - - - + + + {$save_html} "; - html_end_box(); + html_end_box(); - bottom_footer(); + bottom_footer(); } /* -------------------------- mactrack Item Functions -------------------------- */ -function mactrack_snmp_item_movedown() -{ - // ================= input validation ================= - get_filter_request_var('item_id'); - get_filter_request_var('id'); - // ==================================================== - - move_item_down('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id='.get_request_var('id')); +function mactrack_snmp_item_movedown() { + // ================= input validation ================= + get_filter_request_var('item_id'); + get_filter_request_var('id'); + // ==================================================== + + move_item_down('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id=' . get_request_var('id')); } -function mactrack_snmp_item_moveup() -{ - // ================= input validation ================= - get_filter_request_var('item_id'); - get_filter_request_var('id'); - // ==================================================== +function mactrack_snmp_item_moveup() { + // ================= input validation ================= + get_filter_request_var('item_id'); + get_filter_request_var('id'); + // ==================================================== - move_item_up('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id='.get_request_var('id')); + move_item_up('mac_track_snmp_items', get_request_var('item_id'), 'snmp_id=' . get_request_var('id')); } -function mactrack_snmp_item_remove() -{ - // ================= input validation ================= - get_filter_request_var('item_id'); - // ==================================================== +function mactrack_snmp_item_remove() { + // ================= input validation ================= + get_filter_request_var('item_id'); + // ==================================================== - db_execute_prepared( - 'DELETE FROM mac_track_snmp_items + db_execute_prepared( + 'DELETE FROM mac_track_snmp_items WHERE id = ?', - [get_request_var('item_id')] - ); + [get_request_var('item_id')] + ); } -function mactrack_snmp_item_edit() -{ - global $config; - global $fields_mactrack_snmp_item_edit; +function mactrack_snmp_item_edit() { + global $config; + global $fields_mactrack_snmp_item_edit; - // ================= input validation ================= - get_filter_request_var('id'); - get_filter_request_var('item_id'); - // ==================================================== + // ================= input validation ================= + get_filter_request_var('id'); + get_filter_request_var('item_id'); + // ==================================================== - // fetch the current mactrack snmp record - $snmp_option = db_fetch_row_prepared( - 'SELECT * + // fetch the current mactrack snmp record + $snmp_option = db_fetch_row_prepared( + 'SELECT * FROM mac_track_snmp WHERE id = ?', - [get_request_var('id')] - ); + [get_request_var('id')] + ); - // if an existing item was requested, fetch data for it - if ('' !== get_request_var('item_id', '')) { - $mactrack_snmp_item = db_fetch_row_prepared( - 'SELECT * + // if an existing item was requested, fetch data for it + if (get_request_var('item_id', '') !== '') { + $mactrack_snmp_item = db_fetch_row_prepared( + 'SELECT * FROM mac_track_snmp_items WHERE id = ?', - [get_request_var('item_id')] - ); + [get_request_var('item_id')] + ); - $header_label = __('SNMP Options [edit %s]', $snmp_option['name'], 'mactrack'); - } else { - $header_label = __('SNMP Options [new]', 'mactrack'); + $header_label = __('SNMP Options [edit %s]', $snmp_option['name'], 'mactrack'); + } else { + $header_label = __('SNMP Options [new]', 'mactrack'); - $mactrack_snmp_item = []; - $mactrack_snmp_item['snmp_id'] = get_request_var('id'); - $mactrack_snmp_item['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id='.get_request_var('id')); - } + $mactrack_snmp_item = []; + $mactrack_snmp_item['snmp_id'] = get_request_var('id'); + $mactrack_snmp_item['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id=' . get_request_var('id')); + } - form_start(get_current_page(), 'mactrack_item_edit'); + form_start(get_current_page(), 'mactrack_item_edit'); - html_start_box($header_label, '100%', '', '3', 'center', ''); + html_start_box($header_label, '100%', '', '3', 'center', ''); - draw_edit_form( - [ - 'config' => ['no_form_tag' => true], - 'fields' => inject_form_variables($fields_mactrack_snmp_item_edit, isset($mactrack_snmp_item) ? $mactrack_snmp_item : []), - ] - ); + draw_edit_form( + [ + 'config' => ['no_form_tag' => true], + 'fields' => inject_form_variables($fields_mactrack_snmp_item_edit, isset($mactrack_snmp_item) ? $mactrack_snmp_item : []), + ] + ); - html_end_box(); + html_end_box(); - form_hidden_box('item_id', isset_request_var('item_id') ? get_request_var('item_id') : '0', ''); - form_hidden_box('id', isset($mactrack_snmp_item['snmp_id']) ? $mactrack_snmp_item['snmp_id'] : '0', ''); - form_hidden_box('save_component_mactrack_snmp_item', '1', ''); + form_hidden_box('item_id', isset_request_var('item_id') ? get_request_var('item_id') : '0', ''); + form_hidden_box('id', isset($mactrack_snmp_item['snmp_id']) ? $mactrack_snmp_item['snmp_id'] : '0', ''); + form_hidden_box('save_component_mactrack_snmp_item', '1', ''); - form_save_button(htmlspecialchars('mactrack_snmp.php?action=edit&id='.get_request_var('id'))); + form_save_button(htmlspecialchars('mactrack_snmp.php?action=edit&id=' . get_request_var('id'))); - ?> + ?> \n"; - echo "\n"; - if (file_exists($config['base_path'].'/plugins/mactrack/themes/'.get_selected_theme().'/mactrack.css')) { - echo "\n"; - } else { - echo "\n"; - } +function mactrack_page_head() { + global $config; + + print "\n"; + print "\n"; + + if (file_exists($config['base_path'] . '/plugins/mactrack/themes/' . get_selected_theme() . '/mactrack.css')) { + print "\n"; + } else { + print "\n"; + } } -function mactrack_poller_bottom() -{ - global $config; +function mactrack_poller_bottom() { + global $config; - $command_string = read_config_option('path_php_binary'); - $extra_args = '-q '.$config['base_path'].'/plugins/mactrack/poller_mactrack.php'; - exec_background($command_string, $extra_args); + $command_string = read_config_option('path_php_binary'); + $extra_args = '-q ' . $config['base_path'] . '/plugins/mactrack/poller_mactrack.php'; + exec_background($command_string, $extra_args); } -function mactrack_config_settings() -{ - global $tabs, $settings, $settings_user, $tabs_graphs, $snmp_versions, $mactrack_poller_frequencies, - $mactrack_data_retention, $mactrack_macauth_frequencies, $mactrack_update_policies; - - $tabs['mactrack'] = __('Mactrack', 'mactrack'); - - $settings['mactrack'] = [ - 'mactrack_hdr_timing' => [ - 'friendly_name' => __('General Settings', 'mactrack'), - 'method' => 'spacer', - ], - 'mt_collection_timing' => [ - 'friendly_name' => __('Scanning Frequency', 'mactrack'), - 'description' => __('Choose when to collect MAC and IP Addresses and Interface statistics from your network devices.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'disabled', - 'array' => $mactrack_poller_frequencies, - ], - 'mt_processes' => [ - 'friendly_name' => __('Concurrent Processes', 'mactrack'), - 'description' => __('Specify how many devices will be polled simultaneously until all devices have been polled.', 'mactrack'), - 'default' => '7', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '4', - ], - 'mt_script_runtime' => [ - 'friendly_name' => __('Scanner Max Runtime', 'mactrack'), - 'description' => __('Specify the number of minutes a device scanning function will be allowed to run prior to the system assuming it has been completed. This setting will correct for abended scanning jobs.', 'mactrack'), - 'default' => '20', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '4', - ], - 'mt_base_time' => [ - 'friendly_name' => __('Start Time for Data Collection', 'mactrack'), - 'description' => __('When would you like the first data collection to take place. All future data collection times will be based upon this start time. A good example would be 12:00AM.', 'mactrack'), - 'default' => '1:00am', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '8', - ], - 'mt_maint_time' => [ - 'friendly_name' => __('Database Maintenance Time', 'mactrack'), - 'description' => __('When should old database records be removed from the database. Please note that no access will be permitted to the port database while this action is taking place.', 'mactrack'), - 'default' => '12:00am', - 'method' => 'textbox', - 'max_length' => '10', - 'size' => '8', - ], - 'mt_maint_confirm' => [ - 'friendly_name' => __('Confirm Utilities Prompt', 'mactrack'), - 'description' => __('When using utilities, prompt for verification', 'mactrack'), - 'default' => read_config_option('deletion_verification'), - 'method' => 'checkbox', - ], - 'mt_data_retention' => [ - 'friendly_name' => __('Data Retention', 'mactrack'), - 'description' => __('How long should port MAC details be retained in the database.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '14', - 'array' => $mactrack_data_retention, - ], - 'mt_data_retention_ip' => [ - 'friendly_name' => __('Data Retention IPs', 'mactrack'), - 'description' => __('How long should discovered IPs details be retained in the database.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '3', - 'array' => $mactrack_data_retention, - ], - 'mt_ignorePorts_delim' => [ - 'friendly_name' => __('Switch Level Ignore Ports Delimiter', 'mactrack'), - 'description' => __('What delimiter should Mactrack use when parsing the Ignore Ports string for each switch.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '-1', - 'array' => [ - '-1' => __('Auto Detect', 'mactrack'), - ':' => __('Colon [:]', 'mactrack'), - '|' => __('Pipe [|]', 'mactrack'), - ' ' => __('Space [ ]', 'mactrack'), - ], - ], - 'mt_mac_format' => [ - 'friendly_name' => __('Mac Address Output Format', 'mactrack'), - 'description' => __('Format used for display.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'aa:bb:cc:dd:ee:ff', - 'array' => [ - 'aa:bb:cc:dd:ee:ff' => 'aa:bb:cc:dd:ee:ff', - 'aa-bb-cc-dd-ee-ff' => 'aa-bb-cc-dd-ee-ff', - 'aabb-ccdd-eeff' => 'aabb-ccdd-eeff', - 'aabbccddeeff' => 'aabbccddeeff', - 'aabb.ccdd.eeff' => 'aabb.ccdd.eeff', - ], - ], - 'mt_ignorePorts' => [ - 'method' => 'textbox', - 'friendly_name' => __('Ports to Ignore', 'mactrack'), - 'description' => __('Provide a regular expression of ifNames or ifDescriptions of ports to ignore in the interface list. For example, (Vlan|Loopback|Null).', 'mactrack'), - 'class' => 'textAreaNotes', - 'defaults' => '(Vlan|Loopback|Null)', - 'max_length' => '255', - 'size' => '80', - ], - 'mt_interface_high' => [ - 'friendly_name' => __('Bandwidth Usage Threshold', 'mactrack'), - 'description' => __('When reviewing network interface statistics, what bandwidth threshold do you want to view by default.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '70', - 'array' => [ - '-1' => __('N/A', 'mactrack'), - '10' => __('%d Percent', 10, 'mactrack'), - '20' => __('%d Percent', 20, 'mactrack'), - '30' => __('%d Percent', 30, 'mactrack'), - '40' => __('%d Percent', 40, 'mactrack'), - '50' => __('%d Percent', 50, 'mactrack'), - '60' => __('%d Percent', 60, 'mactrack'), - '70' => __('%d Percent', 70, 'mactrack'), - '80' => __('%d Percent', 80, 'mactrack'), - '90' => __('%d Percent', 90, 'mactrack'), - ], - ], - 'mt_hdr_rdns' => [ - 'friendly_name' => __('DNS Settings', 'mactrack'), - 'method' => 'spacer', - ], - 'mt_reverse_dns' => [ - 'friendly_name' => __('Perform Reverse DNS Name Resolution', 'mactrack'), - 'description' => __('Should Mactrack perform reverse DNS lookup of the IP addresses associated with ports. CAUTION: If DNS is not properly setup, this will slow scan time significantly.', 'mactrack'), - 'default' => '', - 'method' => 'checkbox', - ], - 'mt_dns_primary' => [ - 'friendly_name' => __('Primary DNS IP Address', 'mactrack'), - 'description' => __('Enter the primary DNS IP Address to utilize for reverse lookups.', 'mactrack'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '18', - ], - 'mt_dns_secondary' => [ - 'friendly_name' => __('Secondary DNS IP Address', 'mactrack'), - 'description' => __('Enter the secondary DNS IP Address to utilize for reverse lookups.', 'mactrack'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '18', - ], - 'mt_dns_timeout' => [ - 'friendly_name' => __('DNS Timeout', 'mactrack'), - 'description' => __('Please enter the DNS timeout in milliseconds. Mactrack uses a PHP based DNS resolver.', 'mactrack'), - 'method' => 'textbox', - 'default' => '500', - 'max_length' => '10', - 'size' => '4', - ], - 'mt_dns_prime_interval' => [ - 'friendly_name' => __('DNS Prime Interval', 'mactrack'), - 'description' => __('How often, in seconds do Mactrack scanning IP\'s need to be resolved to MAC addresses for DNS resolution. Using a larger number when you have several thousand devices will increase performance.', 'mactrack'), - 'method' => 'textbox', - 'default' => '120', - 'max_length' => '10', - 'size' => '4', - ], - 'mactrack_hdr_notification' => [ - 'friendly_name' => __('Notification Settings', 'mactrack'), - 'method' => 'spacer', - ], - 'mt_from_email' => [ - 'friendly_name' => __('Source Address', 'mactrack'), - 'description' => __('The source Email address for Mactrack Emails.', 'mactrack'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '100', - 'size' => '30', - ], - 'mt_from_name' => [ - 'friendly_name' => __('Source Email Name', 'mactrack'), - 'description' => __('The Source Email name for Mactrack Emails.', 'mactrack'), - 'method' => 'textbox', - 'default' => __('MACTrack Administrator', 'mactrack'), - 'max_length' => '100', - 'size' => '30', - ], - 'mt_macwatch_description' => [ - 'friendly_name' => __('MacWatch Default Body', 'mactrack'), - 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain ' - .'any valid html tags. It also supports replacement tags that will be processed when sending an Email. ' - .'Valid tags include , , , , , , , .', 'mactrack')), - 'method' => 'textarea', - 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), - 'class' => 'textAreaNotes', - 'max_length' => '512', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - ], - 'mt_macauth_emails' => [ - 'friendly_name' => __('MacAuth Report Email Addresses', 'mactrack'), - 'description' => __('A comma delimited list of users to receive the MacAuth Email notifications.', 'mactrack'), - 'method' => 'textarea', - 'default' => '', - 'class' => 'textAreaNotes', - 'max_length' => '255', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - ], - 'mt_macauth_email_frequency' => [ - 'friendly_name' => __('MacAuth Report Frequency', 'mactrack'), - 'description' => __('How often will the MacAuth Reports be Emailed.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'disabled', - 'array' => $mactrack_macauth_frequencies, - ], - 'mactrack_hdr_arpwatch' => [ - 'friendly_name' => __('Mactrack ArpWatch Settings', 'mactrack'), - 'method' => 'spacer', - ], - 'mt_arpwatch' => [ - 'friendly_name' => __('Enable ArpWatch', 'mactrack'), - 'description' => __('Should Mactrack also use ArpWatch data to supplement Mac to IP/DNS resolution?', 'mactrack'), - 'default' => '', - 'method' => 'checkbox', - ], - 'mt_arpwatch_path' => [ - 'friendly_name' => __('ArpWatch Database Path', 'mactrack'), - 'description' => __('The location of the ArpWatch Database file on the Cacti server.', 'mactrack'), - 'method' => 'filepath', - 'default' => '', - 'max_length' => '255', - 'size' => '60', - ], - 'mactrack_hdr_general' => [ - 'friendly_name' => __('SNMP Presets', 'mactrack'), - 'method' => 'spacer', - ], - 'mt_update_policy' => [ - 'friendly_name' => __('Update Policy for SNMP Options', 'mactrack'), - 'description' => __('Policy for synchronization of SNMP Options between Cacti devices and Mactrack Devices.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 1, - 'array' => $mactrack_update_policies, - ], - 'mt_snmp_ver' => [ - 'friendly_name' => __('Version', 'mactrack'), - 'description' => __('Default SNMP version for all new hosts.', 'mactrack'), - 'method' => 'drop_array', - 'default' => '2', - 'array' => $snmp_versions, - ], - 'mt_snmp_community' => [ - 'friendly_name' => __('Community', 'mactrack'), - 'description' => __('Default SNMP read community for all new hosts.', 'mactrack'), - 'method' => 'textbox', - 'default' => 'public', - 'max_length' => '100', - 'size' => '20', - ], - 'mt_snmp_communities' => [ - 'friendly_name' => __('Communities', 'mactrack'), - 'description' => __('Fill in the list of available SNMP read strings to test for this device. Each read string must be separated by a colon \':\'. These read strings will be tested sequentially if the primary read string is invalid.', 'mactrack'), - 'method' => 'textbox', - 'default' => 'public:private:secret', - 'max_length' => '255', - ], - 'mt_snmp_port' => [ - 'friendly_name' => __('Port', 'mactrack'), - 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), - 'method' => 'textbox', - 'default' => '161', - 'max_length' => '10', - 'size' => '4', - ], - 'mt_snmp_timeout' => [ - 'friendly_name' => __('Timeout', 'mactrack'), - 'description' => __('Default SNMP timeout in milli-seconds.', 'mactrack'), - 'method' => 'textbox', - 'default' => '500', - 'max_length' => '10', - 'size' => '4', - ], - 'mt_snmp_retries' => [ - 'friendly_name' => __('Retries', 'mactrack'), - 'description' => __('The number times the SNMP poller will attempt to reach the host before failing.', 'mactrack'), - 'method' => 'textbox', - 'default' => '3', - 'max_length' => '10', - 'size' => '4', - ], - ]; - - $ts = []; - foreach ($settings['path'] as $t => $ta) { - $ts[$t] = $ta; - if ('path_snmpget' == $t) { - $ts['path_snmpbulkwalk'] = [ - 'friendly_name' => __('snmpbulkwalk Binary Path', 'mactrack'), - 'description' => __('The path to your snmpbulkwalk binary.', 'mactrack'), - 'method' => 'textbox', - 'max_length' => '255', - ]; - } - } - $settings['path'] = $ts; - - $tabs_graphs += ['mactrack' => __('MacTrack Settings', 'mactrack')]; - - $settings_user += [ - 'mactrack' => [ - 'default_mactrack_tab' => [ - 'friendly_name' => __('Default Tab', 'mactrack'), - 'description' => __('Which MacTrack tab would you want to be your Default tab every time you goto the MacTrack second.', 'mactrack'), - 'method' => 'drop_array', - 'default' => 'sites', - 'array' => [ - 'sites' => __('Sites', 'mactrack'), - 'devices' => __('Devices', 'mactrack'), - 'ips' => __('IP Addresses', 'mactrack'), - 'macs' => __('Mac Addresses', 'mactrack'), - 'interfaces' => __('Interfaces', 'mactrack'), - 'dot1x' => __('dot1x Deta', 'mactrack'), - ], - ], - ], - ]; - - $settings['mail'] += [ - 'settings_proxy_header' => [ - 'friendly_name' => __('Internet Proxy Settings'), - 'collapsible' => 'true', - 'method' => 'spacer', - ], - 'settings_proxy_server' => [ - 'friendly_name' => __('Internet Proxy Address'), - 'description' => __('For either core Cacti Services or Plugins that require internet access, enter the proxy server and port here in the following format IP:PORT. For example 192.168.1.1:8080.'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '30', - ], - 'settings_proxy_user' => [ - 'friendly_name' => __('Internet Proxy User'), - 'description' => __('If your Internet Proxy requires a username, enter it here.'), - 'method' => 'textbox', - 'default' => '', - 'max_length' => '30', - 'size' => '10', - ], - 'settings_proxy_password' => [ - 'friendly_name' => __('Internet Proxy Password'), - 'description' => __('If your Internet Proxy requires a password, enter it here.'), - 'method' => 'textbox_password', - 'default' => '', - 'max_length' => '30', - 'size' => '10', - ], - ]; - - mactrack_check_upgrade(); +function mactrack_config_settings() { + global $tabs, $settings, $settings_user, $tabs_graphs, $snmp_versions, $mactrack_poller_frequencies, + $mactrack_data_retention, $mactrack_macauth_frequencies, $mactrack_update_policies; + + $tabs['mactrack'] = __('Mactrack', 'mactrack'); + + $settings['mactrack'] = [ + 'mactrack_hdr_timing' => [ + 'friendly_name' => __('General Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_collection_timing' => [ + 'friendly_name' => __('Scanning Frequency', 'mactrack'), + 'description' => __('Choose when to collect MAC and IP Addresses and Interface statistics from your network devices.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'disabled', + 'array' => $mactrack_poller_frequencies, + ], + 'mt_processes' => [ + 'friendly_name' => __('Concurrent Processes', 'mactrack'), + 'description' => __('Specify how many devices will be polled simultaneously until all devices have been polled.', 'mactrack'), + 'default' => '7', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_script_runtime' => [ + 'friendly_name' => __('Scanner Max Runtime', 'mactrack'), + 'description' => __('Specify the number of minutes a device scanning function will be allowed to run prior to the system assuming it has been completed. This setting will correct for abended scanning jobs.', 'mactrack'), + 'default' => '20', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_base_time' => [ + 'friendly_name' => __('Start Time for Data Collection', 'mactrack'), + 'description' => __('When would you like the first data collection to take place. All future data collection times will be based upon this start time. A good example would be 12:00AM.', 'mactrack'), + 'default' => '1:00am', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '8', + ], + 'mt_maint_time' => [ + 'friendly_name' => __('Database Maintenance Time', 'mactrack'), + 'description' => __('When should old database records be removed from the database. Please note that no access will be permitted to the port database while this action is taking place.', 'mactrack'), + 'default' => '12:00am', + 'method' => 'textbox', + 'max_length' => '10', + 'size' => '8', + ], + 'mt_maint_confirm' => [ + 'friendly_name' => __('Confirm Utilities Prompt', 'mactrack'), + 'description' => __('When using utilities, prompt for verification', 'mactrack'), + 'default' => read_config_option('deletion_verification'), + 'method' => 'checkbox', + ], + 'mt_data_retention' => [ + 'friendly_name' => __('Data Retention', 'mactrack'), + 'description' => __('How long should port MAC details be retained in the database.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '14', + 'array' => $mactrack_data_retention, + ], + 'mt_data_retention_ip' => [ + 'friendly_name' => __('Data Retention IPs', 'mactrack'), + 'description' => __('How long should discovered IPs details be retained in the database.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '3', + 'array' => $mactrack_data_retention, + ], + 'mt_ignorePorts_delim' => [ + 'friendly_name' => __('Switch Level Ignore Ports Delimiter', 'mactrack'), + 'description' => __('What delimiter should Mactrack use when parsing the Ignore Ports string for each switch.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '-1', + 'array' => [ + '-1' => __('Auto Detect', 'mactrack'), + ':' => __('Colon [:]', 'mactrack'), + '|' => __('Pipe [|]', 'mactrack'), + ' ' => __('Space [ ]', 'mactrack'), + ], + ], + 'mt_mac_format' => [ + 'friendly_name' => __('Mac Address Output Format', 'mactrack'), + 'description' => __('Format used for display.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'aa:bb:cc:dd:ee:ff', + 'array' => [ + 'aa:bb:cc:dd:ee:ff' => 'aa:bb:cc:dd:ee:ff', + 'aa-bb-cc-dd-ee-ff' => 'aa-bb-cc-dd-ee-ff', + 'aabb-ccdd-eeff' => 'aabb-ccdd-eeff', + 'aabbccddeeff' => 'aabbccddeeff', + 'aabb.ccdd.eeff' => 'aabb.ccdd.eeff', + ], + ], + 'mt_ignorePorts' => [ + 'method' => 'textbox', + 'friendly_name' => __('Ports to Ignore', 'mactrack'), + 'description' => __('Provide a regular expression of ifNames or ifDescriptions of ports to ignore in the interface list. For example, (Vlan|Loopback|Null).', 'mactrack'), + 'class' => 'textAreaNotes', + 'defaults' => '(Vlan|Loopback|Null)', + 'max_length' => '255', + 'size' => '80', + ], + 'mt_interface_high' => [ + 'friendly_name' => __('Bandwidth Usage Threshold', 'mactrack'), + 'description' => __('When reviewing network interface statistics, what bandwidth threshold do you want to view by default.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '70', + 'array' => [ + '-1' => __('N/A', 'mactrack'), + '10' => __('%d Percent', 10, 'mactrack'), + '20' => __('%d Percent', 20, 'mactrack'), + '30' => __('%d Percent', 30, 'mactrack'), + '40' => __('%d Percent', 40, 'mactrack'), + '50' => __('%d Percent', 50, 'mactrack'), + '60' => __('%d Percent', 60, 'mactrack'), + '70' => __('%d Percent', 70, 'mactrack'), + '80' => __('%d Percent', 80, 'mactrack'), + '90' => __('%d Percent', 90, 'mactrack'), + ], + ], + 'mt_hdr_rdns' => [ + 'friendly_name' => __('DNS Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_reverse_dns' => [ + 'friendly_name' => __('Perform Reverse DNS Name Resolution', 'mactrack'), + 'description' => __('Should Mactrack perform reverse DNS lookup of the IP addresses associated with ports. CAUTION: If DNS is not properly setup, this will slow scan time significantly.', 'mactrack'), + 'default' => '', + 'method' => 'checkbox', + ], + 'mt_dns_primary' => [ + 'friendly_name' => __('Primary DNS IP Address', 'mactrack'), + 'description' => __('Enter the primary DNS IP Address to utilize for reverse lookups.', 'mactrack'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '18', + ], + 'mt_dns_secondary' => [ + 'friendly_name' => __('Secondary DNS IP Address', 'mactrack'), + 'description' => __('Enter the secondary DNS IP Address to utilize for reverse lookups.', 'mactrack'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '18', + ], + 'mt_dns_timeout' => [ + 'friendly_name' => __('DNS Timeout', 'mactrack'), + 'description' => __('Please enter the DNS timeout in milliseconds. Mactrack uses a PHP based DNS resolver.', 'mactrack'), + 'method' => 'textbox', + 'default' => '500', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_dns_prime_interval' => [ + 'friendly_name' => __('DNS Prime Interval', 'mactrack'), + 'description' => __('How often, in seconds do Mactrack scanning IP\'s need to be resolved to MAC addresses for DNS resolution. Using a larger number when you have several thousand devices will increase performance.', 'mactrack'), + 'method' => 'textbox', + 'default' => '120', + 'max_length' => '10', + 'size' => '4', + ], + 'mactrack_hdr_notification' => [ + 'friendly_name' => __('Notification Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_from_email' => [ + 'friendly_name' => __('Source Address', 'mactrack'), + 'description' => __('The source Email address for Mactrack Emails.', 'mactrack'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '100', + 'size' => '30', + ], + 'mt_from_name' => [ + 'friendly_name' => __('Source Email Name', 'mactrack'), + 'description' => __('The Source Email name for Mactrack Emails.', 'mactrack'), + 'method' => 'textbox', + 'default' => __('MACTrack Administrator', 'mactrack'), + 'max_length' => '100', + 'size' => '30', + ], + 'mt_macwatch_description' => [ + 'friendly_name' => __('MacWatch Default Body', 'mactrack'), + 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain ' + . 'any valid html tags. It also supports replacement tags that will be processed when sending an Email. ' + . 'Valid tags include , , , , , , , .', 'mactrack')), + 'method' => 'textarea', + 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), + 'class' => 'textAreaNotes', + 'max_length' => '512', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + ], + 'mt_macauth_emails' => [ + 'friendly_name' => __('MacAuth Report Email Addresses', 'mactrack'), + 'description' => __('A comma delimited list of users to receive the MacAuth Email notifications.', 'mactrack'), + 'method' => 'textarea', + 'default' => '', + 'class' => 'textAreaNotes', + 'max_length' => '255', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + ], + 'mt_macauth_email_frequency' => [ + 'friendly_name' => __('MacAuth Report Frequency', 'mactrack'), + 'description' => __('How often will the MacAuth Reports be Emailed.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'disabled', + 'array' => $mactrack_macauth_frequencies, + ], + 'mactrack_hdr_arpwatch' => [ + 'friendly_name' => __('Mactrack ArpWatch Settings', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_arpwatch' => [ + 'friendly_name' => __('Enable ArpWatch', 'mactrack'), + 'description' => __('Should Mactrack also use ArpWatch data to supplement Mac to IP/DNS resolution?', 'mactrack'), + 'default' => '', + 'method' => 'checkbox', + ], + 'mt_arpwatch_path' => [ + 'friendly_name' => __('ArpWatch Database Path', 'mactrack'), + 'description' => __('The location of the ArpWatch Database file on the Cacti server.', 'mactrack'), + 'method' => 'filepath', + 'default' => '', + 'max_length' => '255', + 'size' => '60', + ], + 'mactrack_hdr_general' => [ + 'friendly_name' => __('SNMP Presets', 'mactrack'), + 'method' => 'spacer', + ], + 'mt_update_policy' => [ + 'friendly_name' => __('Update Policy for SNMP Options', 'mactrack'), + 'description' => __('Policy for synchronization of SNMP Options between Cacti devices and Mactrack Devices.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 1, + 'array' => $mactrack_update_policies, + ], + 'mt_snmp_ver' => [ + 'friendly_name' => __('Version', 'mactrack'), + 'description' => __('Default SNMP version for all new hosts.', 'mactrack'), + 'method' => 'drop_array', + 'default' => '2', + 'array' => $snmp_versions, + ], + 'mt_snmp_community' => [ + 'friendly_name' => __('Community', 'mactrack'), + 'description' => __('Default SNMP read community for all new hosts.', 'mactrack'), + 'method' => 'textbox', + 'default' => 'public', + 'max_length' => '100', + 'size' => '20', + ], + 'mt_snmp_communities' => [ + 'friendly_name' => __('Communities', 'mactrack'), + 'description' => __('Fill in the list of available SNMP read strings to test for this device. Each read string must be separated by a colon \':\'. These read strings will be tested sequentially if the primary read string is invalid.', 'mactrack'), + 'method' => 'textbox', + 'default' => 'public:private:secret', + 'max_length' => '255', + ], + 'mt_snmp_port' => [ + 'friendly_name' => __('Port', 'mactrack'), + 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), + 'method' => 'textbox', + 'default' => '161', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_snmp_timeout' => [ + 'friendly_name' => __('Timeout', 'mactrack'), + 'description' => __('Default SNMP timeout in milli-seconds.', 'mactrack'), + 'method' => 'textbox', + 'default' => '500', + 'max_length' => '10', + 'size' => '4', + ], + 'mt_snmp_retries' => [ + 'friendly_name' => __('Retries', 'mactrack'), + 'description' => __('The number times the SNMP poller will attempt to reach the host before failing.', 'mactrack'), + 'method' => 'textbox', + 'default' => '3', + 'max_length' => '10', + 'size' => '4', + ], + ]; + + $ts = []; + + foreach ($settings['path'] as $t => $ta) { + $ts[$t] = $ta; + + if ($t == 'path_snmpget') { + $ts['path_snmpbulkwalk'] = [ + 'friendly_name' => __('snmpbulkwalk Binary Path', 'mactrack'), + 'description' => __('The path to your snmpbulkwalk binary.', 'mactrack'), + 'method' => 'textbox', + 'max_length' => '255', + ]; + } + } + $settings['path'] = $ts; + + $tabs_graphs += ['mactrack' => __('MacTrack Settings', 'mactrack')]; + + $settings_user += [ + 'mactrack' => [ + 'default_mactrack_tab' => [ + 'friendly_name' => __('Default Tab', 'mactrack'), + 'description' => __('Which MacTrack tab would you want to be your Default tab every time you goto the MacTrack second.', 'mactrack'), + 'method' => 'drop_array', + 'default' => 'sites', + 'array' => [ + 'sites' => __('Sites', 'mactrack'), + 'devices' => __('Devices', 'mactrack'), + 'ips' => __('IP Addresses', 'mactrack'), + 'macs' => __('Mac Addresses', 'mactrack'), + 'interfaces' => __('Interfaces', 'mactrack'), + 'dot1x' => __('dot1x Deta', 'mactrack'), + ], + ], + ], + ]; + + $settings['mail'] += [ + 'settings_proxy_header' => [ + 'friendly_name' => __('Internet Proxy Settings'), + 'collapsible' => 'true', + 'method' => 'spacer', + ], + 'settings_proxy_server' => [ + 'friendly_name' => __('Internet Proxy Address'), + 'description' => __('For either core Cacti Services or Plugins that require internet access, enter the proxy server and port here in the following format IP:PORT. For example 192.168.1.1:8080.'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '30', + ], + 'settings_proxy_user' => [ + 'friendly_name' => __('Internet Proxy User'), + 'description' => __('If your Internet Proxy requires a username, enter it here.'), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '30', + 'size' => '10', + ], + 'settings_proxy_password' => [ + 'friendly_name' => __('Internet Proxy Password'), + 'description' => __('If your Internet Proxy requires a password, enter it here.'), + 'method' => 'textbox_password', + 'default' => '', + 'max_length' => '30', + 'size' => '10', + ], + ]; + + mactrack_check_upgrade(); } -function mactrack_draw_navigation_text($nav) -{ - $nav['mactrack_devices.php:'] = [ - 'title' => __('Mactrack Devices', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_devices.php', - 'level' => '1', - ]; - - $nav['mactrack_devices.php:edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_devices.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_devices.php:import'] = [ - 'title' => __('(Import)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_devices.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_devices.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_devices.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_snmp.php:'] = [ - 'title' => __('Mactrack SNMP Options', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_snmp.php', - 'level' => '1', - ]; - - $nav['mactrack_snmp.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_snmp.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_snmp.php:edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_snmp.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_snmp.php:item_edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_snmp.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_device_types.php:'] = [ - 'title' => __('Mactrack Device Types', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_device_types.php', - 'level' => '1', - ]; - - $nav['mactrack_device_types.php:edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_device_types.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_device_types.php:import'] = [ - 'title' => __('(Import)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_device_types.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_device_types.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_device_types.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_sites.php:'] = [ - 'title' => __('Mactrack Sites', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_sites.php', - 'level' => '1', - ]; - - $nav['mactrack_sites.php:edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_sites.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_sites.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_sites.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_macwatch.php:'] = [ - 'title' => __('Mac Address Tracking Utility', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_macwatch.php', - 'level' => '1', - ]; - - $nav['mactrack_macwatch.php:edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macwatch.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_macwatch.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macwatch.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_macauth.php:'] = [ - 'title' => __('Mac Address Authorization Utility', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_macauth.php', - 'level' => '1', - ]; - - $nav['mactrack_macauth.php:edit'] = [ - 'title' => __('(Edit)', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macauth.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_macauth.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_macauth.php:', - 'url' => '', - 'level' => '2', - ]; - - $nav['mactrack_vendormacs.php:'] = [ - 'title' => __('Mactrack Vendor Macs', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_vendormacs.php', - 'level' => '1', - ]; - - $nav['mactrack_view_macs.php:'] = [ - 'title' => __('Mactrack View Macs', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_macs.php', - 'level' => '0', - ]; - - $nav['mactrack_view_macs.php:actions'] = [ - 'title' => __('Actions', 'mactrack'), - 'mapping' => 'mactrack_view_macs.php:', - 'url' => '', - 'level' => '1', - ]; - - $nav['mactrack_view_dot1x.php:'] = [ - 'title' => __('Mactrack Dot1x View', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_dot1x.php', - 'level' => '0', - ]; - - $nav['mactrack_view_arp.php:'] = [ - 'title' => __('Mactrack IP Address Viewer', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_arp.php', - 'level' => '0', - ]; - - $nav['mactrack_view_interfaces.php:'] = [ - 'title' => __('Mactrack View Interfaces', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_interfaces.php', - 'level' => '0', - ]; - - $nav['mactrack_view_sites.php:'] = [ - 'title' => __('Mactrack View Sites', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_sites.php', - 'level' => '0', - ]; - - $nav['mactrack_view_ips.php:'] = [ - 'title' => __('Mactrack View IP Ranges', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_ips.php', - 'level' => '0', - ]; - - $nav['mactrack_view_devices.php:'] = [ - 'title' => __('Mactrack View Devices', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_devices.php', - 'level' => '0', - ]; - - $nav['mactrack_utilities.php:'] = [ - 'title' => __('Mactrack Utilities', 'mactrack'), - 'mapping' => 'index.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '1', - ]; - - $nav['mactrack_utilities.php:mactrack_utilities_perform_db_maint'] = [ - 'title' => __('Perform Database Maintenance', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_utilities.php:mactrack_utilities_purge_scanning_funcs'] = [ - 'title' => __('Refresh Scanning Functions', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_utilities.php:mactrack_utilities_truncate_ports_table'] = [ - 'title' => __('Truncate Port Results Table', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_utilities.php:mactrack_utilities_purge_aggregated_data'] = [ - 'title' => __('Truncate Aggregated Port Results Table', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_utilities.php:mactrack_utilities_recreate_aggregated_data'] = [ - 'title' => __('Truncate and Re-create Aggregated Port Results Table', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_utilities.php:mactrack_proc_status'] = [ - 'title' => __('View Mactrack Process Status', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_utilities.php:mactrack_refresh_oui_database'] = [ - 'title' => __('Refresh/Update Vendor MAC Database from IEEE', 'mactrack'), - 'mapping' => 'index.php:,mactrack_utilities.php:', - 'url' => 'mactrack_utilities.php', - 'level' => '2', - ]; - - $nav['mactrack_view_graphs.php:'] = [ - 'title' => __('Mactrack Graph Viewer', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_graphs.php', - 'level' => '0', - ]; - - $nav['mactrack_view_graphs.php:preview'] = [ - 'title' => __('Mactrack Graph Viewer', 'mactrack'), - 'mapping' => '', - 'url' => 'mactrack_view_graphs.php', - 'level' => '0', - ]; - - return $nav; +function mactrack_draw_navigation_text($nav) { + $nav['mactrack_devices.php:'] = [ + 'title' => __('Mactrack Devices', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_devices.php', + 'level' => '1', + ]; + + $nav['mactrack_devices.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_devices.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_devices.php:import'] = [ + 'title' => __('(Import)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_devices.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_devices.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_devices.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_snmp.php:'] = [ + 'title' => __('Mactrack SNMP Options', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_snmp.php', + 'level' => '1', + ]; + + $nav['mactrack_snmp.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_snmp.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_snmp.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_snmp.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_snmp.php:item_edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_snmp.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_device_types.php:'] = [ + 'title' => __('Mactrack Device Types', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_device_types.php', + 'level' => '1', + ]; + + $nav['mactrack_device_types.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_device_types.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_device_types.php:import'] = [ + 'title' => __('(Import)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_device_types.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_device_types.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_device_types.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_sites.php:'] = [ + 'title' => __('Mactrack Sites', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_sites.php', + 'level' => '1', + ]; + + $nav['mactrack_sites.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_sites.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_sites.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_sites.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macwatch.php:'] = [ + 'title' => __('Mac Address Tracking Utility', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_macwatch.php', + 'level' => '1', + ]; + + $nav['mactrack_macwatch.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macwatch.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macwatch.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macwatch.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macauth.php:'] = [ + 'title' => __('Mac Address Authorization Utility', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_macauth.php', + 'level' => '1', + ]; + + $nav['mactrack_macauth.php:edit'] = [ + 'title' => __('(Edit)', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macauth.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_macauth.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_macauth.php:', + 'url' => '', + 'level' => '2', + ]; + + $nav['mactrack_vendormacs.php:'] = [ + 'title' => __('Mactrack Vendor Macs', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_vendormacs.php', + 'level' => '1', + ]; + + $nav['mactrack_view_macs.php:'] = [ + 'title' => __('Mactrack View Macs', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_macs.php', + 'level' => '0', + ]; + + $nav['mactrack_view_macs.php:actions'] = [ + 'title' => __('Actions', 'mactrack'), + 'mapping' => 'mactrack_view_macs.php:', + 'url' => '', + 'level' => '1', + ]; + + $nav['mactrack_view_dot1x.php:'] = [ + 'title' => __('Mactrack Dot1x View', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_dot1x.php', + 'level' => '0', + ]; + + $nav['mactrack_view_arp.php:'] = [ + 'title' => __('Mactrack IP Address Viewer', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_arp.php', + 'level' => '0', + ]; + + $nav['mactrack_view_interfaces.php:'] = [ + 'title' => __('Mactrack View Interfaces', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_interfaces.php', + 'level' => '0', + ]; + + $nav['mactrack_view_sites.php:'] = [ + 'title' => __('Mactrack View Sites', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_sites.php', + 'level' => '0', + ]; + + $nav['mactrack_view_ips.php:'] = [ + 'title' => __('Mactrack View IP Ranges', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_ips.php', + 'level' => '0', + ]; + + $nav['mactrack_view_devices.php:'] = [ + 'title' => __('Mactrack View Devices', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_devices.php', + 'level' => '0', + ]; + + $nav['mactrack_utilities.php:'] = [ + 'title' => __('Mactrack Utilities', 'mactrack'), + 'mapping' => 'index.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '1', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_perform_db_maint'] = [ + 'title' => __('Perform Database Maintenance', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_purge_scanning_funcs'] = [ + 'title' => __('Refresh Scanning Functions', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_truncate_ports_table'] = [ + 'title' => __('Truncate Port Results Table', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_purge_aggregated_data'] = [ + 'title' => __('Truncate Aggregated Port Results Table', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_utilities_recreate_aggregated_data'] = [ + 'title' => __('Truncate and Re-create Aggregated Port Results Table', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_proc_status'] = [ + 'title' => __('View Mactrack Process Status', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_utilities.php:mactrack_refresh_oui_database'] = [ + 'title' => __('Refresh/Update Vendor MAC Database from IEEE', 'mactrack'), + 'mapping' => 'index.php:,mactrack_utilities.php:', + 'url' => 'mactrack_utilities.php', + 'level' => '2', + ]; + + $nav['mactrack_view_graphs.php:'] = [ + 'title' => __('Mactrack Graph Viewer', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_graphs.php', + 'level' => '0', + ]; + + $nav['mactrack_view_graphs.php:preview'] = [ + 'title' => __('Mactrack Graph Viewer', 'mactrack'), + 'mapping' => '', + 'url' => 'mactrack_view_graphs.php', + 'level' => '0', + ]; + + return $nav; } -function mactrack_show_tab() -{ - global $config, $user_auth_realm_filenames; +function mactrack_show_tab() { + global $config, $user_auth_realm_filenames; - include_once $config['base_path'].'/plugins/mactrack/lib/mactrack_functions.php'; + include_once $config['base_path'] . '/plugins/mactrack/lib/mactrack_functions.php'; - if (!isset_request_var('report')) { - set_request_var('report', 'sites'); - } + if (!isset_request_var('report')) { + set_request_var('report', 'sites'); + } - if (api_user_realm_auth('mactrack_view_macs.php')) { - if (substr_count($_SERVER['REQUEST_URI'], 'mactrack_view_')) { - echo ''.__('MacTrack', 'mactrack').''; - } else { - echo ''.__('MacTrack', 'mactrack').''; - } - } + if (api_user_realm_auth('mactrack_view_macs.php')) { + if (substr_count($_SERVER['REQUEST_URI'], 'mactrack_view_')) { + print '' . __('MacTrack', 'mactrack') . ''; + } else { + print '' . __('MacTrack', 'mactrack') . ''; + } + } } -function mactrack_config_arrays() -{ - global $mactrack_device_types, $mactrack_search_types, $messages; - global $menu, $menu_glyphs, $config, $rows_selector; - global $mactrack_poller_frequencies, $mactrack_data_retention, $refresh_interval; - global $mactrack_macauth_frequencies, $mactrack_duplexes, $mactrack_update_policies; - - if (isset($_SESSION['mactrack_message']) && '' != $_SESSION['mactrack_message']) { - $messages['mactrack_message'] = ['message' => $_SESSION['mactrack_message'], 'type' => 'info']; - kill_session_var('mactrack_message'); - } - - $refresh_interval = [ - 5 => __('%d Seconds', 5, 'mactrack'), - 10 => __('%d Seconds', 10, 'mactrack'), - 20 => __('%d Seconds', 20, 'mactrack'), - 30 => __('%d Seconds', 30, 'mactrack'), - 60 => __('%d Minute', 1, 'mactrack'), - 300 => __('%d Minutes', 5, 'mactrack'), - ]; - - $mactrack_device_types = [ - 1 => __('Switch/Hub', 'mactrack'), - 2 => __('Switch/Router', 'mactrack'), - 3 => __('Router', 'mactrack'), - ]; - - $mactrack_search_types = [ - 1 => '', - 2 => __('Matches', 'mactrack'), - 3 => __('Contains', 'mactrack'), - 4 => __('Begins With', 'mactrack'), - 5 => __('Does Not Contain', 'mactrack'), - 6 => __('Does Not Begin With', 'mactrack'), - 7 => __('Is Null', 'mactrack'), - 8 => __('Is Not Null', 'mactrack'), - ]; - - $mactrack_duplexes = [ - 1 => __('Unknown', 'mactrack'), - 2 => __('Half', 'mactrack'), - 3 => __('Full', 'mactrack'), - ]; - - $mactrack_update_policies = [ - 1 => __('None', 'mactrack'), - 2 => __('Sync Cacti Device to Mactrack Device', 'mactrack'), - 3 => __('Sync Mactrack Device to Cacti Device', 'mactrack'), - ]; - - $rows_selector = [ - -1 => __('Default', 'mactrack'), - 10 => '10', - 15 => '15', - 20 => '20', - 30 => '30', - 50 => '50', - 100 => '100', - 500 => '500', - 1000 => '1000', - -2 => __('All', 'mactrack'), - ]; - - $mactrack_poller_frequencies = [ - 'disabled' => __('Disabled', 'mactrack'), - '5' => __('Every %d Minutes', 5, 'mactrack'), - '10' => __('Every %d Minutes', 10, 'mactrack'), - '15' => __('Every %d Minutes', 15, 'mactrack'), - '20' => __('Every %d Minutes', 20, 'mactrack'), - '30' => __('Every %d Minutes', 30, 'mactrack'), - '60' => __('Every %d Hour', 1, 'mactrack'), - '120' => __('Every %d Hours', 2, 'mactrack'), - '240' => __('Every %d Hours', 4, 'mactrack'), - '480' => __('Every %d Hours', 8, 'mactrack'), - '720' => __('Every %d Hours', 12, 'mactrack'), - '1440' => __('Every Day', 'mactrack'), - ]; - - $mactrack_data_retention = [ - '3' => __('%d Days', 3, 'mactrack'), - '7' => __('%d Days', 7, 'mactrack'), - '10' => __('%d Days', 10, 'mactrack'), - '14' => __('%d Days', 14, 'mactrack'), - '20' => __('%d Days', 20, 'mactrack'), - '30' => __('%d Month', 1, 'mactrack'), - '60' => __('%d Months', 2, 'mactrack'), - '120' => __('%d Months', 4, 'mactrack'), - '240' => __('%d Months', 8, 'mactrack'), - '365' => __('%d Year', 1, 'mactrack'), - ]; - - $mactrack_macauth_frequencies = [ - 'disabled' => __('Disabled', 'mactrack'), - '0' => __('On Scan Completion', 'mactrack'), - '720' => __('Every %d Hours', 12), - '1440' => __('Every Day', 'mactrack'), - '2880' => __('Every %d Days', 2), - '10080' => __('Every Week', 'mactrack'), - ]; - - $menu2 = []; - foreach ($menu as $temp => $temp2) { - $menu2[$temp] = $temp2; - if ($temp == __('Management')) { - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_sites.php'] = __('Sites', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_devices.php'] = __('Devices', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_snmp.php'] = __('SNMP Options', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_device_types.php'] = __('Device Types', 'mactrack'); - $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_vendormacs.php'] = __('Vendor Macs', 'mactrack'); - $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macwatch.php'] = __('Mac Watch', 'mactrack'); - $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macauth.php'] = __('Mac Authorizations', 'mactrack'); - $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_utilities.php'] = __('Tracking Utilities', 'mactrack'); - } - } - $menu = $menu2; - - if (cacti_version_compare(CACTI_VERSION, '1.2', '<')) { - $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield'; - } else { - $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield-alt'; - } - $menu_glyphs[__('Mactrack Tools', 'mactrack')] = 'fa fa-bullhorn'; +function mactrack_config_arrays() { + global $mactrack_device_types, $mactrack_search_types, $messages; + global $menu, $menu_glyphs, $config, $rows_selector; + global $mactrack_poller_frequencies, $mactrack_data_retention, $refresh_interval; + global $mactrack_macauth_frequencies, $mactrack_duplexes, $mactrack_update_policies; + + if (isset($_SESSION['mactrack_message']) && $_SESSION['mactrack_message'] != '') { + $messages['mactrack_message'] = ['message' => $_SESSION['mactrack_message'], 'type' => 'info']; + kill_session_var('mactrack_message'); + } + + $refresh_interval = [ + 5 => __('%d Seconds', 5, 'mactrack'), + 10 => __('%d Seconds', 10, 'mactrack'), + 20 => __('%d Seconds', 20, 'mactrack'), + 30 => __('%d Seconds', 30, 'mactrack'), + 60 => __('%d Minute', 1, 'mactrack'), + 300 => __('%d Minutes', 5, 'mactrack'), + ]; + + $mactrack_device_types = [ + 1 => __('Switch/Hub', 'mactrack'), + 2 => __('Switch/Router', 'mactrack'), + 3 => __('Router', 'mactrack'), + ]; + + $mactrack_search_types = [ + 1 => '', + 2 => __('Matches', 'mactrack'), + 3 => __('Contains', 'mactrack'), + 4 => __('Begins With', 'mactrack'), + 5 => __('Does Not Contain', 'mactrack'), + 6 => __('Does Not Begin With', 'mactrack'), + 7 => __('Is Null', 'mactrack'), + 8 => __('Is Not Null', 'mactrack'), + ]; + + $mactrack_duplexes = [ + 1 => __('Unknown', 'mactrack'), + 2 => __('Half', 'mactrack'), + 3 => __('Full', 'mactrack'), + ]; + + $mactrack_update_policies = [ + 1 => __('None', 'mactrack'), + 2 => __('Sync Cacti Device to Mactrack Device', 'mactrack'), + 3 => __('Sync Mactrack Device to Cacti Device', 'mactrack'), + ]; + + $rows_selector = [ + -1 => __('Default', 'mactrack'), + 10 => '10', + 15 => '15', + 20 => '20', + 30 => '30', + 50 => '50', + 100 => '100', + 500 => '500', + 1000 => '1000', + -2 => __('All', 'mactrack'), + ]; + + $mactrack_poller_frequencies = [ + 'disabled' => __('Disabled', 'mactrack'), + '5' => __('Every %d Minutes', 5, 'mactrack'), + '10' => __('Every %d Minutes', 10, 'mactrack'), + '15' => __('Every %d Minutes', 15, 'mactrack'), + '20' => __('Every %d Minutes', 20, 'mactrack'), + '30' => __('Every %d Minutes', 30, 'mactrack'), + '60' => __('Every %d Hour', 1, 'mactrack'), + '120' => __('Every %d Hours', 2, 'mactrack'), + '240' => __('Every %d Hours', 4, 'mactrack'), + '480' => __('Every %d Hours', 8, 'mactrack'), + '720' => __('Every %d Hours', 12, 'mactrack'), + '1440' => __('Every Day', 'mactrack'), + ]; + + $mactrack_data_retention = [ + '3' => __('%d Days', 3, 'mactrack'), + '7' => __('%d Days', 7, 'mactrack'), + '10' => __('%d Days', 10, 'mactrack'), + '14' => __('%d Days', 14, 'mactrack'), + '20' => __('%d Days', 20, 'mactrack'), + '30' => __('%d Month', 1, 'mactrack'), + '60' => __('%d Months', 2, 'mactrack'), + '120' => __('%d Months', 4, 'mactrack'), + '240' => __('%d Months', 8, 'mactrack'), + '365' => __('%d Year', 1, 'mactrack'), + ]; + + $mactrack_macauth_frequencies = [ + 'disabled' => __('Disabled', 'mactrack'), + '0' => __('On Scan Completion', 'mactrack'), + '720' => __('Every %d Hours', 12), + '1440' => __('Every Day', 'mactrack'), + '2880' => __('Every %d Days', 2), + '10080' => __('Every Week', 'mactrack'), + ]; + + $menu2 = []; + + foreach ($menu as $temp => $temp2) { + $menu2[$temp] = $temp2; + + if ($temp == __('Management')) { + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_sites.php'] = __('Sites', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_devices.php'] = __('Devices', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_snmp.php'] = __('SNMP Options', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_device_types.php'] = __('Device Types', 'mactrack'); + $menu2[__('Mactrack', 'mactrack')]['plugins/mactrack/mactrack_vendormacs.php'] = __('Vendor Macs', 'mactrack'); + $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macwatch.php'] = __('Mac Watch', 'mactrack'); + $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_macauth.php'] = __('Mac Authorizations', 'mactrack'); + $menu2[__('Mactrack Tools', 'mactrack')]['plugins/mactrack/mactrack_utilities.php'] = __('Tracking Utilities', 'mactrack'); + } + } + $menu = $menu2; + + if (cacti_version_compare(CACTI_VERSION, '1.2', '<')) { + $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield'; + } else { + $menu_glyphs[__('Mactrack', 'mactrack')] = 'fa fa-shield-alt'; + } + $menu_glyphs[__('Mactrack Tools', 'mactrack')] = 'fa fa-bullhorn'; } -function mactrack_config_form() -{ - global $fields_mactrack_device_type_edit, $fields_mactrack_device_edit, $fields_mactrack_site_edit; - global $fields_mactrack_snmp_edit, $fields_mactrack_snmp_item, $fields_mactrack_snmp_item_edit; - global $mactrack_device_types, $snmp_versions, $fields_mactrack_macw_edit, $fields_mactrack_maca_edit; - global $snmp_priv_protocols, $snmp_auth_protocols; - - // file: mactrack_device_types.php, action: edit - $fields_mactrack_device_type_edit = [ - 'spacer0' => [ - 'method' => 'spacer', - 'friendly_name' => __('Device Scanning Function Options', 'mactrack'), - ], - 'description' => [ - 'method' => 'textbox', - 'friendly_name' => __('Description', 'mactrack'), - 'description' => __('Give this device type a meaningful description.', 'mactrack'), - 'value' => '|arg1:description|', - 'max_length' => '250', - ], - 'vendor' => [ - 'method' => 'textbox', - 'friendly_name' => __('Vendor', 'mactrack'), - 'description' => __('Fill in the name for the vendor of this device type.', 'mactrack'), - 'value' => '|arg1:vendor|', - 'max_length' => '250', - ], - 'device_type' => [ - 'method' => 'drop_array', - 'friendly_name' => __('Device Type', 'mactrack'), - 'description' => __('Choose the type of device.', 'mactrack'), - 'value' => '|arg1:device_type|', - 'default' => 1, - 'array' => $mactrack_device_types, - ], - 'sysDescr_match' => [ - 'method' => 'textbox', - 'friendly_name' => __('System Description Match', 'mactrack'), - 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), - 'value' => '|arg1:sysDescr_match|', - 'max_length' => '250', - ], - 'sysObjectID_match' => [ - 'method' => 'textbox', - 'friendly_name' => __('Vendor SNMP Object ID Match', 'mactrack'), - 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), - 'value' => '|arg1:sysObjectID_match|', - 'max_length' => '250', - ], - 'scanning_function' => [ - 'method' => 'drop_sql', - 'friendly_name' => __('MAC Address Scanning Function', 'mactrack'), - 'description' => __('Mactrack scanning function to call in order to obtain and store port details. The function name is all that is required. The following four parameters are assumed and will always be appended: \'my_function($site, &$device, $lowport, $highport)\'. There is no function required for a pure router.', 'mactrack'), - 'value' => '|arg1:scanning_function|', - 'default' => 0, - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select scanning_function as id, scanning_function as name from mac_track_scanning_functions where type="1" order by scanning_function', - ], - 'ip_scanning_function' => [ - 'method' => 'drop_sql', - 'friendly_name' => __('IP Address Scanning Function', 'mactrack'), - 'description' => __('Mactrack scanning function specific to Layer3 devices that track IP Addresses.', 'mactrack'), - 'value' => '|arg1:ip_scanning_function|', - 'default' => 0, - 'none_value' => __('None', 'mactrack'), - 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="2" ORDER BY scanning_function', - ], - 'dot1x_scanning_function' => [ - 'method' => 'drop_sql', - 'friendly_name' => __('802.1x Scanning Function', 'mactrack'), - 'description' => __('Mactrack scanning function specific to Switches with dot1x enabled.', 'mactrack'), - 'value' => '|arg1:dot1x_scanning_function|', - 'default' => '', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="3" ORDER BY scanning_function', - ], - 'serial_number_oid' => [ - 'method' => 'textbox', - 'friendly_name' => __('Serial Number Base OID', 'mactrack'), - 'description' => __('The SNMP OID used to obtain this device types serial number to be stored in the Mactrack Asset Information table.', 'mactrack'), - 'value' => '|arg1:serial_number_oid|', - 'max_length' => '100', - 'default' => '', - ], - 'serial_number_oid_type' => [ - 'method' => 'drop_array', - 'friendly_name' => __('Serial Number Collection Method', 'mactrack'), - 'description' => __('How is the serial number collected for this OID. If \'SNMP Walk\', we assume multiple serial numbers. If \'Get\', it will be only one..', 'mactrack'), - 'value' => '|arg1:serial_number_oid_method|', - 'default' => 'get', - 'array' => ['get' => __('SNMP Get', 'mactrack'), 'walk' => __('SNMP Walk', 'mactrack')], - ], - 'lowPort' => [ - 'method' => 'textbox', - 'friendly_name' => __('Low User Port Number', 'mactrack'), - 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), - 'value' => '|arg1:lowPort|', - 'default' => read_config_option('mt_port_lowPort'), - 'max_length' => '100', - 'size' => '10', - ], - 'highPort' => [ - 'method' => 'textbox', - 'friendly_name' => __('High User Port Number', 'mactrack'), - 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), - 'value' => '|arg1:highPort|', - 'default' => read_config_option('mt_port_highPort'), - 'max_length' => '100', - 'size' => '10', - ], - 'disabled' => [ - 'method' => 'checkbox', - 'friendly_name' => __('Disabled', 'mactrack'), - 'description' => __('Disabled device type is not used.', 'mactrack'), - 'value' => '|arg1:disabled|', - 'default' => '', - ], - 'device_type_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:device_type_id|', - ], - '_device_type_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:device_type_id|', - ], - 'save_component_device_type' => [ - 'method' => 'hidden', - 'value' => '1', - ], - ]; - - // file: mactrack_snmp.php, action: edit - $fields_mactrack_snmp_edit = [ - 'name' => [ - 'method' => 'textbox', - 'friendly_name' => __('Name', 'mactrack'), - 'description' => __('Fill in the name of this SNMP option set.', 'mactrack'), - 'value' => '|arg1:name|', - 'default' => '', - 'max_length' => '100', - 'size' => '40', - ], - ]; - - // file: mactrack_snmp.php, action: item_edit - $fields_mactrack_snmp_item = [ - 'snmp_version' => [ - 'method' => 'drop_array', - 'friendly_name' => __('SNMP Version', 'mactrack'), - 'description' => __('Choose the SNMP version for this host.', 'mactrack'), - 'value' => '|arg1:snmp_version|', - 'default' => read_config_option('mt_snmp_ver'), - 'array' => $snmp_versions, - ], - 'snmp_readstring' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Community String', 'mactrack'), - 'description' => __('Fill in the SNMP read community for this device.', 'mactrack'), - 'value' => '|arg1:snmp_readstring|', - 'default' => read_config_option('mt_snmp_community'), - 'max_length' => '100', - 'size' => '20', - ], - 'snmp_port' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Port', 'mactrack'), - 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), - 'value' => '|arg1:snmp_port|', - 'max_length' => '8', - 'default' => read_config_option('mt_snmp_port'), - 'size' => '10', - ], - 'snmp_timeout' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Timeout', 'mactrack'), - 'description' => __('The maximum number of milliseconds Cacti will wait for an SNMP response (does not work with php-snmp support).', 'mactrack'), - 'value' => '|arg1:snmp_timeout|', - 'max_length' => '8', - 'default' => read_config_option('mt_snmp_timeout'), - 'size' => '10', - ], - 'snmp_retries' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Retries', 'mactrack'), - 'description' => __('The maximum number of attempts to reach a device via an SNMP readstring prior to giving up.', 'mactrack'), - 'value' => '|arg1:snmp_retries|', - 'max_length' => '8', - 'default' => read_config_option('mt_snmp_retries'), - 'size' => '10', - ], - 'max_oids' => [ - 'method' => 'textbox', - 'friendly_name' => __('Maximum OID\'s Per Get Request', 'mactrack'), - 'description' => __('Specified the number of OID\'s that can be obtained in a single SNMP Get request.', 'mactrack'), - 'value' => '|arg1:max_oids|', - 'max_length' => '8', - 'default' => read_config_option('max_get_size'), - 'size' => '15', - ], - 'snmp_username' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Username (v3)', 'mactrack'), - 'description' => __('SNMP v3 username for this device.', 'mactrack'), - 'value' => '|arg1:snmp_username|', - 'default' => read_config_option('snmp_username'), - 'max_length' => '50', - 'size' => '15', - ], - 'snmp_password' => [ - 'method' => 'textbox_password', - 'friendly_name' => __('SNMP Password (v3)', 'mactrack'), - 'description' => __('SNMP v3 password for this device.', 'mactrack'), - 'value' => '|arg1:snmp_password|', - 'default' => read_config_option('snmp_password'), - 'max_length' => '50', - 'size' => '15', - ], - 'snmp_auth_protocol' => [ - 'method' => 'drop_array', - 'friendly_name' => __('SNMP Auth Protocol (v3)', 'mactrack'), - 'description' => __('Choose the SNMPv3 Authorization Protocol.', 'mactrack'), - 'value' => '|arg1:snmp_auth_protocol|', - 'default' => read_config_option('snmp_auth_protocol'), - 'array' => $snmp_auth_protocols, - ], - 'snmp_priv_passphrase' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Privacy Passphrase (v3)', 'mactrack'), - 'description' => __('Choose the SNMPv3 Privacy Passphrase.', 'mactrack'), - 'value' => '|arg1:snmp_priv_passphrase|', - 'default' => read_config_option('snmp_priv_passphrase'), - 'max_length' => '200', - 'size' => '40', - ], - 'snmp_priv_protocol' => [ - 'method' => 'drop_array', - 'friendly_name' => __('SNMP Privacy Protocol (v3)', 'mactrack'), - 'description' => __('Choose the SNMPv3 Privacy Protocol.', 'mactrack'), - 'value' => '|arg1:snmp_priv_protocol|', - 'default' => read_config_option('snmp_priv_protocol'), - 'array' => $snmp_priv_protocols, - ], - 'snmp_context' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Context (v3)', 'mactrack'), - 'description' => __('Enter the SNMP v3 Context to use for this device.', 'mactrack'), - 'value' => '|arg1:snmp_context|', - 'default' => '', - 'max_length' => '64', - 'size' => '40', - ], - 'snmp_engine_id' => [ - 'method' => 'textbox', - 'friendly_name' => __('SNMP Engine ID (v3)', 'mactrack'), - 'description' => __('Enter the SNMP v3 Engine ID to use for this device.', 'mactrack'), - 'value' => '|arg1:snmp_engine_id|', - 'default' => '', - 'max_length' => '64', - 'size' => '40', - ], - ]; - - // file: mactrack_devices.php, action: edit - $fields_mactrack_device_edit = [ - 'spacer0' => [ - 'method' => 'spacer', - 'friendly_name' => __('General Device Settings', 'mactrack'), - ], - 'device_name' => [ - 'method' => 'textbox', - 'friendly_name' => __('Device Name', 'mactrack'), - 'description' => __('Give this device a meaningful name.', 'mactrack'), - 'value' => '|arg1:device_name|', - 'max_length' => '250', - ], - 'hostname' => [ - 'method' => 'textbox', - 'friendly_name' => __('Hostname', 'mactrack'), - 'description' => __('Fill in the fully qualified hostname for this device.', 'mactrack'), - 'value' => '|arg1:hostname|', - 'max_length' => '250', - ], - 'host_id' => [ - 'friendly_name' => __('Related Cacti Host', 'mactrack'), - 'description' => __('Given Mactrack Host is connected to this Cacti Host.', 'mactrack'), - // 'method' => 'view', - 'method' => 'drop_sql', - 'value' => '|arg1:host_id|', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select id,CONCAT_WS("",description," (",hostname,")") as name from host order by description,hostname', - ], - 'device_type_id' => [ - 'method' => 'drop_sql', - 'friendly_name' => 'Device Type', - 'description' => 'Choose the type of device.', - 'value' => '|arg1:device_type_id|', - 'default' => 0, - 'none_value' => 'Not Detected', - 'sql' => 'select device_type_id as id,description as name from mac_track_device_types order by description', - ], - 'scan_type' => [ - 'method' => 'drop_array', - 'friendly_name' => __('Scan Type', 'mactrack'), - 'description' => __('Choose the scan type you wish to perform on this device.', 'mactrack'), - 'value' => '|arg1:scan_type|', - 'default' => 1, - 'array' => $mactrack_device_types, - ], - 'site_id' => [ - 'method' => 'drop_sql', - 'friendly_name' => __('Site Name', 'mactrack'), - 'description' => __('Choose the site to associate with this device.', 'mactrack'), - 'value' => '|arg1:site_id|', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select site_id as id,site_name as name from mac_track_sites order by name', - ], - 'notes' => [ - 'method' => 'textarea', - 'friendly_name' => __('Device Notes', 'mactrack'), - 'description' => __('This field value is useful to save general information about a specific device.', 'mactrack'), - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'value' => '|arg1:notes|', - 'max_length' => '255', - ], - 'disabled' => [ - 'method' => 'checkbox', - 'friendly_name' => __('Disable Device', 'mactrack'), - 'description' => __('Check this box to disable all checks for this host.', 'mactrack'), - 'value' => '|arg1:disabled|', - 'default' => '', - 'form_id' => false, - ], - 'spacer1' => [ - 'method' => 'spacer', - 'friendly_name' => __('Switch/Hub, Switch/Router Settings', 'mactrack'), - ], - 'ignorePorts' => [ - 'method' => 'textarea', - 'friendly_name' => __('Ports to Ignore', 'mactrack'), - 'description' => __('Provide a list of ports on a specific switch/hub whose MAC results should be ignored. Ports such as link/trunk ports that can not be distinguished from other user ports are examples. Each port number must be separated by a colon, pipe, or a space \':\', \'|\', \' \'. For example, \'Fa0/1: Fa1/23\' or \'Fa0/1 Fa1/23\' would be acceptable for some manufacturers switch types.', 'mactrack'), - 'value' => '|arg1:ignorePorts|', - 'default' => '', - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'max_length' => '255', - ], - 'scan_trunk_port' => [ - 'method' => 'textarea', - 'friendly_name' => 'Trunk Ports to Scan', - 'description' => 'A comma delimited list of Port Number to be scanned. Some VMware network port will be configured with 802.1Q', - 'value' => '|arg1:scan_trunk_port|', - 'default' => '', - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'max_length' => '255', - ], - 'spacer2' => [ - 'method' => 'spacer', - 'friendly_name' => __('SNMP Options', 'mactrack'), - ], - 'snmp_options' => [ - 'method' => 'drop_sql', - 'friendly_name' => __('SNMP Options', 'mactrack'), - 'description' => __('You can use specific SNMP settings or select SNMP set. In the second case, mactrack tries to find correct settings from SNMP set', 'mactrack'), - 'value' => '|arg1:snmp_options|', - 'none_value' => __('None', 'mactrack'), - 'sql' => 'select * from mac_track_snmp order by name', - ], - 'snmp_readstrings' => [ - 'method' => 'view', - 'friendly_name' => __('Read Strings', 'mactrack'), - 'description' => __('DEPRECATED: SNMP community strings', 'mactrack'), - 'value' => '|arg1:snmp_readstrings|', - ], - 'spacer3' => [ - 'method' => 'spacer', - 'friendly_name' => __('Specific SNMP Settings', 'mactrack'), - ], - ]; - - $fields_mactrack_device_edit += $fields_mactrack_snmp_item; - - $fields_mactrack_device_edit += [ - 'spacer4' => [ - 'method' => 'spacer', - 'friendly_name' => __('Connectivity Options', 'mactrack'), - ], - 'term_type' => [ - 'method' => 'drop_array', - 'friendly_name' => __('Terminal Type', 'mactrack'), - 'description' => __('Choose the terminal type that you use to connect to this device.', 'mactrack'), - 'value' => '|arg1:term_type|', - 'default' => 1, - 'array' => [ - 0 => __('None', 'mactrack'), - 1 => __('Telnet', 'mactrack'), - 2 => __('SSH', 'mactrack'), - 3 => __('HTTP', 'mactrack'), - 4 => __('HTTPS', 'mactrack')], - ], - 'user_name' => [ - 'method' => 'textbox', - 'friendly_name' => __('User Name', 'mactrack'), - 'description' => __('The user name to be used for your custom authentication method. Examples include SSH, RSH, HTML, etc.', 'mactrack'), - 'value' => '|arg1:user_name|', - 'default' => '', - 'max_length' => '40', - 'size' => '20', - ], - 'user_password' => [ - 'method' => 'textbox_password', - 'friendly_name' => __('Password', 'mactrack'), - 'description' => __('The password to be used for your custom authentication.', 'mactrack'), - 'value' => '|arg1:user_password|', - 'default' => '', - 'max_length' => '40', - 'size' => '20', - ], - 'private_key_path' => [ - 'method' => 'filepath', - 'friendly_name' => __('Private Key Path', 'mactrack'), - 'description' => __('The path to the private key used for SSH authentication.', 'mactrack'), - 'value' => '|arg1:private_key_path|', - 'default' => '', - 'max_length' => '128', - 'size' => '40', - ], - 'device_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:device_id|', - ], - '_device_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:device_id|', - ], - 'save_component_device' => [ - 'method' => 'hidden', - 'value' => '1', - ], - ]; - - // file: mactrack_snmp.php, action: item_edit - $fields_mactrack_snmp_item_edit = $fields_mactrack_snmp_item + [ - 'sequence' => [ - 'method' => 'view', - 'friendly_name' => __('Sequence', 'mactrack'), - 'description' => __('Sequence of Item.', 'mactrack'), - 'value' => '|arg1:sequence|'], - ]; - - // file: mactrack_sites.php, action: edit - $fields_mactrack_site_edit = [ - 'spacer0' => [ - 'method' => 'spacer', - 'friendly_name' => __('General Site Settings', 'mactrack'), - ], - 'site_name' => [ - 'method' => 'textbox', - 'friendly_name' => __('Site Name', 'mactrack'), - 'description' => __('Please enter a reasonable name for this site.', 'mactrack'), - 'value' => '|arg1:site_name|', - 'size' => '70', - 'max_length' => '250', - ], - 'customer_contact' => [ - 'method' => 'textbox', - 'friendly_name' => __('Primary Customer Contact', 'mactrack'), - 'description' => __('The principal customer contact name and number for this site.', 'mactrack'), - 'value' => '|arg1:customer_contact|', - 'size' => '70', - 'max_length' => '150', - ], - 'netops_contact' => [ - 'method' => 'textbox', - 'friendly_name' => __('NetOps Contact', 'mactrack'), - 'description' => __('Please principal network support contact name and number for this site.', 'mactrack'), - 'value' => '|arg1:netops_contact|', - 'size' => '70', - 'max_length' => '150', - ], - 'facilities_contact' => [ - 'method' => 'textbox', - 'friendly_name' => __('Facilities Contact', 'mactrack'), - 'description' => __('Please principal facilities/security contact name and number for this site.', 'mactrack'), - 'value' => '|arg1:facilities_contact|', - 'size' => '70', - 'max_length' => '150', - ], - 'site_info' => [ - 'method' => 'textarea', - 'friendly_name' => __('Site Information', 'mactrack'), - 'class' => 'textAreaNotes', - 'textarea_rows' => '3', - 'textarea_cols' => '80', - 'description' => __('Provide any site-specific information, in free form, that allows you to better manage this location.', 'mactrack'), - 'value' => '|arg1:site_info|', - 'max_length' => '255', - ], - 'skip_vlans' => [ - 'method' => 'textarea', - 'friendly_name' => 'VLAN ID to Skipped Scan', - 'class' => 'textAreaNotes', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - 'description' => 'A comma delimited list of VLAN ID always forced to be skipped scanning.', - 'value' => '|arg1:skip_vlans|', - 'max_length' => '1024', - ], - 'scan_vlans' => [ - 'method' => 'textarea', - 'friendly_name' => 'VLAN ID to Scan', - 'class' => 'textAreaNotes', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - 'description' => 'A comma delimited list of VLAN ID to be scanned', - 'value' => '|arg1:scan_vlans|', - 'max_length' => '1024', - ], - 'site_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:site_id|', - ], - '_site_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:site_id|', - ], - 'save_component_site' => [ - 'method' => 'hidden', - 'value' => '1', - ], - ]; - - // file: mactrack_macwatch.php, action: edit - $fields_mactrack_macw_edit = [ - 'spacer0' => [ - 'method' => 'spacer', - 'friendly_name' => __('General Mac Address Tracking Settings', 'mactrack'), - ], - 'mac_address' => [ - 'method' => 'textbox', - 'friendly_name' => __('MAC Address', 'mactrack'), - 'description' => __('Please enter the MAC Address to be watched for.', 'mactrack'), - 'value' => '|arg1:mac_address|', - 'default' => '', - 'max_length' => '40', - ], - 'name' => [ - 'method' => 'textbox', - 'friendly_name' => __('MAC Tracking Name/Email Subject', 'mactrack'), - 'description' => __('Please enter a reasonable name for this MAC Tracking entry. This information will be in the subject line of your Email', 'mactrack'), - 'value' => '|arg1:name|', - 'size' => '70', - 'max_length' => '250', - ], - 'description' => [ - 'friendly_name' => __('MacWatch Default Body', 'mactrack'), - 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain any valid html tags. It also supports replacement tags that will be processed when sending an Email. Valid tags include , , , , , , , .', 'mactrack')), - 'method' => 'textarea', - 'class' => 'textAreaNotes', - 'value' => '|arg1:description|', - 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), - 'max_length' => '512', - 'textarea_rows' => '5', - 'textarea_cols' => '80', - ], - 'ticket_number' => [ - 'method' => 'textbox', - 'friendly_name' => __('Ticket Number', 'mactrack'), - 'description' => __('Ticket number for cross referencing with your corporate help desk system(s).', 'mactrack'), - 'value' => '|arg1:ticket_number|', - 'size' => '70', - 'max_length' => '150', - ], - 'notify_schedule' => [ - 'method' => 'drop_array', - 'friendly_name' => __('Notification Schedule', 'mactrack'), - 'description' => __('Choose how often an Email should be generated for this Mac Watch item.', 'mactrack'), - 'value' => '|arg1:notify_schedule|', - 'default' => '1', - 'array' => [ - 1 => __('First Occurrence Only', 'mactrack'), - 2 => __('All Occurrences', 'mactrack'), - 60 => __('Every Hour', 'mactrack'), - 240 => __('Every %d Hours', 4, 'mactrack'), - 1800 => __('Every %d Hours', 12, 'mactrack'), - 3600 => __('Every Day', 'mactrack')], - ], - 'email_addresses' => [ - 'method' => 'textbox', - 'friendly_name' => __('Email Addresses', 'mactrack'), - 'description' => __('Enter a semicolon separated of Email addresses that will be notified where this MAC address is.', 'mactrack'), - 'value' => '|arg1:email_addresses|', - 'size' => '90', - 'max_length' => '255', - ], - 'mac_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|', - ], - '_mac_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|', - ], - 'save_component_macw' => [ - 'method' => 'hidden', - 'value' => '1', - ], - ]; - - // file: mactrack_macwatch.php, action: edit - $fields_mactrack_maca_edit = [ - 'spacer0' => [ - 'method' => 'spacer', - 'friendly_name' => __('General Mac Address Authorization Settings', 'mactrack'), - ], - 'mac_address' => [ - 'method' => 'textbox', - 'friendly_name' => __('MAC Address Match', 'mactrack'), - 'description' => __('Please enter the MAC Address or Mac Address Match string to be automatically authorized. If you wish to authorize a group of MAC Addresses, you can use the wildcard character of \'%\' anywhere in the MAC Address.', 'mactrack'), - 'value' => '|arg1:mac_address|', - 'default' => '', - 'max_length' => '40', - ], - 'description' => [ - 'method' => 'textarea', - 'friendly_name' => __('Reason', 'mactrack'), - 'class' => 'textAreaNotes', - 'description' => __('Please add a reason for this entry.', 'mactrack'), - 'value' => '|arg1:description|', - 'textarea_rows' => '4', - 'textarea_cols' => '80', - ], - 'mac_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|', - ], - '_mac_id' => [ - 'method' => 'hidden_zero', - 'value' => '|arg1:mac_id|', - ], - 'save_component_maca' => [ - 'method' => 'hidden', - 'value' => '1', - ], - ]; +function mactrack_config_form() { + global $fields_mactrack_device_type_edit, $fields_mactrack_device_edit, $fields_mactrack_site_edit; + global $fields_mactrack_snmp_edit, $fields_mactrack_snmp_item, $fields_mactrack_snmp_item_edit; + global $mactrack_device_types, $snmp_versions, $fields_mactrack_macw_edit, $fields_mactrack_maca_edit; + global $snmp_priv_protocols, $snmp_auth_protocols; + + // file: mactrack_device_types.php, action: edit + $fields_mactrack_device_type_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('Device Scanning Function Options', 'mactrack'), + ], + 'description' => [ + 'method' => 'textbox', + 'friendly_name' => __('Description', 'mactrack'), + 'description' => __('Give this device type a meaningful description.', 'mactrack'), + 'value' => '|arg1:description|', + 'max_length' => '250', + ], + 'vendor' => [ + 'method' => 'textbox', + 'friendly_name' => __('Vendor', 'mactrack'), + 'description' => __('Fill in the name for the vendor of this device type.', 'mactrack'), + 'value' => '|arg1:vendor|', + 'max_length' => '250', + ], + 'device_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Device Type', 'mactrack'), + 'description' => __('Choose the type of device.', 'mactrack'), + 'value' => '|arg1:device_type|', + 'default' => 1, + 'array' => $mactrack_device_types, + ], + 'sysDescr_match' => [ + 'method' => 'textbox', + 'friendly_name' => __('System Description Match', 'mactrack'), + 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), + 'value' => '|arg1:sysDescr_match|', + 'max_length' => '250', + ], + 'sysObjectID_match' => [ + 'method' => 'textbox', + 'friendly_name' => __('Vendor SNMP Object ID Match', 'mactrack'), + 'description' => __('Provide key information to help Mactrack detect the type of device. The wildcard character is the \'*\' sign.', 'mactrack'), + 'value' => '|arg1:sysObjectID_match|', + 'max_length' => '250', + ], + 'scanning_function' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('MAC Address Scanning Function', 'mactrack'), + 'description' => __('Mactrack scanning function to call in order to obtain and store port details. The function name is all that is required. The following four parameters are assumed and will always be appended: \'my_function($site, &$device, $lowport, $highport)\'. There is no function required for a pure router.', 'mactrack'), + 'value' => '|arg1:scanning_function|', + 'default' => 0, + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select scanning_function as id, scanning_function as name from mac_track_scanning_functions where type="1" order by scanning_function', + ], + 'ip_scanning_function' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('IP Address Scanning Function', 'mactrack'), + 'description' => __('Mactrack scanning function specific to Layer3 devices that track IP Addresses.', 'mactrack'), + 'value' => '|arg1:ip_scanning_function|', + 'default' => 0, + 'none_value' => __('None', 'mactrack'), + 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="2" ORDER BY scanning_function', + ], + 'dot1x_scanning_function' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('802.1x Scanning Function', 'mactrack'), + 'description' => __('Mactrack scanning function specific to Switches with dot1x enabled.', 'mactrack'), + 'value' => '|arg1:dot1x_scanning_function|', + 'default' => '', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'SELECT scanning_function AS id, scanning_function AS name FROM mac_track_scanning_functions WHERE type="3" ORDER BY scanning_function', + ], + 'serial_number_oid' => [ + 'method' => 'textbox', + 'friendly_name' => __('Serial Number Base OID', 'mactrack'), + 'description' => __('The SNMP OID used to obtain this device types serial number to be stored in the Mactrack Asset Information table.', 'mactrack'), + 'value' => '|arg1:serial_number_oid|', + 'max_length' => '100', + 'default' => '', + ], + 'serial_number_oid_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Serial Number Collection Method', 'mactrack'), + 'description' => __('How is the serial number collected for this OID. If \'SNMP Walk\', we assume multiple serial numbers. If \'Get\', it will be only one..', 'mactrack'), + 'value' => '|arg1:serial_number_oid_method|', + 'default' => 'get', + 'array' => ['get' => __('SNMP Get', 'mactrack'), 'walk' => __('SNMP Walk', 'mactrack')], + ], + 'lowPort' => [ + 'method' => 'textbox', + 'friendly_name' => __('Low User Port Number', 'mactrack'), + 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), + 'value' => '|arg1:lowPort|', + 'default' => read_config_option('mt_port_lowPort'), + 'max_length' => '100', + 'size' => '10', + ], + 'highPort' => [ + 'method' => 'textbox', + 'friendly_name' => __('High User Port Number', 'mactrack'), + 'description' => __('Provide the low user port number on this switch. Leave 0 to allow the system to calculate it.', 'mactrack'), + 'value' => '|arg1:highPort|', + 'default' => read_config_option('mt_port_highPort'), + 'max_length' => '100', + 'size' => '10', + ], + 'disabled' => [ + 'method' => 'checkbox', + 'friendly_name' => __('Disabled', 'mactrack'), + 'description' => __('Disabled device type is not used.', 'mactrack'), + 'value' => '|arg1:disabled|', + 'default' => '', + ], + 'device_type_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_type_id|', + ], + '_device_type_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_type_id|', + ], + 'save_component_device_type' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_snmp.php, action: edit + $fields_mactrack_snmp_edit = [ + 'name' => [ + 'method' => 'textbox', + 'friendly_name' => __('Name', 'mactrack'), + 'description' => __('Fill in the name of this SNMP option set.', 'mactrack'), + 'value' => '|arg1:name|', + 'default' => '', + 'max_length' => '100', + 'size' => '40', + ], + ]; + + // file: mactrack_snmp.php, action: item_edit + $fields_mactrack_snmp_item = [ + 'snmp_version' => [ + 'method' => 'drop_array', + 'friendly_name' => __('SNMP Version', 'mactrack'), + 'description' => __('Choose the SNMP version for this host.', 'mactrack'), + 'value' => '|arg1:snmp_version|', + 'default' => read_config_option('mt_snmp_ver'), + 'array' => $snmp_versions, + ], + 'snmp_readstring' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Community String', 'mactrack'), + 'description' => __('Fill in the SNMP read community for this device.', 'mactrack'), + 'value' => '|arg1:snmp_readstring|', + 'default' => read_config_option('mt_snmp_community'), + 'max_length' => '100', + 'size' => '20', + ], + 'snmp_port' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Port', 'mactrack'), + 'description' => __('The UDP/TCP Port to poll the SNMP agent on.', 'mactrack'), + 'value' => '|arg1:snmp_port|', + 'max_length' => '8', + 'default' => read_config_option('mt_snmp_port'), + 'size' => '10', + ], + 'snmp_timeout' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Timeout', 'mactrack'), + 'description' => __('The maximum number of milliseconds Cacti will wait for an SNMP response (does not work with php-snmp support).', 'mactrack'), + 'value' => '|arg1:snmp_timeout|', + 'max_length' => '8', + 'default' => read_config_option('mt_snmp_timeout'), + 'size' => '10', + ], + 'snmp_retries' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Retries', 'mactrack'), + 'description' => __('The maximum number of attempts to reach a device via an SNMP readstring prior to giving up.', 'mactrack'), + 'value' => '|arg1:snmp_retries|', + 'max_length' => '8', + 'default' => read_config_option('mt_snmp_retries'), + 'size' => '10', + ], + 'max_oids' => [ + 'method' => 'textbox', + 'friendly_name' => __('Maximum OID\'s Per Get Request', 'mactrack'), + 'description' => __('Specified the number of OID\'s that can be obtained in a single SNMP Get request.', 'mactrack'), + 'value' => '|arg1:max_oids|', + 'max_length' => '8', + 'default' => read_config_option('max_get_size'), + 'size' => '15', + ], + 'snmp_username' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Username (v3)', 'mactrack'), + 'description' => __('SNMP v3 username for this device.', 'mactrack'), + 'value' => '|arg1:snmp_username|', + 'default' => read_config_option('snmp_username'), + 'max_length' => '50', + 'size' => '15', + ], + 'snmp_password' => [ + 'method' => 'textbox_password', + 'friendly_name' => __('SNMP Password (v3)', 'mactrack'), + 'description' => __('SNMP v3 password for this device.', 'mactrack'), + 'value' => '|arg1:snmp_password|', + 'default' => read_config_option('snmp_password'), + 'max_length' => '50', + 'size' => '15', + ], + 'snmp_auth_protocol' => [ + 'method' => 'drop_array', + 'friendly_name' => __('SNMP Auth Protocol (v3)', 'mactrack'), + 'description' => __('Choose the SNMPv3 Authorization Protocol.', 'mactrack'), + 'value' => '|arg1:snmp_auth_protocol|', + 'default' => read_config_option('snmp_auth_protocol'), + 'array' => $snmp_auth_protocols, + ], + 'snmp_priv_passphrase' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Privacy Passphrase (v3)', 'mactrack'), + 'description' => __('Choose the SNMPv3 Privacy Passphrase.', 'mactrack'), + 'value' => '|arg1:snmp_priv_passphrase|', + 'default' => read_config_option('snmp_priv_passphrase'), + 'max_length' => '200', + 'size' => '40', + ], + 'snmp_priv_protocol' => [ + 'method' => 'drop_array', + 'friendly_name' => __('SNMP Privacy Protocol (v3)', 'mactrack'), + 'description' => __('Choose the SNMPv3 Privacy Protocol.', 'mactrack'), + 'value' => '|arg1:snmp_priv_protocol|', + 'default' => read_config_option('snmp_priv_protocol'), + 'array' => $snmp_priv_protocols, + ], + 'snmp_context' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Context (v3)', 'mactrack'), + 'description' => __('Enter the SNMP v3 Context to use for this device.', 'mactrack'), + 'value' => '|arg1:snmp_context|', + 'default' => '', + 'max_length' => '64', + 'size' => '40', + ], + 'snmp_engine_id' => [ + 'method' => 'textbox', + 'friendly_name' => __('SNMP Engine ID (v3)', 'mactrack'), + 'description' => __('Enter the SNMP v3 Engine ID to use for this device.', 'mactrack'), + 'value' => '|arg1:snmp_engine_id|', + 'default' => '', + 'max_length' => '64', + 'size' => '40', + ], + ]; + + // file: mactrack_devices.php, action: edit + $fields_mactrack_device_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Device Settings', 'mactrack'), + ], + 'device_name' => [ + 'method' => 'textbox', + 'friendly_name' => __('Device Name', 'mactrack'), + 'description' => __('Give this device a meaningful name.', 'mactrack'), + 'value' => '|arg1:device_name|', + 'max_length' => '250', + ], + 'hostname' => [ + 'method' => 'textbox', + 'friendly_name' => __('Hostname', 'mactrack'), + 'description' => __('Fill in the fully qualified hostname for this device.', 'mactrack'), + 'value' => '|arg1:hostname|', + 'max_length' => '250', + ], + 'host_id' => [ + 'friendly_name' => __('Related Cacti Host', 'mactrack'), + 'description' => __('Given Mactrack Host is connected to this Cacti Host.', 'mactrack'), + // 'method' => 'view', + 'method' => 'drop_sql', + 'value' => '|arg1:host_id|', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select id,CONCAT_WS("",description," (",hostname,")") as name from host order by description,hostname', + ], + 'device_type_id' => [ + 'method' => 'drop_sql', + 'friendly_name' => 'Device Type', + 'description' => 'Choose the type of device.', + 'value' => '|arg1:device_type_id|', + 'default' => 0, + 'none_value' => 'Not Detected', + 'sql' => 'select device_type_id as id,description as name from mac_track_device_types order by description', + ], + 'scan_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Scan Type', 'mactrack'), + 'description' => __('Choose the scan type you wish to perform on this device.', 'mactrack'), + 'value' => '|arg1:scan_type|', + 'default' => 1, + 'array' => $mactrack_device_types, + ], + 'site_id' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('Site Name', 'mactrack'), + 'description' => __('Choose the site to associate with this device.', 'mactrack'), + 'value' => '|arg1:site_id|', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select site_id as id,site_name as name from mac_track_sites order by name', + ], + 'notes' => [ + 'method' => 'textarea', + 'friendly_name' => __('Device Notes', 'mactrack'), + 'description' => __('This field value is useful to save general information about a specific device.', 'mactrack'), + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'value' => '|arg1:notes|', + 'max_length' => '255', + ], + 'disabled' => [ + 'method' => 'checkbox', + 'friendly_name' => __('Disable Device', 'mactrack'), + 'description' => __('Check this box to disable all checks for this host.', 'mactrack'), + 'value' => '|arg1:disabled|', + 'default' => '', + 'form_id' => false, + ], + 'spacer1' => [ + 'method' => 'spacer', + 'friendly_name' => __('Switch/Hub, Switch/Router Settings', 'mactrack'), + ], + 'ignorePorts' => [ + 'method' => 'textarea', + 'friendly_name' => __('Ports to Ignore', 'mactrack'), + 'description' => __('Provide a list of ports on a specific switch/hub whose MAC results should be ignored. Ports such as link/trunk ports that can not be distinguished from other user ports are examples. Each port number must be separated by a colon, pipe, or a space \':\', \'|\', \' \'. For example, \'Fa0/1: Fa1/23\' or \'Fa0/1 Fa1/23\' would be acceptable for some manufacturers switch types.', 'mactrack'), + 'value' => '|arg1:ignorePorts|', + 'default' => '', + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'max_length' => '255', + ], + 'scan_trunk_port' => [ + 'method' => 'textarea', + 'friendly_name' => 'Trunk Ports to Scan', + 'description' => 'A comma delimited list of Port Number to be scanned. Some VMware network port will be configured with 802.1Q', + 'value' => '|arg1:scan_trunk_port|', + 'default' => '', + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'max_length' => '255', + ], + 'spacer2' => [ + 'method' => 'spacer', + 'friendly_name' => __('SNMP Options', 'mactrack'), + ], + 'snmp_options' => [ + 'method' => 'drop_sql', + 'friendly_name' => __('SNMP Options', 'mactrack'), + 'description' => __('You can use specific SNMP settings or select SNMP set. In the second case, mactrack tries to find correct settings from SNMP set', 'mactrack'), + 'value' => '|arg1:snmp_options|', + 'none_value' => __('None', 'mactrack'), + 'sql' => 'select * from mac_track_snmp order by name', + ], + 'snmp_readstrings' => [ + 'method' => 'view', + 'friendly_name' => __('Read Strings', 'mactrack'), + 'description' => __('DEPRECATED: SNMP community strings', 'mactrack'), + 'value' => '|arg1:snmp_readstrings|', + ], + 'spacer3' => [ + 'method' => 'spacer', + 'friendly_name' => __('Specific SNMP Settings', 'mactrack'), + ], + ]; + + $fields_mactrack_device_edit += $fields_mactrack_snmp_item; + + $fields_mactrack_device_edit += [ + 'spacer4' => [ + 'method' => 'spacer', + 'friendly_name' => __('Connectivity Options', 'mactrack'), + ], + 'term_type' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Terminal Type', 'mactrack'), + 'description' => __('Choose the terminal type that you use to connect to this device.', 'mactrack'), + 'value' => '|arg1:term_type|', + 'default' => 1, + 'array' => [ + 0 => __('None', 'mactrack'), + 1 => __('Telnet', 'mactrack'), + 2 => __('SSH', 'mactrack'), + 3 => __('HTTP', 'mactrack'), + 4 => __('HTTPS', 'mactrack')], + ], + 'user_name' => [ + 'method' => 'textbox', + 'friendly_name' => __('User Name', 'mactrack'), + 'description' => __('The user name to be used for your custom authentication method. Examples include SSH, RSH, HTML, etc.', 'mactrack'), + 'value' => '|arg1:user_name|', + 'default' => '', + 'max_length' => '40', + 'size' => '20', + ], + 'user_password' => [ + 'method' => 'textbox_password', + 'friendly_name' => __('Password', 'mactrack'), + 'description' => __('The password to be used for your custom authentication.', 'mactrack'), + 'value' => '|arg1:user_password|', + 'default' => '', + 'max_length' => '40', + 'size' => '20', + ], + 'private_key_path' => [ + 'method' => 'filepath', + 'friendly_name' => __('Private Key Path', 'mactrack'), + 'description' => __('The path to the private key used for SSH authentication.', 'mactrack'), + 'value' => '|arg1:private_key_path|', + 'default' => '', + 'max_length' => '128', + 'size' => '40', + ], + 'device_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_id|', + ], + '_device_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:device_id|', + ], + 'save_component_device' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_snmp.php, action: item_edit + $fields_mactrack_snmp_item_edit = $fields_mactrack_snmp_item + [ + 'sequence' => [ + 'method' => 'view', + 'friendly_name' => __('Sequence', 'mactrack'), + 'description' => __('Sequence of Item.', 'mactrack'), + 'value' => '|arg1:sequence|'], + ]; + + // file: mactrack_sites.php, action: edit + $fields_mactrack_site_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Site Settings', 'mactrack'), + ], + 'site_name' => [ + 'method' => 'textbox', + 'friendly_name' => __('Site Name', 'mactrack'), + 'description' => __('Please enter a reasonable name for this site.', 'mactrack'), + 'value' => '|arg1:site_name|', + 'size' => '70', + 'max_length' => '250', + ], + 'customer_contact' => [ + 'method' => 'textbox', + 'friendly_name' => __('Primary Customer Contact', 'mactrack'), + 'description' => __('The principal customer contact name and number for this site.', 'mactrack'), + 'value' => '|arg1:customer_contact|', + 'size' => '70', + 'max_length' => '150', + ], + 'netops_contact' => [ + 'method' => 'textbox', + 'friendly_name' => __('NetOps Contact', 'mactrack'), + 'description' => __('Please principal network support contact name and number for this site.', 'mactrack'), + 'value' => '|arg1:netops_contact|', + 'size' => '70', + 'max_length' => '150', + ], + 'facilities_contact' => [ + 'method' => 'textbox', + 'friendly_name' => __('Facilities Contact', 'mactrack'), + 'description' => __('Please principal facilities/security contact name and number for this site.', 'mactrack'), + 'value' => '|arg1:facilities_contact|', + 'size' => '70', + 'max_length' => '150', + ], + 'site_info' => [ + 'method' => 'textarea', + 'friendly_name' => __('Site Information', 'mactrack'), + 'class' => 'textAreaNotes', + 'textarea_rows' => '3', + 'textarea_cols' => '80', + 'description' => __('Provide any site-specific information, in free form, that allows you to better manage this location.', 'mactrack'), + 'value' => '|arg1:site_info|', + 'max_length' => '255', + ], + 'skip_vlans' => [ + 'method' => 'textarea', + 'friendly_name' => 'VLAN ID to Skipped Scan', + 'class' => 'textAreaNotes', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + 'description' => 'A comma delimited list of VLAN ID always forced to be skipped scanning.', + 'value' => '|arg1:skip_vlans|', + 'max_length' => '1024', + ], + 'scan_vlans' => [ + 'method' => 'textarea', + 'friendly_name' => 'VLAN ID to Scan', + 'class' => 'textAreaNotes', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + 'description' => 'A comma delimited list of VLAN ID to be scanned', + 'value' => '|arg1:scan_vlans|', + 'max_length' => '1024', + ], + 'site_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:site_id|', + ], + '_site_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:site_id|', + ], + 'save_component_site' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_macwatch.php, action: edit + $fields_mactrack_macw_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Mac Address Tracking Settings', 'mactrack'), + ], + 'mac_address' => [ + 'method' => 'textbox', + 'friendly_name' => __('MAC Address', 'mactrack'), + 'description' => __('Please enter the MAC Address to be watched for.', 'mactrack'), + 'value' => '|arg1:mac_address|', + 'default' => '', + 'max_length' => '40', + ], + 'name' => [ + 'method' => 'textbox', + 'friendly_name' => __('MAC Tracking Name/Email Subject', 'mactrack'), + 'description' => __('Please enter a reasonable name for this MAC Tracking entry. This information will be in the subject line of your Email', 'mactrack'), + 'value' => '|arg1:name|', + 'size' => '70', + 'max_length' => '250', + ], + 'description' => [ + 'friendly_name' => __('MacWatch Default Body', 'mactrack'), + 'description' => htmlspecialchars(__('The Email body preset for Mactrack MacWatch Emails. The body can contain any valid html tags. It also supports replacement tags that will be processed when sending an Email. Valid tags include , , , , , , , .', 'mactrack')), + 'method' => 'textarea', + 'class' => 'textAreaNotes', + 'value' => '|arg1:description|', + 'default' => __('Mac Address found at IP Address for Ticket Number: .
The device is located at
Site: , Device , IP , Port , and Port Name ', 'mactrack'), + 'max_length' => '512', + 'textarea_rows' => '5', + 'textarea_cols' => '80', + ], + 'ticket_number' => [ + 'method' => 'textbox', + 'friendly_name' => __('Ticket Number', 'mactrack'), + 'description' => __('Ticket number for cross referencing with your corporate help desk system(s).', 'mactrack'), + 'value' => '|arg1:ticket_number|', + 'size' => '70', + 'max_length' => '150', + ], + 'notify_schedule' => [ + 'method' => 'drop_array', + 'friendly_name' => __('Notification Schedule', 'mactrack'), + 'description' => __('Choose how often an Email should be generated for this Mac Watch item.', 'mactrack'), + 'value' => '|arg1:notify_schedule|', + 'default' => '1', + 'array' => [ + 1 => __('First Occurrence Only', 'mactrack'), + 2 => __('All Occurrences', 'mactrack'), + 60 => __('Every Hour', 'mactrack'), + 240 => __('Every %d Hours', 4, 'mactrack'), + 1800 => __('Every %d Hours', 12, 'mactrack'), + 3600 => __('Every Day', 'mactrack')], + ], + 'email_addresses' => [ + 'method' => 'textbox', + 'friendly_name' => __('Email Addresses', 'mactrack'), + 'description' => __('Enter a semicolon separated of Email addresses that will be notified where this MAC address is.', 'mactrack'), + 'value' => '|arg1:email_addresses|', + 'size' => '90', + 'max_length' => '255', + ], + 'mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + '_mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + 'save_component_macw' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; + + // file: mactrack_macwatch.php, action: edit + $fields_mactrack_maca_edit = [ + 'spacer0' => [ + 'method' => 'spacer', + 'friendly_name' => __('General Mac Address Authorization Settings', 'mactrack'), + ], + 'mac_address' => [ + 'method' => 'textbox', + 'friendly_name' => __('MAC Address Match', 'mactrack'), + 'description' => __('Please enter the MAC Address or Mac Address Match string to be automatically authorized. If you wish to authorize a group of MAC Addresses, you can use the wildcard character of \'%\' anywhere in the MAC Address.', 'mactrack'), + 'value' => '|arg1:mac_address|', + 'default' => '', + 'max_length' => '40', + ], + 'description' => [ + 'method' => 'textarea', + 'friendly_name' => __('Reason', 'mactrack'), + 'class' => 'textAreaNotes', + 'description' => __('Please add a reason for this entry.', 'mactrack'), + 'value' => '|arg1:description|', + 'textarea_rows' => '4', + 'textarea_cols' => '80', + ], + 'mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + '_mac_id' => [ + 'method' => 'hidden_zero', + 'value' => '|arg1:mac_id|', + ], + 'save_component_maca' => [ + 'method' => 'hidden', + 'value' => '1', + ], + ]; } -function convert_readstrings() -{ - global $config; - - $sql = 'SELECT DISTINCT ' - .'snmp_readstrings, ' - .'snmp_version, ' - .'snmp_port, ' - .'snmp_timeout, ' - .'snmp_retries ' - .'FROM mac_track_devices'; - - $devices = db_fetch_assoc($sql); - - if (cacti_sizeof($devices)) { - $i = 0; - foreach ($devices as $device) { - // create new SNMP Option Set - unset($save); - $save['id'] = 0; - $save['name'] = 'Custom_'.$i++; - $snmp_id = sql_save($save, 'mac_track_snmp'); - - // add each single option derived from readstrings - $read_strings = explode(':', $device['snmp_readstrings']); - if (cacti_sizeof($read_strings)) { - foreach ($read_strings as $snmp_readstring) { - unset($save); - $save['id'] = 0; - $save['snmp_id'] = $snmp_id; - $save['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id='.$snmp_id); - - $save['snmp_readstring'] = $snmp_readstring; - $save['snmp_version'] = $device['snmp_version']; - $save['snmp_port'] = $device['snmp_port']; - $save['snmp_timeout'] = $device['snmp_timeout']; - $save['snmp_retries'] = $device['snmp_retries']; - $save['snmp_username'] = ''; - $save['snmp_password'] = ''; - $save['snmp_auth_protocol'] = ''; - $save['snmp_priv_passphrase'] = ''; - $save['snmp_priv_protocol'] = ''; - $save['snmp_context'] = ''; - $save['snmp_engine_id'] = ''; - $save['max_oids'] = ''; - - $item_id = sql_save($save, 'mac_track_snmp_items'); - } - } // each readstring added as SNMP Option item - - // now, let's find all devices, that used this snmp_readstrings - $sql = 'UPDATE mac_track_devices SET snmp_options='.$snmp_id - ." WHERE snmp_readstrings='".$device['snmp_readstrings'] - ."' AND snmp_version=".$device['snmp_version'] - .' AND snmp_port='.$device['snmp_port'] - .' AND snmp_timeout='.$device['snmp_timeout'] - .' AND snmp_retries='.$device['snmp_retries']; - - $ok = db_execute($sql); - } - } - db_execute("REPLACE INTO settings (name,value) VALUES ('mt_convert_readstrings', 'on')"); - // we keep the field:snmp_readstrings in mac_track_devices, it should be deprecated first - // next mactrack release may delete that field, then +function convert_readstrings() { + global $config; + + $sql = 'SELECT DISTINCT ' + . 'snmp_readstrings, ' + . 'snmp_version, ' + . 'snmp_port, ' + . 'snmp_timeout, ' + . 'snmp_retries ' + . 'FROM mac_track_devices'; + + $devices = db_fetch_assoc($sql); + + if (cacti_sizeof($devices)) { + $i = 0; + + foreach ($devices as $device) { + // create new SNMP Option Set + unset($save); + $save['id'] = 0; + $save['name'] = 'Custom_' . $i++; + $snmp_id = sql_save($save, 'mac_track_snmp'); + + // add each single option derived from readstrings + $read_strings = explode(':', $device['snmp_readstrings']); + + if (cacti_sizeof($read_strings)) { + foreach ($read_strings as $snmp_readstring) { + unset($save); + $save['id'] = 0; + $save['snmp_id'] = $snmp_id; + $save['sequence'] = get_sequence('', 'sequence', 'mac_track_snmp_items', 'snmp_id=' . $snmp_id); + + $save['snmp_readstring'] = $snmp_readstring; + $save['snmp_version'] = $device['snmp_version']; + $save['snmp_port'] = $device['snmp_port']; + $save['snmp_timeout'] = $device['snmp_timeout']; + $save['snmp_retries'] = $device['snmp_retries']; + $save['snmp_username'] = ''; + $save['snmp_password'] = ''; + $save['snmp_auth_protocol'] = ''; + $save['snmp_priv_passphrase'] = ''; + $save['snmp_priv_protocol'] = ''; + $save['snmp_context'] = ''; + $save['snmp_engine_id'] = ''; + $save['max_oids'] = ''; + + $item_id = sql_save($save, 'mac_track_snmp_items'); + } + } // each readstring added as SNMP Option item + + // now, let's find all devices, that used this snmp_readstrings + $sql = 'UPDATE mac_track_devices SET snmp_options=' . $snmp_id + . " WHERE snmp_readstrings='" . $device['snmp_readstrings'] + . "' AND snmp_version=" . $device['snmp_version'] + . ' AND snmp_port=' . $device['snmp_port'] + . ' AND snmp_timeout=' . $device['snmp_timeout'] + . ' AND snmp_retries=' . $device['snmp_retries']; + + $ok = db_execute($sql); + } + } + db_execute("REPLACE INTO settings (name,value) VALUES ('mt_convert_readstrings', 'on')"); + // we keep the field:snmp_readstrings in mac_track_devices, it should be deprecated first + // next mactrack release may delete that field, then } From da32083ae74d21ec22b24752a00d923a2f3dbf78 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:41:00 -0500 Subject: [PATCH 14/18] Update mactrack_functions.php --- lib/mactrack_functions.php | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/lib/mactrack_functions.php b/lib/mactrack_functions.php index d8a130f9..db26650c 100644 --- a/lib/mactrack_functions.php +++ b/lib/mactrack_functions.php @@ -3545,18 +3545,19 @@ function mactrack_dot1x_row_class($port_result) { return 'dot1x_authn_success'; } -/** mactrack_create_sql_filter - this routine will take a filter string and process it into a - sql where clause that will be returned to the caller with a formatted SQL where clause - that can then be integrated into the overall where clause. - The filter takes the following forms. The default is to find occurrence that match "all" - Any string prefixed by a "-" will mean "exclude" this search string. Boolean expressions - are currently not supported. - @arg $filter - (string) The filter provided by the user - @arg $fields - (array) A list of field names to include in the where clause. They can also - contain the table name in cases where joins are important. - * @param mixed $filter - * @param mixed $fields - @returns - (string) The formatted SQL syntax */ +/** + * mactrack_create_sql_filter - this routine will take a filter string and process it into a + * sql where clause that will be returned to the caller with a formatted SQL where clause + * that can then be integrated into the overall where clause. + * The filter takes the following forms. The default is to find occurrences that match "all". + * Any string prefixed by a "-" will mean "exclude" this search string. Boolean expressions + * are currently not supported. + * + * @param string $filter The filter provided by the user + * @param array $fields A list of field names to include in the where clause. They can also + * contain the table name in cases where joins are important. + * @return string The formatted SQL syntax + */ function mactrack_create_sql_filter($filter, $fields) { $query = ''; From 92efe3dc97285e285f3eadbfec120b83a23ba61f Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 20:42:43 -0500 Subject: [PATCH 15/18] Update mactrack_functions.php --- lib/mactrack_functions.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/mactrack_functions.php b/lib/mactrack_functions.php index db26650c..74eda204 100644 --- a/lib/mactrack_functions.php +++ b/lib/mactrack_functions.php @@ -3553,9 +3553,9 @@ function mactrack_dot1x_row_class($port_result) { * Any string prefixed by a "-" will mean "exclude" this search string. Boolean expressions * are currently not supported. * - * @param string $filter The filter provided by the user - * @param array $fields A list of field names to include in the where clause. They can also - * contain the table name in cases where joins are important. + * @param string $filter The filter provided by the user + * @param array $fields A list of field names to include in the where clause. They can also + * contain the table name in cases where joins are important. * @return string The formatted SQL syntax */ function mactrack_create_sql_filter($filter, $fields) { From e2548ab1d324ed202b11d03ee4e74661d50f86a7 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 14 Feb 2026 10:08:12 -0500 Subject: [PATCH 16/18] Rename triage_agent.md.agent.md to triage_agent.agent.md --- .../agents/{triage_agent.md.agent.md => triage_agent.agent.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename .github/agents/{triage_agent.md.agent.md => triage_agent.agent.md} (99%) diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.agent.md similarity index 99% rename from .github/agents/triage_agent.md.agent.md rename to .github/agents/triage_agent.agent.md index 1575ef5b..69204a92 100644 --- a/.github/agents/triage_agent.md.agent.md +++ b/.github/agents/triage_agent.agent.md @@ -129,4 +129,4 @@ When calling other agents via the 'agent' tool, pass a structured payload: ## Testing - Create unit tests for the rule set covering edge cases where both 'sql' and 'lint' appear. -- Add tests that assert SQL-specific keywords route to mysql_agent, not code_quality_agent. \ No newline at end of file +- Add tests that assert SQL-specific keywords route to mysql_agent, not code_quality_agent. From 675e4503aae53317b7ddd767feb73dfa4e39b3c0 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 14 Feb 2026 10:09:13 -0500 Subject: [PATCH 17/18] Update MySQL and MariaDB agent documentation Correct formatting and improve clarity in the MySQL and MariaDB agent documentation. --- .github/agents/mysql-mariadb.agent.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/agents/mysql-mariadb.agent.md b/.github/agents/mysql-mariadb.agent.md index 072e2aaf..f7acd282 100644 --- a/.github/agents/mysql-mariadb.agent.md +++ b/.github/agents/mysql-mariadb.agent.md @@ -35,16 +35,14 @@ When assisting with tasks, follow these guidelines: 4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. 5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. - ## Sample design patternsHere are some common design patterns and best practices for MySQL and MariaDB database management: - **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. - **Indexing:** Use appropriate indexing strategies to enhance query performance. - **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance - - ## Built in Cacti DB functions Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: + ## you can find the included file in the cacti project here: - [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) - `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. @@ -58,9 +56,9 @@ Built in Cacti DB functions are included from the cacti project. Here are some o - `db_last_insert_id()`: Retrieves the ID of the last inserted record. -##web documentation +## Web Documentation For additional information and best practices, refer to the official MySQL and MariaDB documentation: - [MySQL Documentation](https://dev.mysql.com/doc/) - [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) -Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. \ No newline at end of file +Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. From b63f5d7ea949d5dd702019bceffd5b9820a8041f Mon Sep 17 00:00:00 2001 From: TheWitness Date: Sat, 14 Feb 2026 10:09:43 -0500 Subject: [PATCH 18/18] Clean up blank lines in php-developer.agent.md Removed unnecessary blank lines in the PHP developer agent documentation. --- .github/agents/php-developer.agent.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/agents/php-developer.agent.md b/.github/agents/php-developer.agent.md index 4153ea3d..d5e380a4 100644 --- a/.github/agents/php-developer.agent.md +++ b/.github/agents/php-developer.agent.md @@ -24,14 +24,10 @@ You have access to the following tools to assist you in your tasks: - **extensions:** Utilize extensions that can enhance your capabilities in PHP development. - **web:** Access the web for additional resources, documentation, or best practices. - - ## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: - [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) - [Cacti Documentation](https://www.github.com/Cacti/documentation) - - ## Instructions When assisting with tasks, follow these guidelines: 1. **Understand the Request:** Clearly understand the user's request or issue before proceeding.