Source

bbdb / utils / bbdb-cid.pl

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#!/usr/local/bin/perl5 -w
#
# Caller-ID-logger, by jwz (19-Jan-97)
# Modified: 24-Apr-97
#
# Opens the modem and waits for it to print caller-ID data.  When it does,
# it logs it to a file, parses it, and pops up a window using "xmessage".
# If the number is present in your .bbdb file, it shows the name (or company)
# associated with it.  
#
# Todo:
#  My caller ID service (in San Francisco) only ever sends numbers, not names,
#  so I've never seen a "name" line come in; I assume that it would send both
#  a name and a number, so it would be nice to present both (with error 
#  checking against BBDB) but the code as currently structured only handles
#  one-line-per-call.  It should realize that consecutive lines with the same
#  timestamp are the same call.
#
#  Modems other than ZyXELs have different caller-ID formats, and this doesn't
#  deal with those.

##############################################################################
#
# Some variables you might want to set...


# Set this to the device that your modem is attached to.
#
$modem_device = "/dev/ttyd1";

# This is your .bbdb file.  (Set it to null if you don't want to do BBDB
# lookups at all, but why would you want to go and do a thing like that?)
#
$bbdb_file    = "$ENV{HOME}/.bbdb";

# A shell command to use to cause emacs to pop up the BBDB buffer
# (bbdb-srv.pl is a good choice, so it defaults to the value of the
# shell environment variable $NS_MSG_DISPLAY_HOOK.)
#
$bbdb_cmd     = $ENV{NS_MSG_DISPLAY_HOOK};

# If you want the $bbdb_cmd to be run on a different host, set it here.
#
$bbdb_host    = "gimp";

# If you want each call to be logged to a file as well, name it here.
#
$logfile      = "/usr/spool/fax/log/cid-log";

# For verbosity...
$debug        = 0;

# How to pop up a dialog box.
#
$xmessage_cmd	= "xmessage";
@xmessage_args	= ("-display",	":0",
		   "-name",	"Caller ID",
		   # roughly centered on my screen; YMMV.
		   "-geometry",	"+400+400",
		   "-xrm",	"*Font: -*-new cent*-bold-r-normal-*-240-*",
		   "-xrm",	"*Foreground: black",
		   "-xrm",	"*Background: lightgreen",
		   # no buttons on the window: dismiss it by clicking in it.
		   "-button",	"",
		   "-xrm", "*form.Translations: #override <BtnDown>: exit(0)",
		   "-xrm", "*Command.Font: -*-new cent*-bold-r-normal-*-120-*",
		   "-xrm", "*Command.horizDistance: 130"
		   );

# Uh, let's turn off the screensaver before popping up the window.
#
$pre_dialog_cmd = "xscreensaver-command -deactivate";


# commands (and their expected responses) used to initialize the modem.
#
@modem_init   = ( "AT",		"OK",		# ping
		  "ATZ",	"OK",		# reset
		  "ATE0",	"OK",		# don't echo commands
		  "ATM0",	"OK",		# turn off speaker
		  "ATN0",	"OK",		# turn off ringer
		  "ATS40.2=1",	"OK",		# turn on caller ID
	        );


# for diagnostics: if the modem ever asynchronously prints something that
# doesn't match this, we issue a warning.
#
$expected_responses = "^CALLER NUMBER"		. "|" .
    		      "^REASON FOR NO CALLER "	. "|" .
    		      "^RING"			. "|" .
    		      "^TIME: [-0-9: ]+\$";


##############################################################################
#
# Talking to the serial port...
#
#

if ( $ debug ) {
    use diagnostics;
}


