persistence.pl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use Kamailio qw ( log );
  2. use Kamailio::Constants;
  3. use IPC::Shareable;
  4. my $foo = 0;
  5. my %lastcalltimes;
  6. my %lastcallids;
  7. # This function shows that normal persistent variables are _not_ valid between multiple instances of the Kamailio.
  8. # With the default setup of 4 children, the value logged is only incremented every 4th time.
  9. sub limited {
  10. use vars qw ($foo);
  11. log(L_INFO, "My persistent variable is $foo\n");
  12. $foo++;
  13. return 1;
  14. }
  15. # Only one call per hour to each recipient
  16. # By using the IPC::Shareable perl module, real persistence between multiple instances can be achieved
  17. # Consider using the locking mechanisms available in IPC::Shareable when using in real world environments.
  18. sub onceperhour {
  19. my $m = shift;
  20. tie %lastcalltimes, IPC::Shareable, { key => "lstt", create => 1, destroy => 1 } or die "Error with IPC::Shareable";
  21. tie %lastcallids, IPC::Shareable, { key => "lsti", create => 1, destroy => 1 } or die "Error with IPC::Shareable";
  22. if ($m->getMethod() eq "INVITE") {
  23. my $dst = $m->getRURI();
  24. my $currentid = $m->getHeader("Call-ID");
  25. log(L_INFO, "invite to $dst");
  26. my $lasttime = %lastcalltimes->{$dst};
  27. log(L_INFO, "lasttime is $lasttime");
  28. if ($lasttime) { # Value set.
  29. log(L_INFO, "I was already called at $lasttime");
  30. if ((time() - $lasttime) < 3600) {
  31. if ($currentid eq %lastcallids->{$dst}) {
  32. log(L_INFO, "I know this call already. Doing nothing.");
  33. } else {
  34. log(L_INFO, "replying, return 1");
  35. $m->sl_send_reply("488", "You already called this hour");
  36. return 1;
  37. }
  38. }
  39. }
  40. %lastcalltimes->{$dst} = time();
  41. %lastcallids->{$dst} = $currentid;
  42. }
  43. return -1;
  44. }