home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / linux / network / domain-check-4.0 < prev    next >
Text File  |  2008-12-29  |  20KB  |  531 lines

  1. #!/usr/bin/perl -ws
  2. # Created by Ben Okopnik on Thu Jun 28 09:11:52 EDT 2007
  3. #
  4. # Copyright (C) 2007 Ben Okopnik <ben@okopnik.com>
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14.  
  15. =pod
  16. ################################## Changelog ##############################
  17. 12/30/08 12:33 v4.0
  18. * Hostfile parsing is now a bit more robust (tolerant of comments and blanks
  19. in the host list file.) Thanks to ESR for the pointer!
  20.  
  21. 11/09/08 09:55 v3.9
  22. * North Koreans (silently) switched their WHOIS and now use an invalid year
  23. (9999.) This crashes 'timegm()' - so I've added a "ridiculous year" detector.
  24.  
  25. 10/22/08 09:33 v3.8
  26. * Added several Korean formats - 'gabia.com', 'yesnic.com', 'cfolder.net'.
  27. Thanks, Sukbum Hong!
  28.  
  29. 08/27/08 19:55 v3.7
  30. * Tweaked for the PairNIC date format. Thanks to Janek Hellqvist for the
  31. heads-up!
  32.  
  33. 07/27/08 22:33 v3.6
  34. * Added a .ca "special": 'Renewal date:'
  35.  
  36. 11/05/07 21:01 v3.5
  37. * Tweaked to resolve .cz ("expire:" along with "expires:")
  38.  
  39. 09/25/07 12:27 v3.4
  40. * Tweaked regexes to include the ".name" date syntax.
  41.  
  42. 08/15/07  1:06 v3.3
  43. * Added a bit more CLI error checking (trips off on '-d foo.com', etc.)
  44.  
  45. 08/14/07 23:03 v3.2
  46. * Polished the regexen based on Rick Moen's list of 270 TLDs
  47. * Wrapped the date-calc section in an eval for cases where the date is past
  48.     the Unix "death boundary" (18-Jan-2038)
  49.  
  50. 08/08/07 23:26 v3.1
  51. * Added another regex to parse the weird structure of 'extragalactic.net';
  52.     modified another regex slightly to accomodate 'expire date' for 'nic.it'.
  53.  
  54. 07/29/07  1:26 v3.0
  55. * MAJOR REVISION:
  56.     o The format of the 'domain-list' file has been changed, although the
  57.       old format is still valid. You can now add the name of the host for
  58.       'whois' to use as the second argument on the line; however, using the
  59.       '-s' command line argument will force all lookups to be done via the
  60.       specified host.
  61.     o Fixed up a number of regexen for the 'jwhois' differences
  62.  
  63. 07/28/07  0:41 - v2.2
  64. * Added 'jwhois' as the preferred option, with a warning if it's not
  65.     installed. Caching for 'jwhois' is disabled when '-X' is in effect;
  66.     '-H' is no longer a hard-wired argument to 'whois' ('jwhois' doesn't
  67.     support it), but is still appended if 'whois' is used.
  68. * Tweaked a couple of the regexen to process new TLDs (.fi, .ly, etc.)
  69. * Giving serious thought to modifying the format of the -F files; it would
  70.     be nice to be able to specify the whois server for individual domains.
  71.  
  72. 07/20/07  9:36 - v2.1
  73. * Added a bunch of tracing/debugging statements to the date parser, making
  74.     the '-X' option much more useful
  75. * Built a 'switch-case' structure around the parser so that only one regex
  76.     would apply to any given host
  77. * Added a '-H' argument to 'whois' ("elide legal disclaimer") to make
  78.     debugging output less annoying (and maybe speed things up fractionally)
  79. * Made the 'no expiration date found' error into a non-fatal warning (used
  80.     to break list processing)
  81. * Modified the output format slightly (warnings now appear on the same line
  82.     as the domain name)
  83. * Domains without a registrar will no longer be omitted from the mailed
  84.     notifications
  85.  
  86. 07/19/07 22:28 - v2.0
  87. * Now parsing .ci domains as well (millions of people cheer, world peace
  88.     can't be far away now...)
  89.  
  90. 07/19/07 20:54 - v1.9
  91. * Added a little regex-fu to accept lines that have whitespace at the end
  92. * Added a Big Sekrit Option ('-X' - shhh, don't tell anybody!) for debugging
  93.  
  94. 07/19/07 11:56 - v1.8
  95. * Lots and lots of fixes for many different TLDs; much mangling of regexen.
  96.     Now handles many more expiration date types than before. Most
  97.     importantly, domains that don't list a registrar will now be displayed
  98.     anyway; people probably know where to send their money, but not
  99.     necessarily _when._
  100.  
  101. 07/04/07 12:28 - v1.7
  102. * Scrapped previous approach to the .org delay; the .orgs are now sorted to
  103.     the end of the domain list and all except the first one wait 20 seconds.
  104. * Added a cute little time ticker to the delay routine, just because. :)
  105.  
  106. 07/03/07  1:27 - v1.6
  107. * Added a rate limiter (3/minute) for .org domains
  108.  
  109. 06/30/07 18:34 - v1.5
  110. * Added a "domain not parseable; please report" warning
  111. * Added an "Unable to read 'whois' info" warning for the 'fgets: connection
  112.     reset by peer' error.
  113. * All expiration warnings are now sent as one email instead of one per
  114.     domain; ditto the expired domains notifications.
  115. * The 'printf' for the 'SKIPPED' error was ignoring the '-q' option; fixed
  116.  
  117. 06/30/07  8:19 - v1.4
  118. * Removed dependency on File::Find; searching PATH 'manually'
  119. * Added an 'exit 1' to the silent failure mode of 'croak'
  120.  
  121. 06/30/07  7:06 - v1.3
  122. * Improved the date-parsing regexes (the numerical months part can now only
  123.     match '01-12' instead of 'any two digits'); this should increase the
  124.     reliability of resolving 'dd-mm-yyyy' vs. 'mm-dd-yyyy' somewhat.
  125. * More accurate reporting for the 'SKIPPED' error (now shows exact reason)
  126. * Fixed the regexes that I screwed up while adding the Dotster extension
  127. * Added a '-v' option
  128.  
  129. 06/29/07 18:54 - v1.2
  130. * Got rid of an unnecessary system dependency ('which') - 'File::Find' is a
  131.     bit clunky, but better than depending on unknowns...
  132. * Another date-processing regex (ISOC-IL: 'validity: 29-06-2007')
  133.  
  134. 06/29/07 17:07 - v1.1
  135. * Modified output format to include both exp. date and days remaining
  136. * Added another date-processing regex (DOTSTER: 'Expires on: 29-Jun-07')
  137.  
  138. 06/29/07 15:06 - v1.0
  139. I'm finally willing to admit that this script is usable. :) Recent changes
  140. include:
  141.  
  142. * Parsing routine for "2007/08/12" date format
  143. * 'croak' notifies admin of problems encountered in silent mode
  144. * Added a fallback email address for 'croak'
  145. * Fixed GMT parsing routine miscalc (thanks to Rick Moen for the heads up)
  146.  
  147. For Nosy Nellies only: *Yes*, I'm aware of the various '*Whois.pm' modules
  148. on CPAN. None of them do what I want; the one that comes closest
  149. (Net::XWhois) hasn't been maintained since 2001 and only covers a smallish
  150. subset of what I want. No, I'm not interested in taking it over and
  151. maintaining it; I've got enough to do as it is.
  152.  
  153. ###########################################################################
  154. =cut
  155.  
  156. use strict;
  157. use Time::Local;
  158. $|++;
  159.  
  160. # Command-line variables
  161. our ($d, $e, $F, $h, $q, $s, $v, $x, $X);
  162.  
  163. ### FALLBACK ADDRESS FOR NOTIFICATION ############
  164. my $address = 'root@localhost';
  165. ##################################################
  166.  
  167. my ($name) = $0 =~ /([^\/]+)$/;
  168.  
  169. my $usage =<<"+EoT+";
  170. Usage: $name [-e=email] [-x=expir_days] [-q] [-h] <-d=domain_name|-F=domainfile>
  171.  
  172.   -d=domain        : Domain to analyze
  173.   -e=email_address : Send a warning message by email
  174.   -F=domain_list   : File with a list of domains, one per line
  175.   -h               : Print this message
  176.   -q               : Don't print to the console (REQUIRES '-e' OPTION)
  177.   -s=whois server  : Use alternate whois server
  178.   -v               : Display current version of this script
  179.   -x=days          : Change default (30d) expiration interval (REQUIRES '-e' OPTION)
  180.  
  181. +EoT+
  182.  
  183. # Locate 'whois' or (preferred) 'jwhois'
  184. my ($whois) = grep -e, map "$_/jwhois", split /:/, $ENV{PATH};
  185. ($whois) = grep -e, map "$_/whois", split /:/, $ENV{PATH} unless $whois;
  186. die "'whois'|'jwhois' not found in path.\n" unless $whois;
  187. if ($whois =~ m#/whois$#){
  188.     # $q || print "You really should install 'jwhois'; it gives better results.\n";
  189.     # Turn down the noise (minimal output option - only works with 'whois')
  190.     $whois .= " -H";
  191. }
  192. else {
  193.     # Turn off caching for 'jwhois' if the debug option is on
  194.     $whois .= " -f" if $X;
  195. }
  196.  
  197. # $whois = "/usr/bin/whois";
  198.  
  199. # Find a mail client (mutt or mailx)
  200. my ($mail) = grep -e, map "$_/mutt", split /:/, $ENV{PATH};
  201. # Switch Mutt into 'mailx' mode if found
  202. if ($mail){
  203.     $mail .= " -x";
  204. }
  205. else {
  206.     ($mail) = grep -e, map "$_/mailx", split /:/, $ENV{PATH};
  207. }
  208. die "No 'mailx' or 'mutt' (mail client) found in path.\n" unless $mail;
  209.  
  210. # Read the version number at the top of the changelog
  211. if ($v){
  212.     seek DATA, 0, 0;
  213.     while (<DATA>){
  214.         if (m[^\d+/\d+/\d+[^v]+v([0-9.]+)]){
  215.             print "Version: $1\nCopyright (C) 2007 Ben Okopnik <ben\@okopnik.com>\n\n";
  216.             exit 0;
  217.         }
  218.     }
  219. }
  220.  
  221. # Email admin if '-q' is on; otherwise, just exit with the error
  222. sub croak {
  223.     if ($q){
  224.         # If '-e' wasn't specified, use the fallback address
  225.         $e ||= $address;
  226.  
  227.         # No place to send an error if this fails... :)
  228.         open Mail, "|$mail -s 'WARNING: $name script error' $e";
  229.         print Mail "$name [" . localtime() . "]: ", $_[0];
  230.         close Mail;
  231.  
  232.         exit 1;
  233.     }
  234.     else {
  235.         die $_[0];
  236.     }
  237. }
  238.  
  239. # Display the help output if requested or in case of incorrect usage
  240. die "$usage\n" if $h;
  241. die "\n*ERROR: '$name' requires an email address with the '-q' and the '-x' options*\n\n$usage" if ($q || $x) && ! $e;
  242. die "\n*ERROR: '$name' requires either a domain name or a domain list as an argument*\n\n$usage" if ! $d && ! $F;
  243. die "\n*ERROR: Please make sure you're using correct syntax (i.e., '-d=domain_name')*\n\n$usage" if (defined $d && $d =~ /^1$/) || (defined $F && $F =~ /^1$/) || (defined $s && $s =~ /^1$/);
  244.  
  245. # Set default notification interval to 30 days
  246. if ($x){
  247.     croak "Expiration interval must be specified in days (0-9999).\n"
  248.         unless $x =~ /^\d{1,4}$/;
  249. }
  250. else {
  251.     $x = 30;
  252. }
  253.  
  254. # Read the domain list file
  255. my @domains;
  256. if ($F){
  257.     croak "$F is not a regular file\n" unless -f $F;
  258.     croak "Can't read $F\n" unless -r _;
  259.     # Open the file if it exists
  260.     open F or croak "$F: $!\n";
  261.     while (<F>){
  262.         # Skip blank lines; ignore comments
  263.         next if /^\s*(?:#|$)/;
  264.         # Strip preceding and following blanks
  265.         s/^\s*(.*?)\s*$/$1/;
  266.  
  267.         # Separate domain and server if they exist
  268.         my (@line) = split;
  269.         for (@line){
  270.             # Strip URI method and any terminal '/'s
  271.             s#^.*://##;
  272.             s#/$##;
  273.         }
  274.         push @domains, [ @line ];
  275.     }
  276.     close F;
  277. }
  278.  
  279. # Having a '-F' AND a '-d' is explicitly not excluded
  280. if ($d){
  281.     # Strip URI method and any terminal '/'s
  282.     $d =~ s#^.*://##;
  283.     $d =~ s#/$##;
  284.     push @domains, [ $d ];
  285. }
  286.  
  287. # Set the server if it's been specified (this REPLACES any servers defined
  288. # in the domain-list file)
  289. if ($s){
  290.     $_ -> [1] = $s for @domains;
  291. }
  292.  
  293. # Sort list to push .orgs to the end; ASCIIbetical sort otherwise
  294. @domains = sort { ($a->[0] =~ /\.org$/i) <=> ($b->[0] =~ /\.org$/i) || $a->[0] cmp $b->[0] } @domains;
  295.  
  296. # Trim strings to specified length; return '**UNKNOWN**' if undef
  297. sub trim {
  298.     defined $_[0] || return "**UNKNOWN**";
  299.     substr($_[0], 0, $_[1]);
  300. }
  301.  
  302. # Lookup list for month number->name conversion
  303. my (%mth,%mlookup);
  304. @mth{map sprintf("%02d", $_), 1..12} = qw/jan feb mar apr may jun jul aug sep oct nov dec/;
  305. # Lookup list for month name->abbrev conversion
  306. @mlookup{qw/january february march april may june july august september october november december/} =
  307.     (qw/jan feb mar apr may jun jul aug sep oct nov dec/) x 2;
  308.  
  309. ########################## DATA COLLECTION SECTION #############################
  310.  
  311. # Process the domain list
  312. my ($seen, %list);
  313. for my $line (@domains){
  314.     next if $line =~ /^\s*(?:#|$)/;
  315.  
  316.     my ($host, $server) = @{$line};
  317.  
  318.     my $opt = $server ? "-h $server" : "";
  319.  
  320.     $q || print "\b\nProcessing $host... ";
  321.  
  322.     # Delay to avoid triggering rate limiter
  323.     if ($host =~ /\.org$/i){
  324.         $q || print "(NOTE: Subsequent ORG queries will be delayed by 20 seconds each due to rate limiting) "
  325.             unless $seen;
  326.         # Show the cute little time ticker :)
  327.         if ($seen++){
  328.             my @chars = split //, '|/-\\';
  329.             for (0 .. 19){
  330.                 $q || print $chars[$_ % 4], "\b";
  331.                 sleep 1;
  332.             }
  333.             print " \b";
  334.         }
  335.     }
  336.  
  337.     # Execute the query, save as a single string
  338.     open Who, "$whois $opt $host|" or croak "Error executing $whois: $!\n";
  339.     my $out = do { local $/; <Who> };
  340.     close Who;
  341.  
  342.     # Make sure it's not DOS formatted
  343.     $out =~ tr/\cM//d;
  344.  
  345.     # 'fgets: connection reset by peer' - bloody annoying response!
  346.     if (!$out || $out !~ /domain/i){
  347.         $q || print "Unable to read 'whois' info for $host. Skipping... ";
  348.         next;
  349.     }
  350.  
  351.     # Freak out and run away if there's no match
  352.     if ($out =~ /no match/i){
  353.         $q || print "No match for $host!\n";
  354.         next;
  355.     }
  356.     # Ditto for bad hostnames
  357.     if ($out =~ /No whois server is known for this kind of object/i){
  358.         $q || print "'whois' doesn't recognize this kind of object. ";
  359.         next;
  360.     }
  361.  
  362.     # Convert multi-line 'labeled block' output to 'Label: value'
  363.     my $debug;
  364.     if ($out =~ /registrar:\n/i){
  365.         $out =~ s/:\n(?!\n)/: /gsm;
  366.         $debug .= "matched on line " . (__LINE__ - 1) . ": Multi-line 'labeled block'\n";
  367.     }
  368.  
  369.     # Date processing; this is the heart of the program. Desired date format is '29-jun-2007'
  370.     # 'Fri Jun 29 15:16:00 EDT 2007'
  371.     if ($out =~ s/(date:\s*| on:\s*)[A-Z][a-z]+\s+([a-zA-Z]{3})\s+(\d+).*?(\d+)\s*$/$1$3-$2-$4/igsm){
  372.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'Fri Jun 29 15:16:00 EDT 2007'\n";
  373.     }
  374.     # '29-Jun-07'
  375.     elsif ($out =~ s/(date:\s*| on:\s*)(\d{2})[\/ -](...)[\/ -](\d{2})\s*$/$1$2-$3-20$4/igsm){
  376.         $debug .= "matched on line " . (__LINE__ - 1) . ": '29-Jun-07'\n";
  377.     }
  378.     # '2007-Jun-29'
  379.     elsif ($out =~ s/[^\n]*(?:date| on|expires on\.+):\s*(\d{4})[\/-](...)[\/-](\d{2})\.?\s*$/Expiration date: $3-$2-$1/igsm){
  380.         $debug .= "matched on line " . (__LINE__ - 1) . ": '2007-Jun-29'\n";
  381.     }
  382.     # '2007/06/29'
  383.     elsif ($out =~ s/(?:renewal-|expir(?:e|es|y|ation)\s*)(?:date|on)?[ \t.:]*\s*(\d{4})(?:[\/-]|\. )(0[1-9]|1[0-2])(?:[\/-]|\. )(\d{2})(?:\.?\s*[0-9:.]*\s*\w*\s*|\s+\([-A-Z]+\)?)$/Expiration date: $3-$mth{$2}-$1/igsm){
  384.         $debug .= "matched on line " . (__LINE__ - 1) . ": '2007/06/29'\n";
  385.     }
  386.     # '29-06-2007'
  387.     elsif ($out =~ s/(?:validity:|expir(?:y|ation) date:|expire:|expires? (?:on:?|on \([dmy\/]+\):|at:))\s*(\d{2})[\/.-](0[1-9]|1[0-2])[\/.-](\d{4})\s*[0-9:.]*\s*\w*\s*$/Expiration date: $1-$mth{$2}-$3/igsm){
  388.         $debug .= "matched on line " . (__LINE__ - 1) . ": '29-06-2007'\n";
  389.     }
  390.     # '[Expires on]     2007-06-29' (.jp, .ru, .ca); 'Valid Date     2016-11-02 04:21:35 EST' (yesnic.com); 'Domain Expiration Date......: 2009-01-15 GMT.' (cfolder.net)
  391.     elsif ($out =~ s/(?:valid[- ]date|(?:renewal|expiration) date(?::|\.+:)|paid-till:|\[expires on\]|expires on ?:|expired:)\s*(\d{4})[\/.-](0[1-9]|1[0-2])[\/.-](\d{2})(?:\s*[0-9:.]*\s*\w*\s*|T[0-9:]+Z| GMT\.)$/Expiration date: $3-$mth{$2}-$1/igsm){
  392.         $debug .= "matched on line " . (__LINE__ - 1) . ": '[Expires on]     2007-06-29' (.jp, .ru)\n";
  393.     }
  394.     # 'expires:     June  29[, ]+2007' (.is, PairNIC); 'Record expires on       JULY      21, 2016' (gabia.com)
  395.     elsif ($out =~ s/(?:expires:|expires on)\s*([A-Z][a-z]+)\s+(\d{1,2})(?:\s|,)+(\d{4})\s*$/"Expiration date: " . sprintf("%02d", $2) . "-" . $mlookup{"\L$1\E"} . "-$3"/igsme){
  396.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'expires:     June  29 2007' (.is)\n";
  397.     }
  398.     # 'renewal: 29-June-2007'
  399.     elsif ($out =~ s/renewal:\s*(\d{1,2})[\/ -]([A-Z][a-z]+)[\/ -](\d{4})\s*$/"Expiration date: $1-" . $mlookup{"\L$2\E"} . "-$3"/igsme){
  400.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'renewal: 29-June-2007' (.ie)\n";
  401.     }
  402.     # 'expire:         20080315' (.cz, .ke)
  403.     elsif ($out =~ s/expir[ey]:\s*(\d{4})(\d{2})(\d{2})\s*$/Expiration date: $3-$mth{$2}-$1/igsm){
  404.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'expire:         20080315' (.cz, .ke)\n";
  405.     }
  406.     # 'domain_datebilleduntil: 2007-06-29T00:00:00+12:00' (.nz)
  407.     elsif ($out =~ s/domain_datebilleduntil:\s*(\d{4})[-\/](\d{2})[-\/](\d{2})T[0-9:.+-]+\s*$/Expiration date: $3-$mth{$2}-$1/igsm){
  408.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'domain_datebilleduntil: 2007-06-29T00:00:00+12:00' (.nz)\n";
  409.     }
  410.     # '29 Jun 2007 11:58:42 UTC' (.coop)
  411.     elsif ($out =~ s/(?:expir(?:ation|y) date|expire[sd](?: on)?)[:\] ]\s*(\d{2})[\/ -](...)[\/ -](\d{4})\s*[0-9:.]*\s*\w*\s*$/Expiration date: $1-\L$2\E-$3/igsm){
  412.         $debug .= "matched on line " . (__LINE__ - 1) . ": '29 Jun 2007 11:58:42 UTC' (.coop)\n";
  413.     }
  414.     # 'Record expires on 17/8/2100' (.hm, fi)
  415.     elsif ($out =~ s/(?:expires(?: on|:))\s*(\d{2})[\/.-]([1-9]|0[1-9]|1[0-2])[\/.-](\d{4})\s*[0-9:.]*\s*\w*\s*$/"Expiration date: $1-".$mth{sprintf "%02d", $2} . "-$3"/iegsm){
  416.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'Record expires on 17/8/2100' (.hm)\n";
  417.     }
  418.     # 'Expires on..............: Sat, Mar 29, 2008'
  419.     elsif ($out =~ s/expires on\.*:\s*(?:[SMTWF][uoehra][neduit]),\s+([A-Z][a-z]+)\s+(\d{1,2}),\s+(\d{4})\s*$/"Expiration date: " . sprintf("%02d", $2) . "-\L$1-$3"/iegsm){
  420.         $debug .= "matched on line " . (__LINE__ - 1) . ": 'Expires on..............: Sat, Mar 29, 2008'\n";
  421.     }
  422.     else {
  423.         $debug = "No regexes matched.\n";
  424.     }
  425.  
  426.     # Collect the data from each query
  427.     for (split /\n/, $out){
  428.         # Clip pre- and post- blanks
  429.         s/^\s*(.*?)\s*$/$1/;
  430.         # Squash repeated tabs and spaces
  431.         tr/ \t//s;
  432.  
  433.         # This is where it all happens - regexes to capture registrar and expiration
  434.         $list{$host}{Registrar} ||= $1 if /(?:maintained by|registration [^:]*by|authorized agency|registrar)(?:\s*|_)(?:name|id|of record)?:\s*(.*)$/i;
  435.         $list{$host}{Expires} ||= $1 if /(?:expires(?: on)?|expir(?:e|y|ation) date\s*|renewal(?:[- ]date)?)[:\] ]\s*(\d{2}-[a-z]{3}-\d{4})/i;
  436.         # print "Registrar: $list{$host}{Registrar}\nExpires: $list{$host}{Expires}\n";
  437.     }
  438.  
  439.     # Assign default message if no registrar was found
  440.     $list{$host}{Registrar} ||= "[[[ No registrar found ]]]";
  441.     
  442.     $q || print "No expiration date found in 'whois' output. Please report this domain to the author!"
  443.         unless defined $list{$host}{Expires};
  444.  
  445.     # Debug option (activated by '-X'); exits here with parsed 'whois' output
  446.     $debug .= "Registrar: $list{$host}{Registrar}\n" if defined $list{$host}{Registrar};
  447.     $debug .= "Expires: $list{$host}{Expires}\n" if defined $list{$host}{Expires};
  448.     die "\n", "=" x 70, "\n$out", "=" x 70, "\n$debug", "=" x 70, "\n" if $X;
  449. }
  450.  
  451. $q || print "\n";
  452.  
  453. ########################## DATA ANALYSIS SECTION #############################
  454.  
  455. # Get current time snapshot in UTC
  456. my $now = timegm(gmtime);
  457.  
  458. # Convert dates to UTC epoch seconds; *will* fail on 19 Jan 2038. :)
  459. my %months;
  460. @months{qw/jan feb mar apr may jun jul aug sep oct nov dec/} = 0..11;
  461.  
  462. # Print the header if '$q' is off and there's content in %list
  463. $q || %list && printf "\n\n%-24s%-36s%s\n%s\n", "Host", "Registrar", "Exp.date/Days left", "=" x 78;
  464.  
  465. # Process the collected data
  466. my (%exp, %end);
  467. for my $k (sort keys %list){
  468.     unless (defined $list{$k}{Expires}){
  469.         $q || printf "%-32s%s\n", trim($k, 31), "*** SKIPPED (missing exp. date) ***";
  470.         delete $list{$k};
  471.         next;
  472.     }
  473.     my @chunks = split /-/, $list{$k}{Expires};
  474.     my $epoch;
  475.  
  476.     if ($chunks[2] > 2038){
  477.         $q || print "**** NOTE: Year out of range - date will NOT be calculated correctly! ****\n";
  478.         # Set epoch to EPOCH_MAX
  479.         $epoch = 2147212800;
  480.     }
  481.     else {
  482.         eval { $epoch = timegm(0, 0, 0, $chunks[0], $months{lc $chunks[1]}, $chunks[2] - 1900) };
  483.         if ($@){
  484.             $q || print "$@\n";
  485.             if ($@ =~ /too big/){
  486.                 $q || print "**** NOTE: Date past 19-Jan-2038 - date will NOT be calculated correctly! ****\n";
  487.             }
  488.             # Set epoch to EPOCH_MAX
  489.             $epoch = 2147212800;
  490.         }
  491.     }
  492.     my $diff = int(($epoch - $now) / 86400);
  493.     $q || printf "%-24s%-36s%-12s/%5s\n", trim($k, 23), trim($list{$k}{Registrar}, 35),
  494.         $list{$k}{Expires}, $diff;
  495.  
  496.     # Prepare alerts if domain is expired or the expiration date is <= $x days
  497.     if ($e && ($diff <= $x)){
  498.         if ($diff <= 0){
  499.             $exp{$k} = -$diff;
  500.         }
  501.         else {
  502.             $end{$k} = $diff;
  503.         }
  504.     }
  505. }
  506.  
  507. # Report expired domains
  508. if (%exp){
  509.     open Mail, "|$mail -s '$name: Expired domains' $e" or croak "$mail: $!\n";
  510.     print Mail "According to 'whois', the following domains have expired:\n\n";
  511.     for my $x (sort { $exp{$a} <=> $exp{$b} } keys %exp){
  512.         my $s = $exp{$x} == 1 ? "" : "s";
  513.         print Mail "$x ($exp{$x} day$s ago)\n";
  514.     }
  515.     close Mail;
  516. }
  517.  
  518. # Report domains that will expire within the '-x' period
  519. if (%end){
  520.     open Mail, "|$mail -s '$name: Domain expiration warning ($x day cutoff)' $e" or croak "$mail: $!\n";
  521.     print Mail "According to 'whois', these domains will expire soon:\n\n";
  522.     for my $d (sort { $end{$a} <=> $end{$b} } keys %end){
  523.         my $s = $end{$d} == 1 ? "" : "s";
  524.         print Mail "$d (in $end{$d} day$s)\n";
  525.     }
  526.     close Mail;
  527. }
  528.  
  529. __END__
  530.  
  531.