sub open_modem {
    use IPC::Open2;

    # Close the terminal streams before forking `cu', because otherwise
    # it fucks around with the stty settings.
    #
    open(SAVEIN,  "<&STDIN")  || die("can't dup stdin");
    open(SAVEOUT, ">&STDOUT") || die("can't dup stdout");
    open(SAVEERR, ">&STDERR") || die("can't dup stderr");
    close(STDIN);
    close(STDOUT);
    close(STDERR);

    my $cu_pid = open2( \*MODEM_IN, \*MODEM_OUT,
		       "cu -l$modem_device -s2400 2>&1");

    # Now that cu has been launched, we can restore them.
    #
    open(STDIN,  "<&SAVEIN")  || die("can't restore stdin");
    open(STDOUT, ">&SAVEOUT") || die("can't restore stdout");
    open(STDERR, ">&SAVEERR") || die("can't restore stderr");
    close(SAVEIN);
    close(SAVEOUT);
    close(SAVEERR);

    # The following doesn't seem to work and I don't know why...
    #
    # Set up a signal handler to try and kill off the cu process
    # when we exit, instead of waiting ~30 seconds for it to notice
    # that the pipe is gone...
    #
#    $SIG{INT} = sub { my $signame = shift;
#		      if ( $debug) { 
#			  print STDERR "sending $signame to $cu_pid\n";
#		      }
#		      print MODEM_OUT "\r\n~.\r\n";
#		      close MODEM_OUT;
#		      close MODEM_IN;
#		      kill ($signame, $cu_pid);
#		      exit (1);
#		    };

    $_ = <MODEM_IN>;
    chop;
    if ( !m/^Connected/ ) {
	print STDERR "$0: cu printed `$_' instead of `Connected'\n";
    }
}

sub read_line {
    $_ = <MODEM_IN>;
    $_ || die("got eof on modem");
    s/[\r\n]+$//;
    if ( $_ eq "" ) {
	$_ = <MODEM_IN>;
	$_ || die("got eof on modem");
	s/[\r\n]+$//;
    }
    return $_;
}

sub command {
    my ( $command, $expected_response) = @_;

    if ( $debug ) {
	print STDERR "sending: $command\n";
    }

    print MODEM_OUT "$command\r\n";
    my $line = read_line();

    if ( $line eq $command ) {
	if ( $debug ) {
	    print STDERR "    got echo: reading next line too...\n";
	}
	$line = read_line();
    }

    if ( $line ne $expected_response ) {
	print STDERR "    got: $line ; expected: $expected_response\n";
    } elsif ( $debug ) {
	print STDERR "    got: $line\n";
    }
}

sub init_modem {
    open_modem;

    my $len = $#modem_init + 1;
    my $i;
    for ($i = 0; $i < $len; $i += 2) {
	command($modem_init[$i], $modem_init[$i+1]);
    }
}

sub handle_async_line {
    local ( $_ ) = @_;

    if (!m/$expected_responses/) {
	print STDERR "modem turd:   $_\n";

    } elsif (m/CALLER/) {
	if ( $debug ) {
	    print STDERR "caller: $_\n";
	}
	handle_cid_line($_);

    } elsif ( $debug ) {
	if ( $_ eq '' ) {
	    print STDERR "ignored: blank line\n";
	} else {
	    print STDERR "ignored: $_\n";
	}
    }
}


##############################################################################
#
# Parsing BBDB and CID data...
#

sub find_bbdb_record {
    my ( $area, $exchange, $suffix ) = @_;

    if ( ! $bbdb_file ) {
	return undef;
    }

    # strip off leading 0's, to match the way it's stored in .bbdb.
    $area     =~ s/^0+(.)/$1/;
    $exchange =~ s/^0+(.)/$1/;
    $suffix   =~ s/^0+(.)/$1/;

    my $bbdb_rec = undef;
    my $pat = "\\[\"[^\"]+\" $area $exchange $suffix (nil|[0-9]+)\\]";

    open(BBDB, "<$bbdb_file") || die("error opening $bbdb_file: $!\n");

    while (<BBDB>) {
	if ( m/$pat/ ) {
	    $bbdb_rec = $_;
	    last;
	}
    }
    close(BBDB);
    return $bbdb_rec;
}


