package aeos;
##
## $Id: aeos.pm.in 3746 2017-12-12 15:53:32Z heas $
##
## rancid 3.8
## Copyright (c) 1997-2018 by Henry Kilmer and John Heasley
## All rights reserved.
##
## This code is derived from software contributed to and maintained by
## Henry Kilmer, John Heasley, Andrew Partan,
## Pete Whiting, Austin Schutz, and Andrew Fort.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## 1. Redistributions of source code must retain the above copyright
##    notice, this list of conditions and the following disclaimer.
## 2. Redistributions in binary form must reproduce the above copyright
##    notice, this list of conditions and the following disclaimer in the
##    documentation and/or other materials provided with the distribution.
## 3. Neither the name of RANCID nor the names of its
##    contributors may be used to endorse or promote products derived from
##    this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY Henry Kilmer, John Heasley AND CONTRIBUTORS
## ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
## TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COMPANY OR CONTRIBUTORS
## BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
## POSSIBILITY OF SUCH DAMAGE.
##
## It is the request of the authors, but not a condition of license, that
## parties packaging or redistributing RANCID NOT distribute altered versions
## of the etc/rancid.types.base file nor alter how this file is processed nor
## when in relation to etc/rancid.types.conf.  The goal of this is to help
## suppress our support costs.  If it becomes a problem, this could become a
## condition of license.
# 
#  The expect login scripts were based on Erik Sherk's gwtn, by permission.
# 
#  The original looking glass software was written by Ed Kern, provided by
#  permission and modified beyond recognition.
#
#  RANCID - Really Awesome New Cisco confIg Differ
#
# Rancid for Arista Networks' switches; cisco mode works but
# Arista mode is better.
# Initial version by Bill Fenner <fenner@aristanetworks.com>
#
#  aeos.pm - Arista EOS rancid procedures

use 5.010;
use strict 'vars';
use warnings;
no warnings 'uninitialized';
require(Exporter);
our @ISA = qw(Exporter);

use rancid 3.8;

our $found_env;
our $found_version;

@ISA = qw(Exporter rancid main);
#XXX @Exporter::EXPORT = qw($VERSION @commandtable %commands @commands);

# load-time initialization
sub import {
    $found_version = 0;
    $found_env = 0;

    0;
}

# post-open(collection file) initialization
sub init {

    # add content lines and separators
    ProcessHistory("","","","!RANCID-CONTENT-TYPE: $devtype\n!\n");

    0;
}

