main.pm 28 KB

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