# note: global (kludge!)
$pretty_number = 0;

sub make_message_string {
    my ( $number, $date, $fn, $ln, $co, $error ) = @_;
    my $msg;

    my $line_prefix = "    ";
    my $line_suffix = "    ";

    # First print the date (reformatted.)
    #
    $_ = $date;
    my ( $dotw, $mon, $day, $hr, $min, $sec, $year ) =
	m/^([^ ]+) +([^ ]+) +([^ ]+) +([^:]+):([^:]+):([^:]+) +([^ ]+) *$/;
    $year =~ s/^..(..)/$1/;
    $day  =~ s/^0//;
    $hr   =~ s/^0//;
    if ($hr < 12) {
	$ampm = "am";
    } else {
	$ampm = "pm";
	if ($hr > 12) { $hr -= 12 };
    }
    $date = "$hr:$min$ampm, $day-$mon-$year ($dotw)";
    $msg = $line_prefix . $date . $line_suffix;

    # Next print the caller name, company, or error message.
    #
    if ( $error ) {
	$msg .= "\n" . $line_prefix . $error . $line_suffix;
    } elsif ( $co && !$fn && !$ln ) {
	$msg .= "\n" . $line_prefix . $co . $line_suffix;
    } elsif ( $fn || $ln ) {
	$msg .= "\n" . $line_prefix . "$fn $ln" . $line_suffix;
    }

    # Next print the phone number (formatted nicely.)
    #
    if ( $number ) {
	my $area = 0;
	my $exchange = 0;
	my $suffix = 0;
	$_ = $number;
	( $area, $exchange, $suffix ) =
	    m/^([0-9][0-9][0-9])([0-9][0-9][0-9])([0-9][0-9][0-9][0-9]+)/;

	# note: global (kludge!)
	$pretty_number = "($area) $exchange-$suffix";
	$msg .= "\n" . $line_prefix . $pretty_number . $line_suffix;
    }

    return $msg;
}

use POSIX;
sub reaper {
    $SIG{CHLD} = \&reaper;  # loathe sysV
    my $signame = shift;
    if ( $debug >= 2 ) {
	printf STDERR "  (got SIG$signame...)\n";
    }
    my $child;
    while ( ( $child = waitpid(-1,WNOHANG) ),
	    $child > 0 ) {
	if ( $debug >= 2 ) {
	    printf STDERR "    (pid $child exited with $?)\n";
	}
    }
}

sub fork_and_exec {
    my @cmd_list = @_;

    $SIG{CHLD} = \&reaper;

    if ( $debug >= 2 ) {
	$_ = $cmd_list[0];
	s/ .*//;
	print STDERR "forking for " . $_ . " at " . (localtime) . ".\n";
    }

    my $pid;
    if ($pid = fork()) {
	# parent
    } elsif (!defined $pid) {
	print STDERR "$0: fork failed: $!\n";
    } else {
	# child

	if ( $debug ) {
	    $_ = $cmd_list[0];
	    s/ .*//;
	    print STDERR "exec'ing " . $_ . " at " . (localtime) .
		" in pid $$.\n";
	}
	close(STDIN);
	close(STDOUT);
	close(STDERR);
	exec @cmd_list;
    }
}


