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