# main loop of input of device output
sub inloop {
    my($INPUT, $OUTPUT) = @_;
    my($cmd, $rval);

TOP: while(<$INPUT>) {
	tr/\015//d;
CMD:	if (/[>#]\s?exit$/) {
	    $clean_run = 1;
	    last;
	}
	if (/^Error:/) {
	    print STDOUT ("$host clogin error: $_");
	    print STDERR ("$host clogin error: $_") if ($debug);
	    $clean_run = 0;
	    last;
	}
	while (/#\s*($cmds_regexp)\s*$/) {
	    $cmd = $1;
	    if (!defined($prompt)) {
		$prompt = ($_ =~ /^([^#]+#)/)[0];
		$prompt =~ s/([][}{)(\\])/\\$1/g;
		# "time in prompt" hack:
		$prompt =~ s/\d+:\d+:\d+/\\d+:\\d+:\\d+/;
		print STDERR ("PROMPT MATCH: $prompt\n") if ($debug);
	    }
	    print STDERR ("HIT COMMAND:$_") if ($debug);
	    if (! defined($commands{$cmd})) {
		print STDERR "$host: found unexpected command - \"$cmd\"\n";
		$clean_run = 0;
		last TOP;
	    }
	    $rval = &{$commands{$cmd}}($INPUT, $OUTPUT, $cmd);
	    delete($commands{$cmd});
	    if ($rval == -1) {
		$clean_run = 0;
		last TOP;
	    }
	    if (defined($prompt)) {
		if (/$prompt/) {
		    goto CMD;
		}
	    }
	}
    }
}

# This routine parses "show version"
sub ShowVersion {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowVersion: $_" if ($debug);

    while (<$INPUT>) {
	tr/\015//d;
	if (/^$prompt/) {$found_version = 1; last};
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if /^% Invalid input/;
	return(0) if ($found_version);		# Only do this routine once

	next if (/uptime is/);			# Older AOS show uptime
        my($key, $val) = split(/:\s+/, $_, 2);
        if (! $val) {
           # Must be the model name if there's no colon
           ProcessHistory("COMMENTS", "", "", "!Model: $_" );
           next;
        }
        if ($key ne 'Uptime' and $key ne 'Free memory') {
           ProcessHistory("COMMENTS", "", "", "!$key: $val" );
        }
    }
    return(0);
}

sub DiffConfig {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In DiffConfig: $_" if ($debug);
    my($havediffs) = 0;

    while (<$INPUT>) {
	tr/\015//d;
	last if (/^$prompt/);
	next if (/^(\s*|\s*$cmd\s*)$/);

	ProcessHistory("DIFFS","keysort","BB","!$_");
	$havediffs = 1;
    }
    if ($havediffs) {
	ProcessHistory("DIFFS","keysort","AA","!*****************************\n");
	ProcessHistory("DIFFS","keysort","AB","!*** unsaved changes exist ***\n");
	ProcessHistory("DIFFS","keysort","AC","!*****************************\n");
	ProcessHistory("DIFFS","keysort","CC","!\n");
    }
    return;
}

# This routine parses "show env all"
sub ShowEnv {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowEnv: $_" if ($debug);
    my($fans, $E0) = (0, undef);

    while (<$INPUT>) {
	tr/\015//d;
	if (/^$prompt/) {$found_env = 1; last};
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if /^% Invalid input/;
	return(0) if ($found_env);		# Only do this routine once

	if (!defined($E0)) {
	    $E0 = 1;
	    ProcessHistory("COMMENTS","keysort","E0","!\n");
	}
        /^(System \S+ status is|Action on overheat|Airflow)/ &&
	    ProcessHistory("COMMENTS","keysort","E0","!$_") && next;
        if (/^Fan\s+Status\s+/) {
            $fans = 1;
            next;
        }
        $fans && /^\s*(\d+)\s+(\S+)/ &&
            ProcessHistory("COMMENTS","keysort","E1","!Fan $1: $2\n") && next;
        if (/^supply\s+model\s+capacity/i) {
	    while (<$INPUT>) {
		tr/\015//d;
		last if (/^\s*/);
		if (/^$prompt/) {$found_version = 1; last};
		/^\s*(\d+)\s+(\S+)\s+(\S+)\s+\S+\s+\S+\s+\S+\s+(\S+)/ &&
		    ProcessHistory("COMMENTS","keysort","E2","!Power Supply $1: $2 $3 $4\n");
		    next;
		/^\s*Total\s+\S+\s+(\S+)\s+/ &&
		    ProcessHistory("COMMENTS","keysort","E2","!Power Total: $1\n") &&
		    next;;
            }
        }
    }
    ProcessHistory("COMMENTS","","","!\n");
    return(0);
}

# This routine parses "show boot-config"
sub ShowBoot {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowBoot: $_" if ($debug);
    my($B0) = (undef);

    while (<$INPUT>) {
	tr/\015//d;
	last if (/^$prompt/);
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if /^% Invalid input/;

	if (!defined($B0)) {
	    $B0 = 1; ProcessHistory("COMMENTS","","","!\n");
	}
        ProcessHistory("COMMENTS","","","!$_");
    }
    ProcessHistory("COMMENTS","","","!\n");
    return(0);
}

# This routine parses "show boot-extensions"
sub ShowBootExt {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowBootExt: $_" if ($debug);
    my($C0) = (undef);

    while (<$INPUT>) {
	tr/\015//d;
	last if (/^$prompt/);
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if (/^% Invalid input/);
        return(0) if (/^% Error displaying /);

	if (!defined($C0)) {
	    $C0 = 1; ProcessHistory("COMMENTS","","","!\n");
	}
        ProcessHistory("COMMENTS","","","!BootExtension: $_");
    }
    ProcessHistory("COMMENTS","","","!\n");
    return(0);
}

# This routine parses "show extensions"
sub ShowExt {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowExt: $_" if ($debug);
    my($D0) = (undef);

    while (<$INPUT>) {
	tr/\015//d;
	last if (/^$prompt/);
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if /^% Invalid input/;
        return(0) if /^No extensions are available/;

	if (!defined($D0)) {
	    $D0 = 1; ProcessHistory("COMMENTS","","","!Extensions:\n");
	}
        ProcessHistory("COMMENTS","","","!$_");
    }
    ProcessHistory("COMMENTS","","","!\n");
    return(0);
}

# This routine parses "dir flash:"
sub ShowFlash {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowFlash: $_" if ($debug);

    while (<$INPUT>) {
	tr/\015//d;
	last if (/^$prompt/);
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if /^% Invalid input/;

        # persist changes constantly if you're running ntp, so
        # skip its updates.
        /\spersist$/ && next;

	# Scheduled commands can cause free space to constantly
	# change.  Even the trick of summarizing the free space
	# doesn't help, since it can oscillate, e.g., between
	# 1006MB and 1007MB.  Just skip the free space.
	/.*\((\d+) bytes free\)/ && next;

	ProcessHistory("FLASH","","","!Flash: $_");
    }
    ProcessHistory("","","","!\n");
    return;
}

# This routine parses "show inventory".
sub ShowInventory {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In ShowInventory: $_" if ($debug);

    while (<$INPUT>) {
	tr/\015//d;
	return if (/^\s*\^$/);
	last if (/^$prompt/);
	next if (/^(\s*|\s*$cmd\s*)$/);
	return(1) if /^% Invalid input/;

	ProcessHistory("INVENTORY","","","!$_");
    }
    ProcessHistory("INVENTORY","","","!\n");

    return(0);
}

# This routine parses "show tech ribd running" for Ribd sub-code commands running.
sub WriteRibd {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In WriteRibd: $_" if ($debug);

    while (<$INPUT>) {
        tr/\015//d;
        last if (/^$prompt/);
        next if (/^(\s*|\s*$cmd\s*)$/);
        return(1) if /^% Invalid input/;
        return(0) if /^% Error displaying /;    # Only do this routine once

        ProcessHistory("RIBD","","","!Ribd: $_");
    }
    ProcessHistory("RIBD","","","!\n");
    return(0);
}

# This routine processes a "write term"
sub WriteTerm {
    my($INPUT, $OUTPUT, $cmd) = @_;
    print STDERR "    In WriteTerm: $_" if ($debug);
    my($lineauto, $sortkey) = (0, 0);

    while (<$INPUT>) {
	tr/\015//d;
	last if (/^$prompt/);
	return(1) if /^% Invalid input/;
	return(0) if ($found_end);		# Only do this routine once

	# Dog gone Cool matches to process the rest of the config
        # Lots of Cisco-specific stuff here, but leaving it alone for now.
	/^tftp-server flash /   && next; # kill any tftp remains
	/^ntp clock-period /    && next; # kill ntp clock-period
	/^ length /		&& next; # kill length on serial lines
	/^ width /		&& next; # kill width on serial lines
	$lineauto = 1 if /^ modem auto/;
	/^ speed / && $lineauto	&& next; # kill speed on serial lines
	/^ clockrate /		&& next; # kill clockrate on serial interfaces
	/^! Time: /		&& next; # EOS gives the time that a "show running" command was run

	next if (/(^\*+$|unsaved changes exist)/i);

	if (/^(enable )?(password|passwd)( level \d+)? / && $filter_pwds >= 1) {
	    ProcessHistory("ENABLE","","","!$1$2$3 <removed>\n");
	    next;
	}
	if (/^(enable secret) / && $filter_pwds >= 2) {
	    ProcessHistory("ENABLE","","","!$1 <removed>\n");
	    next;
	}
	if (/^username (\S+)(\s.*)? secret /) {
	    if ($filter_pwds >= 2) {
		ProcessHistory("USER","keysort","$1",
			       "!username $1$2 secret <removed>\n");
	    } else {
		ProcessHistory("USER","keysort","$1","$_");
	    }
	    next;
	}
	if (/^username (\S+)(\s.*)? password ((\d) \S+|\S+)/) {
	    if ($filter_pwds >= 2) {
		ProcessHistory("USER","keysort","$1",
			       "!username $1$2 password <removed>\n");
	    } elsif ($filter_pwds >= 1 && $4 ne "5"){
		ProcessHistory("USER","keysort","$1",
			       "!username $1$2 password <removed>\n");
	    } else {
		ProcessHistory("USER","keysort","$1","$_");
	    }
	    next;
	}
	if (/^(\s*)password / && $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1password <removed>\n");
	    next;
	}
	if (/^(\s*)secret / && $filter_pwds >= 2) {
	    ProcessHistory("","","","!$1secret <removed>\n");
	    next;
	}
	if (/^\s*neighbor (\S*) password / && $filter_pwds >= 1) {
	    ProcessHistory("","","","! neighbor $1 password <removed>\n");
	    next;
	}
	if (/^( ip ospf authentication-key) / && $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1 <removed>\n"); next;
	}
	# isis passwords appear to be completely plain-text
	if (/^\s+isis password (\S+)( .*)?/ && $filter_pwds >= 1) {
	    ProcessHistory("","","","!isis password <removed>$2\n"); next;
	}
	if (/^\s+(domain-password|area-password) (\S+)( .*)?/
							&& $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1 <removed>$3\n"); next;
	}
	# this is reversable, despite 'md5' in the cmd
	if (/^( ip ospf message-digest-key \d+ md5) / && $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1 <removed>\n"); next;
	}
	# this is also reversable, despite 'md5 encrypted' in the cmd
	if (/^(  message-digest-key \d+ md5 (7|encrypted)) /
	    && $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1 <removed>\n"); next;
	}
	# sort route-maps
	if (/^route-map (\S+)/) {
	    my($key) = $1;
	    my($routemap) = $_;
	    while (<$INPUT>) {
		tr/\015//d;
		last if (/^$prompt/ || ! /^(route-map |[ !])/);
		if (/^route-map (\S+)/) {
		    ProcessHistory("ROUTEMAP","keysort","$key","$routemap");
		    $key = $1;
		    $routemap = $_;
		} else  {
		    $routemap .= $_;
		}
	    }
	    ProcessHistory("ROUTEMAP","keysort","$key","$routemap");
	}
	# filter out any RCS/CVS tags to avoid confusing local CVS storage
	s/\$(Revision|Id):/ $1:/;
	# order access-lists
	/^access-list\s+(\d\d?)\s+(\S+)\s+(\S+)/ &&
	    ProcessHistory("ACL $1 $2","$aclsort","$3","$_") && next;
	# order extended access-lists
	/^access-list\s+(\d\d\d)\s+(\S+)\s+ip\s+host\s+(\S+)/ &&
	    ProcessHistory("EACL $1 $2","$aclsort","$3","$_") && next;
	/^access-list\s+(\d\d\d)\s+(\S+)\s+ip\s+(\d\S+)/ &&
	    ProcessHistory("EACL $1 $2","$aclsort","$3","$_") && next;
	/^access-list\s+(\d\d\d)\s+(\S+)\s+ip\s+any/ &&
	    ProcessHistory("EACL $1 $2","$aclsort","0.0.0.0","$_") && next;
	# order arp lists
	/^arp\s+(\d+\.\d+\.\d+\.\d+)\s+/ &&
	    ProcessHistory("ARP","$aclsort","$1","$_") && next;
	/^ip prefix-list\s+(\S+)\s+seq\s+(\d+)\s+(permit|deny)\s+(\d\S+)(\/.*)$/ &&
	    ProcessHistory("PACL $1 $3","$aclsort","$4","ip prefix-list $1 $3 $4$5\n")
	    && next;
	# order logging statements
	/^logging (\d+\.\d+\.\d+\.\d+)/ &&
	    ProcessHistory("LOGGING","ipsort","$1","$_") && next;
	# order/prune snmp-server host statements
	# we only prune lines of the form
	# snmp-server host a.b.c.d <community>
	if (/^snmp-server host (\d+\.\d+\.\d+\.\d+) /) {
	    if ($filter_commstr) {
		my($ip) = $1;
		my($line) = "snmp-server host $ip";
		my(@tokens) = split(' ', $');
		my($token);
		while ($token = shift(@tokens)) {
		    if ($token eq 'version') {
			$line .= " " . join(' ', ($token, shift(@tokens)));
			if ($token eq '3') {
			    $line .= " " . join(' ', ($token, shift(@tokens)));
			}
		    } elsif ($token eq 'vrf') {
			$line .= " " . join(' ', ($token, shift(@tokens)));
		    } elsif ($token =~ /^(informs?|traps?|(no)?auth)$/) {
			$line .= " " . $token;
		    } else {
			$line = "!$line " . join(' ', ("<removed>",
						 join(' ',@tokens)));
			last;
		    }
		}
		ProcessHistory("SNMPSERVERHOST","ipsort","$ip","$line\n");
	    } else {
		ProcessHistory("SNMPSERVERHOST","ipsort","$1","$_");
	    }
	    next;
	}
	if (/^(snmp-server community) (\S+)/) {
	    if ($filter_commstr) {
		ProcessHistory("SNMPSERVERCOMM","keysort","$_",
			       "!$1 <removed>$'") && next;
	    } else {
		ProcessHistory("SNMPSERVERCOMM","keysort","$_","$_") && next;
	    }
	}
	# prune tacacs/radius server keys
	if (/^((tacacs|radius)-server\s(\w*[-\s(\s\S+])*\s?key) (\d )?\w+/
	    && $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1 <removed>$'"); next;
	}
	# order alias statements
	/^alias / && ProcessHistory("ALIAS","keysort","$_","$_") && next;
	# delete ntp auth password - this md5 is a reversable too
	if (/^(ntp authentication-key \d+ md5) / && $filter_pwds >= 1) {
	    ProcessHistory("","","","!$1 <removed>\n"); next;
	}
	# order ntp peers/servers
	if (/^ntp (server|peer) (\d+)\.(\d+)\.(\d+)\.(\d+)/) {
	    $sortkey = sprintf("$1 %03d%03d%03d%03d",$2,$3,$4,$5);
	    ProcessHistory("NTP","keysort",$sortkey,"$_");
	    next;
	}

	# catch anything that wasnt matched above.
	ProcessHistory("","","","$_");
	# end of config.
	if (/^end$/) {
	    $found_end = 1;
	    return(0);
	}
    }

    return(0);
}

1;