sub fork_and_exec_for_bbdb {
    my @cmd_list = @_;
    my $number = shift @cmd_list;

    $SIG{CHLD} = \&reaper;

    if ( $debug >= 2 ) {
	$_ = $cmd_list[0];
	s/ .*//;
	print STDERR "forking for " . $_ . " at " . (localtime) . ".\n";
    }

    my $pid;
    if ($pid = fork()) {
	# parent
    } elsif (!defined $pid) {
	print STDERR "$0: fork failed: $!\n";
	exit (1);
    } else {
	# child

	if ( $debug ) {
	    $_ = $cmd_list[0];
	    s/ .*//;
	    print STDERR "exec'ing " . $_ . " at " . (localtime) .
		" in pid $$.\n";
	}
	if ( system @cmd_list ) {
	    my $cmd = "gnudoit -q '(bbdb-srv-add-phone \"$pretty_number\")'";
	    if ( $bbdb_host ) {
		$cmd =~ s/([()\"])/\\$1/g;
		$cmd = "rsh $bbdb_host $cmd";
	    }
	    exec $cmd;
	}
	exit (0);
    }
}


sub pop_up_dialog {
    my ( $msg, $buttonp, $number ) = @_;

    fork_and_exec $pre_dialog_cmd;

    if ( ! $buttonp ) {
	fork_and_exec $xmessage_cmd, @xmessage_args, "\n$msg\n\n";
    } else {
	my @args = ( @xmessage_args, "-button", "Add To BBDB" );
	fork_and_exec_for_bbdb $number, $xmessage_cmd, @args, "\n$msg\n\n";
    }
}

sub pop_up_bbdb_buffer {
    my ( $caller ) = @_;
    if ( $bbdb_cmd ) {
	my $cmd = $bbdb_cmd;
	if ( $bbdb_host ) {
	    $cmd = "rsh $bbdb_host $cmd";
	}
	$caller =~ s/\\/\\\\/g;
	$caller =~ s/\"/\\\\\"/g;
	`echo "Path:\nFrom: \\\"$caller\\\" <>" | $cmd >&- 2>&- &`;
    }
}


sub handle_cid_line {
    my($line) = @_;

    my $date = localtime;

    # Log the call...
    #
    if ( $logfile ) {
	if (open(LOG, ">>$logfile")) {
	    print LOG "$date\t$line\r\n";
	    close LOG;
	} else {
	    print STDERR "error opening $logfile: $!\n";
	}
    }

    # Pull the phone number out of the message...
    #
    my $number = "";
    my $error = "";

    $_ = $line;
    if ( m/^CALLER NUMBER/ ) {
	( $number ) = m/^[^:]+: *(.*) *$/;
    } else {
	$error = $line;
    }

    my $caller = undef;

    my $fn = undef;
    my $ln = undef;
    my $co = undef;
    my $buttonp = 0;

    if ( !$number || $number eq "" ) {
       	$error =~ tr#A-Z#a-z#;
	$error =~ s/^REASON FOR NO CALLER (NUMBER|NAME)/Caller unknown/i;

    } else {
	$_ = $number;

	my $area = 0;
	my $exchange = 0;
	my $suffix = 0;
	( $area, $exchange, $suffix ) =
	    m/^([0-9][0-9][0-9])([0-9][0-9][0-9])([0-9][0-9][0-9][0-9]+)/;

	my $bbdb_rec = find_bbdb_record($area, $exchange, $suffix);

	if ( $bbdb_rec ) {
	    my $junk = 0;
	    $_ = $bbdb_rec;
	    # This will lose if names or aliases have double-quotes in them.
	    # No doubt there's some hairier regexp magic that handles that...
	    ( $fn, $ln ) = m/^[\[]\"([^\"]*)\" *\"([^\"]*)\"/;
	    ( $junk, $junk, $junk, $co ) =
      m/^[[](nil|\"[^\"]*\") *(nil|\"[^\"]*\") (nil|[(][^)]*[)]) \"([^\"]*)\"/;

	    if ( $fn || $ln ) {
		$caller = "$fn $ln";
	    }
	} else {
	    $buttonp = 1;
	}
    }

    my $msg = make_message_string($number, $date, $fn, $ln, $co, $error);
    pop_up_dialog($msg, $buttonp, $pretty_number);

    if ( $caller ) {
	pop_up_bbdb_buffer($caller);
    }
}


##############################################################################
#
# hey ho.  let's go.
#
sub main {
    init_modem();
    while (1) {
	handle_async_line(read_line());
    }
    exit (1);
}

main();