main.pm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. package eyelib::main;
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use Encode;
  8. use strict;
  9. use English;
  10. use FindBin '$Bin';
  11. use lib "/opt/Eye/scripts";
  12. use base 'Exporter';
  13. use vars qw(@EXPORT @ISA);
  14. use eyelib::config;
  15. use Socket;
  16. use IO::Select;
  17. use IO::Handle;
  18. use Crypt::CBC;
  19. use MIME::Base64;
  20. our @ISA = qw(Exporter);
  21. our @EXPORT = qw(
  22. isNotifyCreate
  23. isNotifyUpdate
  24. isNotifyDelete
  25. isNotifyNone
  26. hasNotifyFlag
  27. log_file
  28. write_to_file
  29. wrlog
  30. log_session
  31. log_warning
  32. log_info
  33. log_debug
  34. log_error
  35. log_verbose
  36. log_die
  37. in_array
  38. timestamp
  39. do_exec
  40. do_exec_ref
  41. do_exit
  42. hash_to_kv_csv
  43. sendEmail
  44. IsNotRun
  45. IsMyPID
  46. Add_PID
  47. Remove_PID
  48. IsNotLocked
  49. IsMyLock
  50. Add_Lock
  51. Remove_Lock
  52. DefHash
  53. read_file
  54. uniq
  55. strim
  56. trim
  57. hash_to_text
  58. is_integer
  59. is_float
  60. run_in_parallel
  61. translit
  62. crypt_string
  63. decrypt_string
  64. netdev_set_auth
  65. );
  66. BEGIN
  67. {
  68. #---------------------------------------------------------------------------------------------------------
  69. # Проверяет, установлен ли флаг создания
  70. sub isNotifyCreate {
  71. my ($flags) = @_;
  72. return ($flags & NOTIFY_CREATE) == NOTIFY_CREATE;
  73. }
  74. #---------------------------------------------------------------------------------------------------------
  75. # Проверяет, установлен ли флаг изменения
  76. sub isNotifyUpdate {
  77. my ($flags) = @_;
  78. return ($flags & NOTIFY_UPDATE) == NOTIFY_UPDATE;
  79. }
  80. #---------------------------------------------------------------------------------------------------------
  81. # Проверяет, установлен ли флаг удаления
  82. sub isNotifyDelete {
  83. my ($flags) = @_;
  84. return ($flags & NOTIFY_DELETE) == NOTIFY_DELETE;
  85. }
  86. #---------------------------------------------------------------------------------------------------------
  87. # Проверяет, отключены ли все уведомления
  88. sub isNotifyNone {
  89. my ($flags) = @_;
  90. return $flags == NOTIFY_NONE;
  91. }
  92. #---------------------------------------------------------------------------------------------------------
  93. # Проверяет, установлен ли конкретный флаг
  94. sub hasNotifyFlag {
  95. my ($flags, $flagToCheck) = @_;
  96. return ($flags & $flagToCheck) == $flagToCheck;
  97. }
  98. #---------------------------------------------------------------------------------------------------------
  99. sub log_file {
  100. return if (!$_[0]);
  101. return if (!$_[1]);
  102. return if (!$_[2]);
  103. open (LG,">>$_[0]") || die("Error open log file $_[0]!!! die...");
  104. my ($sec,$min,$hour,$mday,$mon,$year) = (localtime())[0,1,2,3,4,5];
  105. $mon += 1; $year += 1900;
  106. my @msg = split("\n",$_[2]);
  107. foreach my $row (@msg) {
  108. next if (!$row);
  109. printf LG "%04d%02d%02d-%02d%02d%02d %s [%d] %s\n",$year,$mon,$mday,$hour,$min,$sec,$_[1],$$,$row;
  110. }
  111. close (LG);
  112. if ($< ==0) {
  113. my $uid = getpwnam $log_owner_user;
  114. my $gid = getgrnam $log_owner_user;
  115. if (!$gid) { $gid=getgrnam "root"; }
  116. if (!$uid) { $uid=getpwnam "root"; }
  117. chown $uid, $gid, $_[0];
  118. chmod oct("0660"), $_[0];
  119. }
  120. }
  121. #---------------------------------------------------------------------------------------------------------
  122. sub write_to_file {
  123. return if (!$_[0]);
  124. return if (!$_[1]);
  125. my $f_name = shift;
  126. my $cmd = shift;
  127. my $append = shift;
  128. if ($append) {
  129. open (LG,">>$f_name") || die("Error open file $f_name!!! die...");
  130. } else {
  131. open (LG,">$f_name") || die("Error open file $f_name!!! die...");
  132. }
  133. binmode(LG,':utf8');
  134. if (ref($cmd) eq 'ARRAY') {
  135. foreach my $row (@$cmd) {
  136. next if (!$row);
  137. print LG $row."\n";
  138. }
  139. } else {
  140. my @msg = split("\n",$cmd);
  141. foreach my $row (@msg) {
  142. next if (!$row);
  143. print LG $row."\n";
  144. }
  145. }
  146. close (LG);
  147. }
  148. #---------------------------------------------------------------------------------------------------------
  149. sub wrlog {
  150. my $level = shift;
  151. my $string = shift;
  152. my $PRN_LEVEL = 'INFO:';
  153. if ($level == $W_INFO) { log_info($string); }
  154. if ($level == $W_ERROR) { $PRN_LEVEL = 'ERROR:'; log_error($string); }
  155. if ($level == $W_DEBUG) { $PRN_LEVEL = 'DEBUG'; log_debug($string); }
  156. my @msg = split("\n",$string);
  157. foreach my $row (@msg) {
  158. next if (!$row);
  159. print $PRN_LEVEL.' '.$row."\n";
  160. }
  161. }
  162. #---------------------------------------------------------------------------------------------------------
  163. sub log_session { log_file($LOG_COMMON,"SESSION:",$_[0]) if ($log_enable); }
  164. #---------------------------------------------------------------------------------------------------------
  165. sub log_info { log_file($LOG_COMMON,"INFO:",$_[0]) if ($log_enable); }
  166. #---------------------------------------------------------------------------------------------------------
  167. sub log_verbose { log_file($LOG_COMMON,"VERBOSE:",$_[0]) if ($log_enable); }
  168. #---------------------------------------------------------------------------------------------------------
  169. sub log_warning { log_file($LOG_COMMON,"WARN:",$_[0]) if ($log_enable); }
  170. #---------------------------------------------------------------------------------------------------------
  171. sub log_debug { log_file($LOG_DEBUG,"DEBUG:",$_[0]) if $debug; }
  172. #---------------------------------------------------------------------------------------------------------
  173. sub log_error { log_file($LOG_ERR,"ERROR:",$_[0]) if ($log_enable); }
  174. #---------------------------------------------------------------------------------------------------------
  175. sub log_die {
  176. wrlog($W_ERROR,$_[0]);
  177. my $worktime = time()-$BASETIME;
  178. log_info("Script work $worktime sec.");
  179. sendEmail("$HOSTNAME - $MY_NAME die! ","Process: $MY_NAME aborted with error:\n$_[0]");
  180. die ($_[0]);
  181. }
  182. #---------------------------------------------------------------------------------------------------------
  183. sub timestamp {
  184. my $worktime = time()-$BASETIME;
  185. #print "TimeStamp: $worktime sec.\n";
  186. log_info("TimeStamp: $worktime sec.");
  187. }
  188. #---------------------------------------------------------------------------------------------------------
  189. sub in_array {
  190. my $arr = shift;
  191. my @tmp = ();
  192. if (ref($arr)=~'ARRAY') { @tmp = @{$arr}; } else { push(@tmp,$arr); }
  193. my $value = shift;
  194. my %num = map { $_, 1 } @tmp;
  195. return $num{$value} || 0;
  196. }
  197. #---------------------------------------------------------------------------------------------------------.
  198. sub hash_to_kv_csv {
  199. my ($hash_ref, $delimiter) = @_;
  200. $delimiter ||= ',';
  201. return '' unless $hash_ref && %$hash_ref;
  202. # Экранируем специальные символы
  203. my $escape = sub {
  204. my $value = shift;
  205. return '' unless defined $value;
  206. # Если значение содержит кавычки или запятые - заключаем в кавычки
  207. if ($value =~ /["$delimiter]/) {
  208. $value =~ s/"/""/g;
  209. return '"' . $value . '"';
  210. }
  211. return $value;
  212. };
  213. # Формируем пары ключ=>значение
  214. my @pairs;
  215. while (my ($key, $value) = each %$hash_ref) {
  216. push @pairs, $escape->($key) . '=>' . $escape->($value);
  217. }
  218. return join($delimiter, sort @pairs);
  219. }
  220. #---------------------------------------------------------------------------------------------------------.
  221. sub do_exec_ref {
  222. my $ret = `$_[0] 2>&1`;
  223. my $res = $?;
  224. my %result;
  225. chomp($ret);
  226. $result{output}=$ret;
  227. $result{status}=$res;
  228. log_debug("Run: $_[0] Output:\n$ret\nResult code: $res");
  229. if ($res eq "0") { log_info("Run: $_[0] - $ret"); } else { log_error("Run: $_[0] - $ret"); }
  230. return %result;
  231. }
  232. #---------------------------------------------------------------------------------------------------------
  233. sub do_exec {
  234. my $ret = `$_[0]`;
  235. my $res = $?;
  236. log_debug("Run: $_[0] Output:\n$ret\nResult code: $res");
  237. if ($res eq "0") {
  238. log_info("Run: $_[0] - $ret");
  239. } else {
  240. $ret = "Error";
  241. log_error("Run: $_[0] - $ret");
  242. }
  243. return $ret;
  244. }
  245. #---------------------------------------------------------------------------------------------------------
  246. sub do_exit {
  247. my $worktime = time()-$BASETIME;
  248. my $code;
  249. if ($_[0]) { $code = $_[0]; } else { $code = 0; }
  250. log_info("Script work $worktime sec. Exit code: $code");
  251. exit $code;
  252. }
  253. #---------------------------------------------------------------------------------------------------------
  254. sub encode_mime_header {
  255. my ($str) = @_;
  256. return $str if $str =~ /^[[:ascii:]]*$/;
  257. my $b64 = encode_base64($str, '');
  258. $b64 =~ s/\s+$//;
  259. return "=?UTF-8?B?$b64?=";
  260. }
  261. #---------------------------------------------------------------------------------------------------------
  262. sub sendEmail {
  263. my ($subject, $msg, $use_br) = @_;
  264. return unless defined $msg && length $msg;
  265. return unless $send_email;
  266. unless (defined $sender_email && defined $admin_email) {
  267. log_error("Email addresses not defined");
  268. return;
  269. }
  270. # Санитизация (оставляет Unicode буквы/цифры)
  271. $subject =~ s/[^\p{L}\p{N}\s\-\.\,\!\?]//g;
  272. $msg =~ s/\r//g;
  273. my $html_message = <<"END_HTML";
  274. <!DOCTYPE html>
  275. <html xmlns="http://www.w3.org/1999/xhtml">
  276. <head>
  277. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  278. <title>$subject</title>
  279. </head>
  280. <body>
  281. <div>
  282. END_HTML
  283. my @lines = split(/\n/, $msg);
  284. foreach my $line (@lines) {
  285. $line = htmlspecialchars($line);
  286. $html_message .= $use_br ? "$line<br>\n" : "$line\n";
  287. }
  288. $html_message .= "</div>\n</body>\n</html>\n";
  289. # Кодируем Unicode-строку в байты UTF-8, затем в base64
  290. my $html_utf8_bytes = encode('UTF-8', $html_message);
  291. my $encoded_html = encode_base64($html_utf8_bytes);
  292. my $boundary = '----=' . time() . int(rand(1000));
  293. my $encoded_subject = encode_mime_header($subject);
  294. my $headers = <<"END_HEADERS";
  295. From: $sender_email
  296. To: $admin_email
  297. Subject: $encoded_subject
  298. MIME-Version: 1.0
  299. Content-Type: multipart/mixed; boundary="$boundary"
  300. END_HEADERS
  301. my $mime_message = <<"END_MIME";
  302. --$boundary
  303. Content-Type: text/html; charset=utf-8
  304. Content-Transfer-Encoding: base64
  305. $encoded_html
  306. --$boundary--
  307. END_MIME
  308. my $sendmail = '/usr/sbin/sendmail';
  309. unless (-x $sendmail) {
  310. log_error("Sendmail not found or not executable at $sendmail");
  311. return;
  312. }
  313. unless (open(MAIL, "|$sendmail -oi -t")) {
  314. log_error("Failed to open sendmail: $!");
  315. return;
  316. }
  317. print MAIL $headers;
  318. print MAIL $mime_message;
  319. close(MAIL) or log_error("Failed to send email: $!");
  320. log_info("Sent email from $sender_email to $admin_email with subject: $subject");
  321. log_debug("Email body:\n$msg");
  322. }
  323. #---------------------------------------------------------------------------------------------------------
  324. sub hash_to_text {
  325. my ($hash_ref, $indent, $seen) = @_;
  326. $indent ||= 0;
  327. $seen ||= {};
  328. return 'undef' unless defined $hash_ref;
  329. if (ref $hash_ref eq 'HASH') {
  330. # Защита от циклических ссылок
  331. my $addr = refaddr($hash_ref);
  332. if ($seen->{$addr}) {
  333. return '';
  334. }
  335. $seen->{$addr} = 1;
  336. my $spaces = ' ' x $indent;
  337. my @lines;
  338. for my $key (sort keys %$hash_ref) {
  339. my $value = $hash_ref->{$key};
  340. my $formatted_key = $key =~ /^[a-zA-Z_]\w*$/ ? $key : "'$key'";
  341. my $formatted_value;
  342. if (ref $value eq 'HASH') {
  343. $formatted_value = ":\n" . hash_to_text($value, $indent + 1, $seen) . "\n$spaces";
  344. }
  345. elsif (ref $value eq 'ARRAY') {
  346. $formatted_value = array_to_text($value, $indent + 1, $seen);
  347. }
  348. elsif (ref $value) {
  349. $formatted_value = '[' . ref($value) . ']';
  350. }
  351. elsif (!defined $value) {
  352. $formatted_value = '';
  353. }
  354. else {
  355. $formatted_value = "'$value'";
  356. }
  357. push @lines, "$spaces $formatted_key => $formatted_value" if ($formatted_value);
  358. }
  359. return join(",\n", @lines) || "$spaces # empty";
  360. }
  361. else {
  362. return "'$hash_ref'";
  363. }
  364. }
  365. #---------------------------------------------------------------------------------------------------------
  366. sub array_to_text {
  367. my ($array_ref, $indent, $seen) = @_;
  368. $indent ||= 0;
  369. $seen ||= {};
  370. return '[]' unless @$array_ref;
  371. my $spaces = ' ' x $indent;
  372. my @lines;
  373. foreach my $item (@$array_ref) {
  374. my $formatted_item;
  375. if (ref $item eq 'HASH') {
  376. $formatted_item = ":\n" . hash_to_text($item, $indent + 1, $seen) . "\n$spaces";
  377. }
  378. elsif (ref $item eq 'ARRAY') {
  379. $formatted_item = array_to_text($item, $indent + 1, $seen);
  380. }
  381. elsif (ref $item) {
  382. $formatted_item = '[' . ref($item) . ']';
  383. }
  384. elsif (!defined $item) {
  385. $formatted_item = '';
  386. }
  387. else {
  388. $formatted_item = "'$item'";
  389. }
  390. push @lines, "$spaces $formatted_item" if ($formatted_item);
  391. }
  392. return "[\n" . join(",\n", @lines) . "\n$spaces]";
  393. }
  394. #---------------------------------------------------------------------------------------------------------
  395. # Вспомогательная функция для получения адреса ссылки
  396. sub refaddr {
  397. my $ref = shift;
  398. return "$ref" =~ /\(0x([0-9a-f]+)\)$/ ? "0x$1" : "$ref";
  399. }
  400. #---------------------------------------------------------------------------------------------------------
  401. ### Check few run script
  402. sub IsNotRun {
  403. my $pname = shift;
  404. my $lockfile = $pname.".pid";
  405. # if pid file not exists - OK
  406. log_debug("Check what pid file $lockfile exists.");
  407. if (! -e $lockfile) { log_debug("pid file not found. Continue."); return 1; }
  408. open (FF,"<$lockfile") or log_die("can't open file $lockfile: $!");
  409. my $lockid = <FF>;
  410. close(FF);
  411. chomp($lockid);
  412. # If the process ID belongs to the current program - OK
  413. if ($lockid eq $$) { log_debug("pid file found, but owner is this process. Continue. "); return 1; }
  414. # if owner of this process ID not exists - OK
  415. my $process_count = `ps -p $lockid | grep \'$lockid\' | wc -l`;
  416. chomp($process_count);
  417. log_debug("Process count with id $lockid is $process_count");
  418. if ($process_count==0) { log_debug("pid file found, but owner process not found. Remove lock file and continue. "); unlink $lockfile; return 1; }
  419. log_debug("Another proceess with name $MY_NAME pid: $lockid already worked. ");
  420. return 0;
  421. }
  422. #---------------------------------------------------------------------------------------------------------
  423. sub IsMyPID {
  424. my $pname = shift;
  425. my $lockfile = $pname.".pid";
  426. log_debug("Check what pid file $lockfile exists.");
  427. if (! -e $lockfile) { log_debug("pid file not found. Continue."); return 1; }
  428. open (FF,"<$lockfile") or log_die "can't open file $lockfile: $!";
  429. my $lockid = <FF>;
  430. close(FF);
  431. chomp($lockid);
  432. if ($lockid eq $$) { log_debug("pid file is my. continue."); return 1; }
  433. log_debug("Another proceess with name $MY_NAME pid: $lockid already worked. ");
  434. return 0;
  435. }
  436. #---------------------------------------------------------------------------------------------------------
  437. sub Add_PID {
  438. my $pname = shift;
  439. my $lockfile = $pname.".pid";
  440. log_debug("Try create lock file $lockfile");
  441. open (FF,">$lockfile") or log_die "can't open file $lockfile: $!";
  442. flock(FF,2) or log_die "can't flock $lockfile: $!";
  443. print FF $$;
  444. close(FF);
  445. log_debug("Ok.");
  446. return 1;
  447. }
  448. #---------------------------------------------------------------------------------------------------------
  449. sub Remove_PID {
  450. my $pname = shift;
  451. my $lockfile = $pname.".pid";
  452. log_debug("Check what pid file $lockfile exists.");
  453. if (! -e $lockfile) { log_debug("pid file not exists. Continue."); return 1; }
  454. unlink $lockfile or return 0;
  455. log_debug("pid file $lockfile removed.");
  456. return 1;
  457. }
  458. #---------------------------------------------------------------------------------------------------------
  459. sub IsNotLocked {
  460. my $lockfile = $_[0] . ".lock";
  461. log_debug("Check what lock file $lockfile exists.");
  462. if (! -e $lockfile) { log_debug("lock file not found. Continue."); return 1; }
  463. open (FF,"<$lockfile") or log_die "can't open file $lockfile: $!";
  464. my $lockid = <FF>;
  465. close(FF);
  466. chomp($lockid);
  467. if ($lockid eq $$) { log_debug("lock file found, but it is owner is this process. Continue. "); return 1; }
  468. my $process_count = `ps -p $lockid | grep \'$lockid\' | wc -l`;
  469. if ($process_count lt 1) { log_debug("lock file found, but owner process not found. Remove lock file and continue. "); unlink $lockfile; return 1; }
  470. log_debug("Another proceess with pid: $lockid already use $_[0]");
  471. return 0;
  472. }
  473. #---------------------------------------------------------------------------------------------------------
  474. sub IsMyLock {
  475. my $lockfile = $_[0] . ".lock";
  476. log_debug("Check what lock file $lockfile exists.");
  477. if (! -e $lockfile) { log_debug("lock file not found. Continue."); return 0; }
  478. open (FF,"<$lockfile") or log_die "can't open file $lockfile: $!";
  479. my $lockid = <FF>;
  480. close(FF);
  481. chomp($lockid);
  482. if ($lockid eq $$) { log_debug("lock file found, but it is owner is this process. Continue. "); return 1; }
  483. log_debug("file $_[0] used by process with pid: $lockid");
  484. return 0;
  485. }
  486. #---------------------------------------------------------------------------------------------------------
  487. sub Add_Lock {
  488. if (!IsNotLocked($_[0])) { return 0; }
  489. my $lockfile = $_[0] . ".lock";
  490. open (FF,">$lockfile") or log_die "can't open file $lockfile: $!";
  491. flock(FF,2) or log_die "can't flock $lockfile: $!";
  492. print FF $$;
  493. close(FF);
  494. log_debug("Create lock file for $_[0]");
  495. return 1;
  496. }
  497. #---------------------------------------------------------------------------------------------------------
  498. sub Remove_Lock {
  499. if (!IsNotLocked($_[0])) { return 0; }
  500. my $lockfile = $_[0] . ".lock";
  501. if (! -e $lockfile) { return 1; }
  502. unlink $lockfile or return 0;
  503. log_debug("Lock file for $_[0] removed");
  504. return 1;
  505. }
  506. #---------------------------------------------------------------------------------------------------------
  507. sub DefHash {
  508. my $hash=$_[0];
  509. my $num_list = $_[1];
  510. my %num_keys;
  511. if ($num_list) {
  512. my @ret_num = split(' ',$num_list);
  513. %num_keys = map { $_, 1 } @ret_num;
  514. }
  515. foreach my $key (keys %$hash) {
  516. my $null_value = "";
  517. $null_value = 0 if (defined $num_keys{$key});
  518. $hash->{$key}=$null_value if (!defined($hash->{$key}));
  519. }
  520. return $hash;
  521. }
  522. #---------------------------------------------------------------------------------------------------------
  523. sub read_file {
  524. my $filename = shift;
  525. return if (!$filename);
  526. return if (!-e $filename);
  527. open (FF,"<$filename") or die "unable to open file $filename!" ;
  528. my @tmp=<FF>;
  529. close(FF);
  530. chomp(@tmp);
  531. return @tmp;
  532. }
  533. #---------------------------------------------------------------------------------------------------------
  534. sub uniq (\@) {
  535. my @tmp = @{(shift)};
  536. if (scalar(@tmp) eq 0) { return @tmp; }
  537. chomp(@tmp);
  538. my %newlist = map { $_, 1 } @tmp;
  539. return keys %newlist;
  540. }
  541. #---------------------------------------------------------------------------------------------------------
  542. sub strim {
  543. my $str=shift;
  544. return if (!$str);
  545. #$str =~ s/.*[^[:print:]]+//g;
  546. #$str =~ s/[^[:print:]]+//g;
  547. #$str =~ s/[^(a-z|A-Z|0-9|\:|\-|\s|\.)]//g;
  548. #$str =~ s/[:^print:]//g;
  549. $str =~ s/[^[:ascii:]]//g;
  550. $str =~ s/^\s+//g;
  551. $str =~ s/\s+$//g;
  552. return $str;
  553. }
  554. #---------------------------------------------------------------------------------------------------------
  555. sub trim {
  556. my $str=shift;
  557. return if (!$str);
  558. $str =~ s/\n/ /g;
  559. $str =~ s/^\s+//g;
  560. $str =~ s/\s+$//g;
  561. return $str;
  562. }
  563. #---------------------------------------------------------------------------------------------------------
  564. sub is_integer {
  565. defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
  566. }
  567. #---------------------------------------------------------------------------------------------------------
  568. sub is_float {
  569. defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
  570. }
  571. #---------------------------------------------------------------------------------------------------------
  572. sub run_in_parallel(\@) {
  573. my @commands = @{(shift)};
  574. my @result = ();
  575. return @result if (!@commands or !scalar(@commands));
  576. my $count = scalar(@commands);
  577. my $start = 0;
  578. while ($start<=$count-1) {
  579. my @run_list=();
  580. my $select = IO::Select->new();
  581. my $stop = $start + $parallel_process_count;
  582. $stop=$count-1 if ($stop >=$count);
  583. for (my $index = $start; $index <=$stop; $index++) {
  584. next if (!$commands[$index]);
  585. my $cmd=$commands[$index];
  586. log_info("Starting ".$cmd);
  587. my ($hchild, $hparent, $childid);
  588. socketpair($hchild, $hparent, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair: $!";
  589. $childid = fork;
  590. die "cannot fork" if($childid == -1);
  591. # redirect child Input|Output
  592. unless($childid) {
  593. open STDIN, "<&", $hparent;
  594. open STDOUT, ">&", $hparent;
  595. open STDERR, ">&", $hparent;
  596. close $hparent;
  597. close $hchild;
  598. $select->remove($_) and close $_ for($select->handles);
  599. exec "/bin/nice -n 15 ".$cmd;
  600. }
  601. close $hparent;
  602. $select->add($hchild);
  603. }
  604. while (my @ready = $select->can_read) {
  605. next if (!@ready or !scalar(@ready));
  606. for my $read(@ready) {
  607. if($read->eof || $read->error) {
  608. # child exit
  609. $select->remove($read);
  610. close $read;
  611. next;
  612. }
  613. if(defined(my $str = <$read>)) {
  614. log_info("Read:".$str);
  615. push(@result,$str);
  616. }
  617. }
  618. }
  619. $start = $stop+1;
  620. }
  621. return (@result);
  622. }
  623. #---------------------------------------------------------------------------------
  624. sub translit {
  625. my $textline=shift;
  626. return if (!$textline);
  627. $textline =~ s/А/A/g; $textline =~ s/а/a/g;
  628. $textline =~ s/Б/B/g; $textline =~ s/б/b/g;
  629. $textline =~ s/В/V/g; $textline =~ s/в/v/g;
  630. $textline =~ s/Г/G/g; $textline =~ s/г/g/g;
  631. $textline =~ s/Д/D/g; $textline =~ s/д/d/g;
  632. $textline =~ s/Е/E/g; $textline =~ s/е/e/g;
  633. $textline =~ s/Ё/E/g; $textline =~ s/ё/e/g;
  634. $textline =~ s/Ж/Zh/g; $textline =~ s/ж/zh/g;
  635. $textline =~ s/З/Z/g; $textline =~ s/з/z/g;
  636. $textline =~ s/И/I/g; $textline =~ s/и/i/g;
  637. $textline =~ s/Й/I/g; $textline =~ s/й/i/g;
  638. $textline =~ s/К/K/g; $textline =~ s/к/k/g;
  639. $textline =~ s/Л/L/g; $textline =~ s/л/l/g;
  640. $textline =~ s/М/M/g; $textline =~ s/м/m/g;
  641. $textline =~ s/Н/N/g; $textline =~ s/н/n/g;
  642. $textline =~ s/О/O/g; $textline =~ s/о/o/g;
  643. $textline =~ s/П/P/g; $textline =~ s/п/p/g;
  644. $textline =~ s/Р/R/g; $textline =~ s/р/r/g;
  645. $textline =~ s/ТС/T-S/g; $textline =~ s/Тс/T-s/g; $textline =~ s/тс/t-s/g;
  646. $textline =~ s/С/S/g; $textline =~ s/с/s/g;
  647. $textline =~ s/Т/T/g; $textline =~ s/т/t/g;
  648. $textline =~ s/У/U/g; $textline =~ s/у/u/g;
  649. $textline =~ s/Ф/F/g; $textline =~ s/ф/f/g;
  650. $textline =~ s/Х/Kh/g; $textline =~ s/х/kh/g;
  651. $textline =~ s/Ц/Ts/g; $textline =~ s/ц/ts/g;
  652. $textline =~ s/Ч/Ch/g; $textline =~ s/ч/ch/g;
  653. $textline =~ s/Ш/Sh/g; $textline =~ s/ш/sh/g;
  654. $textline =~ s/Щ/Shch/g; $textline =~ s/щ/shch/g;
  655. #$textline =~ s/Ь/'/g; $textline =~ s/ь/'/g;
  656. #$textline =~ s/Ъ/''/g; $textline =~ s/ъ/''/g;
  657. $textline =~ s/Ь//g; $textline =~ s/ь//g;
  658. $textline =~ s/Ъ//g; $textline =~ s/ъ//g;
  659. $textline =~ s/Ы/Y/g; $textline =~ s/ы/y/g;
  660. $textline =~ s/Э/E/g; $textline =~ s/э/e/g;
  661. $textline =~ s/Ю/Yu/g; $textline =~ s/ю/yu/g;
  662. $textline =~ s/Я/Ya/g; $textline =~ s/я/ya/g;
  663. return $textline;
  664. }
  665. #---------------------------------------------------------------------------------
  666. sub netdev_set_auth {
  667. my $device = shift;
  668. $device->{login}=$config_ref{router_login} if (!$device->{login});
  669. $device->{password}=$config_ref{router_password} if (!$device->{password});
  670. $device->{password}=decrypt_string($device->{password});
  671. $device->{enable_password}='';
  672. #$device->{enable_password}=$device->{passowrd};
  673. $device->{proto} = 'ssh';
  674. $device->{proto} = 'telnet' if ($device->{protocol} eq '1');
  675. #patch for ssh
  676. if ($device->{proto} eq 'ssh' and exists $switch_auth{$device->{vendor_id}}{proto}) {
  677. #set specified ssh type
  678. if ($switch_auth{$device->{vendor_id}}{proto} =~/ssh/i) {
  679. $device->{proto} = $switch_auth{$device->{vendor_id}}{proto};
  680. }
  681. }
  682. $device->{port} = $device->{control_port} if ($device->{control_port});
  683. $device->{prompt} = qr/[\$#>]\s?$/;
  684. if (exists $switch_auth{$device->{vendor_id}}) {
  685. $device->{prompt} = $switch_auth{$device->{vendor_id}}{prompt} if ($switch_auth{$device->{vendor_id}}{prompt});
  686. }
  687. return $device;
  688. }
  689. #---------------------------------------------------------------------------------
  690. sub decrypt_string {
  691. my $crypted_string = shift;
  692. return if (!$crypted_string);
  693. my $cipher_handle = Crypt::CBC->new(
  694. {
  695. 'key' => $config_ref{encryption_key},
  696. 'cipher' => 'Cipher::AES',
  697. 'iv' => $config_ref{encryption_iv},
  698. 'literal_key' => 1,
  699. 'header' => 'none',
  700. keysize => 128 / 8
  701. }
  702. );
  703. my $result = $cipher_handle->decrypt(decode_base64($crypted_string));
  704. return $result;
  705. }
  706. #---------------------------------------------------------------------------------
  707. sub crypt_string {
  708. my $simple_string = shift;
  709. return if (!$simple_string);
  710. my $cipher_handle = Crypt::CBC->new(
  711. {
  712. 'key' => $config_ref{encryption_key},
  713. 'cipher' => 'Cipher::AES',
  714. 'iv' => $config_ref{encryption_iv},
  715. 'literal_key' => 1,
  716. 'header' => 'none',
  717. keysize => 128 / 8
  718. }
  719. );
  720. my $result = encode_base64($cipher_handle->encrypt($simple_string));
  721. return $result;
  722. }
  723. #---------------------------------------------------------------------------------------------------------
  724. # Helper function for HTML escaping
  725. sub htmlspecialchars {
  726. my ($text) = @_;
  727. return '' unless defined $text;
  728. $text =~ s/&/&amp;/g;
  729. $text =~ s/</&lt;/g;
  730. $text =~ s/>/&gt;/g;
  731. $text =~ s/"/&quot;/g;
  732. $text =~ s/'/&#039;/g;
  733. return $text;
  734. }
  735. #---------------------------------------------------------------------------------
  736. #log_file($LOG_COMMON,"INFO:","----------------------------------------------------------------------------------------");
  737. #log_file($LOG_COMMON,"INFO:","Run script $0. Pid: $$ Pid file: $SPID.pid");
  738. #log_file($LOG_COMMON,"INFO:","User uid: $< Effective uid: $>");
  739. #log_file($LOG_COMMON,"INFO:","Status:");
  740. #log_file($LOG_COMMON,"INFO:","Logging enabled: $log_enable");
  741. #log_file($LOG_COMMON,"INFO:","Logging debug: $debug");
  742. 1;
  743. }