diff options
Diffstat (limited to 'mod')
-rw-r--r-- | mod/bridge-port-to.rsc (renamed from mod/bridge-port-to) | 25 | ||||
-rw-r--r-- | mod/bridge-port-vlan.rsc (renamed from mod/bridge-port-vlan) | 28 | ||||
-rw-r--r-- | mod/inspectvar.rsc (renamed from mod/inspectvar) | 9 | ||||
-rw-r--r-- | mod/ipcalc.rsc (renamed from mod/ipcalc) | 20 | ||||
-rw-r--r-- | mod/notification-email.rsc | 240 | ||||
-rw-r--r-- | mod/notification-matrix | 163 | ||||
-rw-r--r-- | mod/notification-matrix.rsc | 266 | ||||
-rw-r--r-- | mod/notification-ntfy.rsc | 148 | ||||
-rw-r--r-- | mod/notification-telegram | 170 | ||||
-rw-r--r-- | mod/notification-telegram.rsc | 196 | ||||
-rw-r--r-- | mod/scriptrunonce | 46 | ||||
-rw-r--r-- | mod/scriptrunonce.rsc | 52 | ||||
-rw-r--r-- | mod/ssh-keys-import.rsc | 114 |
13 files changed, 1066 insertions, 411 deletions
diff --git a/mod/bridge-port-to b/mod/bridge-port-to.rsc index 3f62e6f..000532a 100644 --- a/mod/bridge-port-to +++ b/mod/bridge-port-to.rsc @@ -1,8 +1,10 @@ #!rsc by RouterOS # RouterOS script: mod/bridge-port-to -# Copyright (c) 2013-2022 Christian Hesse <mail@eworm.de> +# Copyright (c) 2013-2024 Christian Hesse <mail@eworm.de> # https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md # +# requires RouterOS, version=7.13 +# # reset bridge ports to default bridge # https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/bridge-port-to.md @@ -12,7 +14,7 @@ :local BridgePortTo [ :tostr $1 ]; :global IfThenElse; - :global LogPrintExit2; + :global LogPrint; :global ParseKeyValueStore; :local InterfaceReEnable ({}); @@ -24,21 +26,22 @@ :if ($BridgeDefault = "dhcp-client") do={ :if ([ :len $DHCPClient ] != 1) do={ - $LogPrintExit2 warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \ - " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!") true; + $LogPrint warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \ + " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!"); + :return false; } :local DHCPClientDisabled [ /ip/dhcp-client/get $DHCPClient disabled ]; :if ($BridgePortVal->"disabled" = false || $DHCPClientDisabled = true) do={ - $LogPrintExit2 info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client.") false; + $LogPrint info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client."); /interface/bridge/port/disable $BridgePort; :delay 200ms; /ip/dhcp-client/enable $DHCPClient; } } else={ :if ($BridgePortVal->"disabled" = true || $BridgeDefault != $BridgePortVal->"bridge") do={ - $LogPrintExit2 info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $BridgePortTo . \ - " bridge " . $BridgeDefault . ", disabling dhcp client.") false; + $LogPrint info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $BridgePortTo . \ + " bridge " . $BridgeDefault . ", disabling dhcp client."); :if ([ :len $DHCPClient ] = 1) do={ /ip/dhcp-client/disable $DHCPClient; :delay 200ms; @@ -50,16 +53,16 @@ } /interface/bridge/port/set disabled=no bridge=$BridgeDefault $BridgePort; } else={ - $LogPrintExit2 debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $BridgePortTo . \ - " bridge " . $BridgeDefault . ".") false; + $LogPrint debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $BridgePortTo . \ + " bridge " . $BridgeDefault . "."); } } } } } :if ([ :len $InterfaceReEnable ] > 0) do={ - :delay 2s; - $LogPrintExit2 info $0 ("Re-enabling interfaces...") false; + :delay 5s; + $LogPrint info $0 ("Re-enabling interfaces..."); /interface/ethernet/enable $InterfaceReEnable; } } diff --git a/mod/bridge-port-vlan b/mod/bridge-port-vlan.rsc index 9a6e08a..760e8a6 100644 --- a/mod/bridge-port-vlan +++ b/mod/bridge-port-vlan.rsc @@ -1,8 +1,10 @@ #!rsc by RouterOS # RouterOS script: mod/bridge-port-vlan -# Copyright (c) 2013-2022 Christian Hesse <mail@eworm.de> +# Copyright (c) 2013-2024 Christian Hesse <mail@eworm.de> # https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md # +# requires RouterOS, version=7.13 +# # manage VLANs on bridge ports # https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/bridge-port-vlan.md @@ -12,7 +14,7 @@ :local ConfigTo [ :tostr $1 ]; :global IfThenElse; - :global LogPrintExit2; + :global LogPrint; :global ParseKeyValueStore; :local InterfaceReEnable ({}); @@ -24,13 +26,14 @@ :if ($Vlan = "dhcp-client") do={ :if ([ :len $DHCPClient ] != 1) do={ - $LogPrintExit2 warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \ - " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!") true; + $LogPrint warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \ + " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!"); + :return false; } :local DHCPClientDisabled [ /ip/dhcp-client/get $DHCPClient disabled ]; :if ($BridgePortVal->"disabled" = false || $DHCPClientDisabled = true) do={ - $LogPrintExit2 info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client.") false; + $LogPrint info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client."); /interface/bridge/port/disable $BridgePort; :delay 200ms; /ip/dhcp-client/enable $DHCPClient; @@ -41,12 +44,13 @@ :do { :set $Vlan ([ /interface/bridge/vlan/get [ find where comment=$Vlan ] vlan-ids ]->0); } on-error={ - $LogPrintExit2 warning $0 ("Could not find VLAN '" . $Vlan . "' for interface " . $BridgePortVal->"interface" . "!") true; + $LogPrint warning $0 ("Could not find VLAN '" . $Vlan . "' for interface " . $BridgePortVal->"interface" . "!"); + :return false; } } :if ($BridgePortVal->"disabled" = true || $Vlan != $BridgePortVal->"pvid") do={ - $LogPrintExit2 info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $ConfigTo . \ - " vlan " . $Vlan . [ $IfThenElse ($Vlan != $VlanName) (" (" . $VlanName . ")") ] . ", disabling dhcp client.") false; + $LogPrint info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $ConfigTo . \ + " vlan " . $Vlan . [ $IfThenElse ($Vlan != $VlanName) (" (" . $VlanName . ")") ] . ", disabling dhcp client."); :if ([ :len $DHCPClient ] = 1) do={ /ip/dhcp-client/disable $DHCPClient; :delay 200ms; @@ -58,16 +62,16 @@ } /interface/bridge/port/set disabled=no pvid=$Vlan $BridgePort; } else={ - $LogPrintExit2 debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $ConfigTo . \ - " vlan " . $Vlan . ".") false; + $LogPrint debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $ConfigTo . \ + " vlan " . $Vlan . "."); } } } } } :if ([ :len $InterfaceReEnable ] > 0) do={ - :delay 2s; - $LogPrintExit2 info $0 ("Re-enabling interfaces...") false; + :delay 5s; + $LogPrint info $0 ("Re-enabling interfaces..."); /interface/ethernet/enable $InterfaceReEnable; } } diff --git a/mod/inspectvar b/mod/inspectvar.rsc index 2629b6e..5adca0a 100644 --- a/mod/inspectvar +++ b/mod/inspectvar.rsc @@ -1,7 +1,12 @@ #!rsc by RouterOS # RouterOS script: mod/inspectvar -# Copyright (c) 2020-2022 Christian Hesse <mail@eworm.de> +# Copyright (c) 2020-2024 Christian Hesse <mail@eworm.de> # https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# inspect variables +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/inspectvar.md :global InspectVar; :global InspectVarReturn; @@ -36,7 +41,7 @@ :local TypeOf [ :typeof $Input ]; :local Return [ $IndentReturn "type" $TypeOf $Level ]; - + :if ($TypeOf = "array") do={ :foreach Key,Value in=$Input do={ :set $Return ($Return . "\n" . \ diff --git a/mod/ipcalc b/mod/ipcalc.rsc index 14bb1ea..128ca54 100644 --- a/mod/ipcalc +++ b/mod/ipcalc.rsc @@ -1,7 +1,12 @@ #!rsc by RouterOS # RouterOS script: mod/ipcalc -# Copyright (c) 2020-2022 Christian Hesse <mail@eworm.de> +# Copyright (c) 2020-2024 Christian Hesse <mail@eworm.de> # https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# ip address calculation +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/ipcalc.md :global IPCalc; :global IPCalcReturn; @@ -10,18 +15,19 @@ :set IPCalc do={ :local Input [ :tostr $1 ]; + :global FormatLine; :global IPCalcReturn; :global PrettyPrint; :local Values [ $IPCalcReturn $1 ]; $PrettyPrint ( \ - "Address: " . $Values->"address" . "\n" . \ - "Netmask: " . $Values->"netmask" . "\n" . \ - "Network: " . $Values->"network" . "\n" . \ - "HostMin: " . $Values->"hostmin" . "\n" . \ - "HostMax: " . $Values->"hostmax" . "\n" . \ - "Broadcast: " . $Values->"broadcast"); + [ $FormatLine "Address" ($Values->"address") ] . "\n" . \ + [ $FormatLine "Netmask" ($Values->"netmask") ] . "\n" . \ + [ $FormatLine "Network" ($Values->"network") ] . "\n" . \ + [ $FormatLine "HostMin" ($Values->"hostmin") ] . "\n" . \ + [ $FormatLine "HostMax" ($Values->"hostmax") ] . "\n" . \ + [ $FormatLine "Broadcast" ($Values->"broadcast") ]); } # calculate and return netmask, network, min host, max host and broadcast diff --git a/mod/notification-email.rsc b/mod/notification-email.rsc new file mode 100644 index 0000000..df2e81a --- /dev/null +++ b/mod/notification-email.rsc @@ -0,0 +1,240 @@ +#!rsc by RouterOS +# RouterOS script: mod/notification-email +# Copyright (c) 2013-2024 Christian Hesse <mail@eworm.de> +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# send notifications via e-mail +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-email.md + +:global EMailGenerateFrom; +:global FlushEmailQueue; +:global LogForwardFilterLogForwarding; +:global NotificationEMailSubject; +:global NotificationFunctions; +:global PurgeEMailQueue; +:global QuotedPrintable; +:global SendEMail; +:global SendEMail2; + +# generate from-property with display name +:set EMailGenerateFrom do={ + :global Identity; + + :global CleanName; + + :local From [ /tool/e-mail/get from ]; + + :if ($From ~ "<.*>\$") do={ + :return $From; + } + + :return ([ $CleanName $Identity ] . " via routeros-scripts <" . $From . ">"); +} + +# flush e-mail queue +:set FlushEmailQueue do={ + :global EmailQueue; + + :global EitherOr; + :global EMailGenerateFrom; + :global IsDNSResolving; + :global IsTimeSync; + :global LogPrint; + + :local AllDone true; + :local QueueLen [ :len $EmailQueue ]; + :local Scheduler [ /system/scheduler/find where name="_FlushEmailQueue" ]; + + :if ([ :len $Scheduler ] > 0 && [ /system/scheduler/get $Scheduler interval ] < 1m) do={ + /system/scheduler/set interval=1m comment="Doing initial checks..." $Scheduler; + } + + :if ([ /tool/e-mail/get last-status ] = "in-progress") do={ + $LogPrint debug $0 ("Sending mail is currently in progress, not flushing."); + :return false; + } + + :if ([ $IsTimeSync ] = false) do={ + $LogPrint debug $0 ("Time is not synced, not flushing."); + :return false; + } + + :local EMailSettings [ /tool/e-mail/get ]; + :if ([ :typeof [ :toip ($EMailSettings->"server") ] ] != "ip" && [ $IsDNSResolving ] = false) do={ + $LogPrint debug $0 ("Server address is a DNS name and resolving fails, not flushing."); + :return false; + } + + :if ([ :len $Scheduler ] > 0 && $QueueLen = 0) do={ + $LogPrint warning $0 ("Flushing E-Mail messages from scheduler, but queue is empty."); + } + + /system/scheduler/set interval=([ $EitherOr $QueueLen 1 ] . "m") comment="Sending..." $Scheduler; + + :foreach Id,Message in=$EmailQueue do={ + :if ([ :typeof $Message ] = "array" ) do={ + :local Attach ({}); + :while ([ /tool/e-mail/get last-status ] = "in-progress") do={ :delay 1s; } + :foreach File in=[ :toarray [ $EitherOr ($Message->"attach") "" ] ] do={ + :if ([ :len [ /file/find where name=$File ] ] = 1) do={ + :set Attach ($Attach, $File); + } else={ + $LogPrint warning $0 ("File '" . $File . "' does not exist, can not attach."); + } + } + /tool/e-mail/send from=[ $EMailGenerateFrom ] to=($Message->"to") cc=($Message->"cc") \ + subject=($Message->"subject") body=($Message->"body") file=$Attach; + :local Wait true; + :do { + :delay 1s; + :local Status [ /tool/e-mail/get last-status ]; + :if ($Status = "succeeded") do={ + :set ($EmailQueue->$Id); + :set Wait false; + :if (($Message->"remove-attach") = true) do={ + :foreach File in=$Attach do={ + /file/remove $File; + } + } + } + :if ($Status = "failed") do={ + :set AllDone false; + :set Wait false; + } + } while=($Wait = true); + } + } + + :if ($AllDone = true && $QueueLen = [ :len $EmailQueue ]) do={ + /system/scheduler/remove $Scheduler; + :set EmailQueue; + } else={ + /system/scheduler/set interval=1m comment="Waiting for retry..." $Scheduler; + } +} + +# generate filter for log-forward +:set LogForwardFilterLogForwarding do={ + :global EscapeForRegEx; + :global NotificationEMailSubject; + :global SymbolForNotification; + + :return ("^Error sending e-mail <(" . \ + [ $EscapeForRegEx [ $NotificationEMailSubject ([ $SymbolForNotification \ + "memo" ] . "Log Forwarding") ] ] . "|" . \ + [ $EscapeForRegEx [ $NotificationEMailSubject ([ $SymbolForNotification \ + "warning-sign" ] . "Log Forwarding") ] ] . ")>:"); +} + +# generate the e-mail subject +:set NotificationEMailSubject do={ + :global Identity; + :global IdentityExtra; + + :global QuotedPrintable; + + :return [ $QuotedPrintable ("[" . $IdentityExtra . $Identity . "] " . $1) ]; +} + +# send notification via e-mail - expects one array argument +:set ($NotificationFunctions->"email") do={ + :local Notification $1; + + :global EmailGeneralTo; + :global EmailGeneralToOverride; + :global EmailGeneralCc; + :global EmailGeneralCcOverride; + :global EmailQueue; + + :global EitherOr; + :global IfThenElse; + :global NotificationEMailSignature; + :global NotificationEMailSubject; + + :local To [ $EitherOr ($EmailGeneralToOverride->($Notification->"origin")) $EmailGeneralTo ]; + :local Cc [ $EitherOr ($EmailGeneralCcOverride->($Notification->"origin")) $EmailGeneralCc ]; + + :local EMailSettings [ /tool/e-mail/get ]; + :if ([ :len $To ] = 0 || ($EMailSettings->"server") = "0.0.0.0" || ($EMailSettings->"from") = "<>") do={ + :return false; + } + + :if ([ :typeof $EmailQueue ] = "nothing") do={ + :set EmailQueue ({}); + } + :local Signature [ $EitherOr [ $NotificationEMailSignature ] [ /system/note/get note ] ]; + :set ($EmailQueue->[ :len $EmailQueue ]) { + to=$To; cc=$Cc; + subject=[ $NotificationEMailSubject ($Notification->"subject") ]; + body=(($Notification->"message") . \ + [ $IfThenElse ([ :len ($Notification->"link") ] > 0) ("\n\n" . ($Notification->"link")) "" ] . \ + [ $IfThenElse ([ :len $Signature ] > 0) ("\n-- \n" . $Signature) "" ]); \ + attach=($Notification->"attach"); remove-attach=($Notification->"remove-attach") }; + :if ([ :len [ /system/scheduler/find where name="_FlushEmailQueue" ] ] = 0) do={ + /system/scheduler/add name="_FlushEmailQueue" interval=1s start-time=startup \ + comment="Queuing new mail..." on-event=(":global FlushEmailQueue; \$FlushEmailQueue;"); + } +} + +# purge the e-mail queue +:set PurgeEMailQueue do={ + :global EmailQueue; + + /system/scheduler/remove [ find where name="_FlushEmailQueue" ]; + :set EmailQueue; +} + +# convert string to quoted-printable +:global QuotedPrintable do={ + :local Input [ :tostr $1 ]; + + :global CharacterMultiply; + + :if ([ :len $Input ] = 0) do={ + :return $Input; + } + + :local Return ""; + :local Chars ( \ + "\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F\10\11\12\13\14\15\16\17\18\19\1A\1B\1C\1D\1E\1F" . \ + [ $CharacterMultiply ("\00") 29 ] . "=\00?" . [ $CharacterMultiply ("\00") 63 ] . "\7F" . \ + "\80\81\82\83\84\85\86\87\88\89\8A\8B\8C\8D\8E\8F\90\91\92\93\94\95\96\97\98\99\9A\9B\9C\9D\9E\9F" . \ + "\A0\A1\A2\A3\A4\A5\A6\A7\A8\A9\AA\AB\AC\AD\AE\AF\B0\B1\B2\B3\B4\B5\B6\B7\B8\B9\BA\BB\BC\BD\BE\BF" . \ + "\C0\C1\C2\C3\C4\C5\C6\C7\C8\C9\CA\CB\CC\CD\CE\CF\D0\D1\D2\D3\D4\D5\D6\D7\D8\D9\DA\DB\DC\DD\DE\DF" . \ + "\E0\E1\E2\E3\E4\E5\E6\E7\E8\E9\EA\EB\EC\ED\EE\EF\F0\F1\F2\F3\F4\F5\F6\F7\F8\F9\FA\FB\FC\FD\FE\FF"); + :local Hex "0123456789ABCDEF"; + + :for I from=0 to=([ :len $Input ] - 1) do={ + :local Char [ :pick $Input $I ]; + :local Replace [ :find $Chars $Char ]; + + :if ([ :typeof $Replace ] = "num") do={ + :set Char ("=" . [ :pick $Hex ($Replace / 16)] . [ :pick $Hex ($Replace % 16) ]); + } + :set Return ($Return . $Char); + } + + :if ($Input = $Return) do={ + :return $Input; + } + + :return ("=?utf-8?Q?" . $Return . "?="); +} + +# send notification via e-mail - expects at least two string arguments +:set SendEMail do={ + :global SendEMail2; + + $SendEMail2 ({ origin=$0; subject=$1; message=$2; link=$3 }); +} + +# send notification via e-mail - expects one array argument +:set SendEMail2 do={ + :local Notification $1; + + :global NotificationFunctions; + + ($NotificationFunctions->"email") ("\$NotificationFunctions->\"email\"") $Notification; +} diff --git a/mod/notification-matrix b/mod/notification-matrix deleted file mode 100644 index c4dd27b..0000000 --- a/mod/notification-matrix +++ /dev/null @@ -1,163 +0,0 @@ -#!rsc by RouterOS -# RouterOS script: mod/notification-matrix -# Copyright (c) 2013-2022 Michael Gisbers <michael@gisbers.de> -# Christian Hesse <mail@eworm.de> -# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md - -:global FlushMatrixQueue; -:global NotificationFunctions; -:global SendMatrix; -:global SendMatrix2; - -# flush Matrix queue -:set FlushMatrixQueue do={ - :global MatrixQueue; - - :global IsFullyConnected; - :global LogPrintExit2; - - :if ([ $IsFullyConnected ] = false) do={ - $LogPrintExit2 debug $0 ("System is not fully connected, not flushing.") false; - :return false; - } - - :local AllDone true; - :local QueueLen [ :len $MatrixQueue ]; - - :if ([ :len [ /system/scheduler/find where name="FlushMatrixQueue" ] ] > 0 && $QueueLen = 0) do={ - $LogPrintExit2 warning $0 ("Flushing Matrix messages from scheduler, but queue is empty.") false; - } - - :foreach Id,Message in=$MatrixQueue do={ - :if ([ :typeof $Message ] = "array" ) do={ - :do { - /tool/fetch check-certificate=yes-without-crl output=none http-method=post \ - ("https://" . $Message->"homeserver" . "/_matrix/client/r0/rooms/" . $Message->"room" . \ - "/send/m.room.message?access_token=" . $Message->"accesstoken") \ - http-data=("{ \"msgtype\": \"m.text\", \"body\": \"" . $Message->"plain" . "\"," . \ - "\"format\": \"org.matrix.custom.html\", \"formatted_body\": \"" . \ - $Message->"formatted" . "\" }") as-value; - :set ($MatrixQueue->$Id); - } on-error={ - $LogPrintExit2 debug $0 ("Sending queued Matrix message failed.") false; - :set AllDone false; - } - } - } - - :if ($AllDone = true && $QueueLen = [ :len $MatrixQueue ]) do={ - /system/scheduler/remove [ find where name="FlushMatrixQueue" ]; - :set MatrixQueue; - } -} - -# send notification via Matrix - expects one array argument -:set ($NotificationFunctions->"matrix") do={ - :local Notification $1; - - :global Identity; - :global MatrixAccessToken; - :global MatrixAccessTokenOverride; - :global MatrixHomeServer; - :global MatrixHomeServerOverride; - :global MatrixQueue; - :global MatrixRoom; - :global MatrixRoomOverride; - - :global EitherOr; - :global LogPrintExit2; - :global SymbolForNotification; - - :local PrepareText do={ - :local Input [ :tostr $1 ]; - - :if ([ :len $Input ] = 0) do={ - :return ""; - } - - :local Return ""; - :local Chars { - "plain"={ "\\"; "\""; "\n" }; - "format"={ "\\"; "\""; "\n"; "&"; "<"; ">" }; - } - :local Subs { - "plain"={ "\\\\"; "\\\""; "\\n" }; - "format"={ "\\\\"; """; "<br/>"; "&"; "<"; ">" }; - } - - :for I from=0 to=([ :len $Input ] - 1) do={ - :local Char [ :pick $Input $I ]; - :local Replace [ :find ($Chars->$2) $Char ]; - - :if ([ :typeof $Replace ] = "num") do={ - :set Char ($Subs->$2->$Replace); - } - :set Return ($Return . $Char); - } - - :return $Return; - } - - :local AccessToken [ $EitherOr ($MatrixAccessTokenOverride->($Notification->"origin")) $MatrixAccessToken ]; - :local HomeServer [ $EitherOr ($MatrixHomeServerOverride->($Notification->"origin")) $MatrixHomeServer ]; - :local Room [ $EitherOr ($MatrixRoomOverride->($Notification->"origin")) $MatrixRoom ]; - - :if ([ :len $AccessToken ] = 0 || [ :len $HomeServer ] = 0 || [ :len $Room ] = 0) do={ - :return false; - } - - :local Plain [ $PrepareText ("## [" . $Identity . "] " . ($Notification->"subject") . "\n```\n" . \ - ($Notification->"message") . "\n```") "plain" ]; - :local Formatted ("<h2>" . [ $PrepareText ("[" . $Identity . "] " . ($Notification->"subject")) "format" ] . "</h2>" . \ - "<pre><code>" . [ $PrepareText ($Notification->"message") "format" ] . "</code></pre>"); - :if ([ :len ($Notification->"link") ] > 0) do={ - :set Plain ($Plain . "\\n" . [ $SymbolForNotification "link" ] . \ - [ $PrepareText ("[" . $Notification->"link" . "](" . $Notification->"link" . ")") "plain" ]); - :set Formatted ($Formatted . "<br/>" . [ $SymbolForNotification "link" ] . \ - "<a href=\\\"" . [ $PrepareText ($Notification->"link") "format" ] . "\\\">" . \ - [ $PrepareText ($Notification->"link") "format" ] . "</a>"); - } - - :do { - /tool/fetch check-certificate=yes-without-crl output=none http-method=post \ - ("https://" . $HomeServer . "/_matrix/client/r0/rooms/" . $Room . \ - "/send/m.room.message?access_token=" . $AccessToken) \ - http-data=("{ \"msgtype\": \"m.text\", \"body\": \"" . $Plain . "\"," . \ - "\"format\": \"org.matrix.custom.html\", \"formatted_body\": \"" . \ - $Formatted . "\" }") as-value; - } on-error={ - $LogPrintExit2 info $0 ("Failed sending Matrix notification! Queuing...") false; - - :if ([ :typeof $MatrixQueue ] = "nothing") do={ - :set MatrixQueue ({}); - } - :local Text ([ $SymbolForNotification "alarm-clock" ] . \ - "This message was queued since " . [ /system/clock/get date ] . \ - " " . [ /system/clock/get time ] . " and may be obsolete."); - :set Plain ($Plain . "\\n" . $Text); - :set Formatted ($Formatted . "<br/>" . $Text); - :set ($MatrixQueue->[ :len $MatrixQueue ]) { room=$Room; \ - accesstoken=$AccessToken; homeserver=$HomeServer; \ - plain=$Plain; formatted=$Formatted }; - :if ([ :len [ /system/scheduler/find where name="FlushMatrixQueue" ] ] = 0) do={ - /system/scheduler/add name=FlushMatrixQueue interval=1m start-time=startup \ - on-event=(":global FlushMatrixQueue; \$FlushMatrixQueue;"); - } - } -} - -# send notification via Matrix - expects at least two string arguments -:set SendMatrix do={ - :global SendMatrix2; - - $SendMatrix2 ({ subject=$1; message=$2; link=$3 }); -} - -# send notification via Matrix - expects one array argument -:set SendMatrix2 do={ - :local Notification $1; - - :global NotificationFunctions; - - ($NotificationFunctions->"matrix") ("\$NotificationFunctions->\"matrix\"") $Notification; -} diff --git a/mod/notification-matrix.rsc b/mod/notification-matrix.rsc new file mode 100644 index 0000000..196633a --- /dev/null +++ b/mod/notification-matrix.rsc @@ -0,0 +1,266 @@ +#!rsc by RouterOS +# RouterOS script: mod/notification-matrix +# Copyright (c) 2013-2024 Michael Gisbers <michael@gisbers.de> +# Christian Hesse <mail@eworm.de> +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# send notifications via Matrix +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-matrix.md + +:global FlushMatrixQueue; +:global NotificationFunctions; +:global PurgeMatrixQueue; +:global SendMatrix; +:global SendMatrix2; +:global SetupMatrixAuthenticate; +:global SetupMatrixJoinRoom; + +# flush Matrix queue +:set FlushMatrixQueue do={ + :global MatrixQueue; + + :global IsFullyConnected; + :global LogPrint; + + :if ([ $IsFullyConnected ] = false) do={ + $LogPrint debug $0 ("System is not fully connected, not flushing."); + :return false; + } + + :local AllDone true; + :local QueueLen [ :len $MatrixQueue ]; + + :if ([ :len [ /system/scheduler/find where name="_FlushMatrixQueue" ] ] > 0 && $QueueLen = 0) do={ + $LogPrint warning $0 ("Flushing Matrix messages from scheduler, but queue is empty."); + } + + :foreach Id,Message in=$MatrixQueue do={ + :if ([ :typeof $Message ] = "array" ) do={ + :do { + /tool/fetch check-certificate=yes-without-crl output=none \ + http-header-field=($Message->"headers") http-method=post \ + http-data=[ :serialize to=json { "msgtype"="m.text"; "body"=($Message->"plain"); + "format"="org.matrix.custom.html"; "formatted_body"=($Message->"formatted") } ] \ + ("https://" . $Message->"homeserver" . "/_matrix/client/r0/rooms/" . $Message->"room" . \ + "/send/m.room.message?access_token=" . $Message->"accesstoken") as-value; + :set ($MatrixQueue->$Id); + } on-error={ + $LogPrint debug $0 ("Sending queued Matrix message failed."); + :set AllDone false; + } + } + } + + :if ($AllDone = true && $QueueLen = [ :len $MatrixQueue ]) do={ + /system/scheduler/remove [ find where name="_FlushMatrixQueue" ]; + :set MatrixQueue; + } +} + +# send notification via Matrix - expects one array argument +:set ($NotificationFunctions->"matrix") do={ + :local Notification $1; + + :global Identity; + :global IdentityExtra; + :global MatrixAccessToken; + :global MatrixAccessTokenOverride; + :global MatrixHomeServer; + :global MatrixHomeServerOverride; + :global MatrixQueue; + :global MatrixRoom; + :global MatrixRoomOverride; + + :global EitherOr; + :global FetchUserAgentStr; + :global LogPrint; + :global ProtocolStrip; + :global SymbolForNotification; + + :local PrepareText do={ + :local Input [ :tostr $1 ]; + + :if ([ :len $Input ] = 0) do={ + :return ""; + } + + :local Return ""; + :local Chars { "\""; "\n"; "&"; "<"; ">" }; + :local Subs { """; "<br/>"; "&"; "<"; ">" }; + + :for I from=0 to=([ :len $Input ] - 1) do={ + :local Char [ :pick $Input $I ]; + :local Replace [ :find $Chars $Char ]; + + :if ([ :typeof $Replace ] = "num") do={ + :set Char ($Subs->$Replace); + } + :set Return ($Return . $Char); + } + + :return $Return; + } + + :local AccessToken [ $EitherOr ($MatrixAccessTokenOverride->($Notification->"origin")) $MatrixAccessToken ]; + :local HomeServer [ $EitherOr ($MatrixHomeServerOverride->($Notification->"origin")) $MatrixHomeServer ]; + :local Room [ $EitherOr ($MatrixRoomOverride->($Notification->"origin")) $MatrixRoom ]; + + :if ([ :len $AccessToken ] = 0 || [ :len $HomeServer ] = 0 || [ :len $Room ] = 0) do={ + :return false; + } + + :local Headers ({ [ $FetchUserAgentStr ($Notification->"origin") ] }); + :local Plain ("## [" . $IdentityExtra . $Identity . "] " . \ + ($Notification->"subject") . "\n```\n" . ($Notification->"message") . "\n```"); + :local Formatted ("<h2>" . [ $PrepareText ("[" . $IdentityExtra . $Identity . "] " . \ + ($Notification->"subject")) ] . "</h2>" . "<pre><code>" . \ + [ $PrepareText ($Notification->"message") ] . "</code></pre>"); + :if ([ :len ($Notification->"link") ] > 0) do={ + :local Label [ $ProtocolStrip ($Notification->"link") ]; + :set Plain ($Plain . "\n" . [ $SymbolForNotification "link" ] . \ + "[" . $Label . "](" . $Notification->"link" . ")"); + :set Formatted ($Formatted . "<br/>" . [ $SymbolForNotification "link" ] . \ + "<a href=\"" . [ $PrepareText ($Notification->"link") ] . "\">" . \ + [ $PrepareText $Label ] . "</a>"); + } + + :do { + /tool/fetch check-certificate=yes-without-crl output=none \ + http-header-field=$Headers http-method=post \ + http-data=[ :serialize to=json { "msgtype"="m.text"; "body"=$Plain; + "format"="org.matrix.custom.html"; "formatted_body"=$Formatted } ] \ + ("https://" . $HomeServer . "/_matrix/client/r0/rooms/" . $Room . \ + "/send/m.room.message?access_token=" . $AccessToken) as-value; + } on-error={ + $LogPrint info $0 ("Failed sending Matrix notification! Queuing..."); + + :if ([ :typeof $MatrixQueue ] = "nothing") do={ + :set MatrixQueue ({}); + } + :local Symbol [ $SymbolForNotification "alarm-clock" ]; + :local DateTime ([ /system/clock/get date ] . " " . [ /system/clock/get time ]); + :set Plain ($Plain . "\n" . $Symbol . "This message was queued since *" . \ + $DateTime . "* and may be obsolete."); + :set Formatted ($Formatted . "<br/>" . $Symbol . "This message was queued since <em>" . \ + $DateTime . "</em> and may be obsolete."); + :set ($MatrixQueue->[ :len $MatrixQueue ]) { headers=$Headers; \ + accesstoken=$AccessToken; homeserver=$HomeServer; room=$Room; \ + plain=$Plain; formatted=$Formatted }; + :if ([ :len [ /system/scheduler/find where name="_FlushMatrixQueue" ] ] = 0) do={ + /system/scheduler/add name="_FlushMatrixQueue" interval=1m start-time=startup \ + on-event=(":global FlushMatrixQueue; \$FlushMatrixQueue;"); + } + } +} + +# purge the Matrix queue +:set PurgeMatrixQueue do={ + :global MatrixQueue; + + /system/scheduler/remove [ find where name="_FlushMatrixQueue" ]; + :set MatrixQueue; +} + +# send notification via Matrix - expects at least two string arguments +:set SendMatrix do={ + :global SendMatrix2; + + $SendMatrix2 ({ origin=$0; subject=$1; message=$2; link=$3 }); +} + +# send notification via Matrix - expects one array argument +:set SendMatrix2 do={ + :local Notification $1; + + :global NotificationFunctions; + + ($NotificationFunctions->"matrix") ("\$NotificationFunctions->\"matrix\"") $Notification; +} + +# setup - get home server and access token +:set SetupMatrixAuthenticate do={ + :local User [ :tostr $1 ]; + :local Pass [ :tostr $2 ]; + + :global FetchUserAgentStr; + :global LogPrint; + + :global MatrixAccessToken; + :global MatrixHomeServer; + + :local Domain [ :pick $User ([ :find $User ":" ] + 1) [ :len $User] ]; + :do { + :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user \ + http-header-field=({ [ $FetchUserAgentStr $0 ] }) \ + ("https://" . $Domain . "/.well-known/matrix/client") as-value ]->"data"); + :set MatrixHomeServer ([ :deserialize from=json value=$Data ]->"m.homeserver"->"base_url"); + $LogPrint debug $0 ("Home server is: " . $MatrixHomeServer); + } on-error={ + $LogPrint error $0 ("Failed getting home server!"); + :return false; + } + + :if ([ :pick $MatrixHomeServer 0 8 ] = "https://") do={ + :set MatrixHomeServer [ :pick $MatrixHomeServer 8 [ :len $MatrixHomeServer ] ]; + } + + :do { + :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user \ + http-header-field=({ [ $FetchUserAgentStr $0 ] }) http-method=post \ + http-data=[ :serialize to=json { "type"="m.login.password"; "user"=$User; "password"=$Pass } ] \ + ("https://" . $MatrixHomeServer . "/_matrix/client/r0/login") as-value ]->"data"); + :set MatrixAccessToken ([ :deserialize from=json value=$Data ]->"access_token"); + $LogPrint debug $0 ("Access token is: " . $MatrixAccessToken); + } on-error={ + $LogPrint error $0 ("Failed logging in (and getting access token)!"); + :return false; + } + + :do { + /system/script/remove [ find where name="global-config-overlay.d/mod/notification-matrix" ]; + /system/script/add name="global-config-overlay.d/mod/notification-matrix" source=( \ + "# configuration snippet: mod/notification-matrix\n\n" . \ + ":global MatrixHomeServer \"" . $MatrixHomeServer . "\";\n" . \ + ":global MatrixAccessToken \"" . $MatrixAccessToken . "\";\n"); + $LogPrint info $0 ("Added configuration snippet. Now create and join a room, please!"); + } on-error={ + $LogPrint error $0 ("Failed adding configuration snippet!"); + :return false; + } +} + +# setup - join a room +:set SetupMatrixJoinRoom do={ + :global MatrixRoom [ :tostr $1 ]; + + :global FetchUserAgentStr; + :global LogPrint; + :global UrlEncode; + + :global MatrixAccessToken; + :global MatrixHomeServer; + :global MatrixRoom; + + :do { + /tool/fetch check-certificate=yes-without-crl output=none \ + http-header-field=({ [ $FetchUserAgentStr $0 ] }) http-method=post http-data="" \ + ("https://" . $MatrixHomeServer . "/_matrix/client/r0/rooms/" . [ $UrlEncode $MatrixRoom ] . \ + "/join?access_token=" . [ $UrlEncode $MatrixAccessToken ]) as-value; + $LogPrint debug $0 ("Joined the room."); + } on-error={ + $LogPrint error $0 ("Failed joining the room!"); + :return false; + } + + :do { + :local Snippet [ /system/script/find where name="global-config-overlay.d/mod/notification-matrix" ]; + /system/script/set $Snippet source=([ get $Snippet source ] . \ + ":global MatrixRoom \"" . $MatrixRoom . "\";\n"); + $LogPrint info $0 ("Appended configuration to configuration snippet. Please review!"); + } on-error={ + $LogPrint error $0 ("Failed appending configuration to snippet!"); + :return false; + } +} diff --git a/mod/notification-ntfy.rsc b/mod/notification-ntfy.rsc new file mode 100644 index 0000000..4413f07 --- /dev/null +++ b/mod/notification-ntfy.rsc @@ -0,0 +1,148 @@ +#!rsc by RouterOS +# RouterOS script: mod/notification-ntfy +# Copyright (c) 2013-2024 Christian Hesse <mail@eworm.de> +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# send notifications via Ntfy (ntfy.sh) +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-ntfy.md + +:global FlushNtfyQueue; +:global NotificationFunctions; +:global PurgeNtfyQueue; +:global SendNtfy; +:global SendNtfy2; + +# flush ntfy queue +:set FlushNtfyQueue do={ + :global NtfyQueue; + :global NtfyMessageIDs; + + :global IsFullyConnected; + :global LogPrint; + + :if ([ $IsFullyConnected ] = false) do={ + $LogPrint debug $0 ("System is not fully connected, not flushing."); + :return false; + } + + :local AllDone true; + :local QueueLen [ :len $NtfyQueue ]; + + :if ([ :len [ /system/scheduler/find where name="_FlushNtfyQueue" ] ] > 0 && $QueueLen = 0) do={ + $LogPrint warning $0 ("Flushing Ntfy messages from scheduler, but queue is empty."); + } + + :foreach Id,Message in=$NtfyQueue do={ + :if ([ :typeof $Message ] = "array" ) do={ + :do { + /tool/fetch check-certificate=yes-without-crl output=none http-method=post \ + http-header-field=($Message->"headers") http-data=($Message->"text") \ + ($Message->"url") user=($Message->"user") password=($Message->"pass") as-value; + :set ($NtfyQueue->$Id); + } on-error={ + $LogPrint debug $0 ("Sending queued Ntfy message failed."); + :set AllDone false; + } + } + } + + :if ($AllDone = true && $QueueLen = [ :len $NtfyQueue ]) do={ + /system/scheduler/remove [ find where name="_FlushNtfyQueue" ]; + :set NtfyQueue; + } +} + +# send notification via ntfy - expects one array argument +:set ($NotificationFunctions->"ntfy") do={ + :local Notification $1; + + :global Identity; + :global IdentityExtra; + :global NtfyQueue; + :global NtfyServer; + :global NtfyServerOverride; + :global NtfyServerPass; + :global NtfyServerPassOverride; + :global NtfyServerUser; + :global NtfyServerUserOverride; + :global NtfyTopic; + :global NtfyTopicOverride; + + :global CertificateAvailable; + :global EitherOr; + :global FetchUserAgentStr; + :global IfThenElse; + :global LogPrint; + :global SymbolForNotification; + :global UrlEncode; + + :local Server [ $EitherOr ($NtfyServerOverride->($Notification->"origin")) $NtfyServer ]; + :local User [ $EitherOr ($NtfyServerUserOverride->($Notification->"origin")) $NtfyServerUser ]; + :local Pass [ $EitherOr ($NtfyServerPassOverride->($Notification->"origin")) $NtfyServerPass ]; + :local Topic [ $EitherOr ($NtfyTopicOverride->($Notification->"origin")) $NtfyTopic ]; + + :if ([ :len $Topic ] = 0) do={ + :return false; + } + + :local Url ("https://" . $NtfyServer . "/" . [ $UrlEncode $NtfyTopic ]); + :local Headers ({ [ $FetchUserAgentStr ($Notification->"origin") ]; \ + ("Priority: " . [ $IfThenElse ($Notification->"silent") "low" "default" ]); \ + ("Title: " . "[" . $IdentityExtra . $Identity . "] " . ($Notification->"subject")) }); + :local Text (($Notification->"message") . "\n"); + :if ([ :len ($Notification->"link") ] > 0) do={ + :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . ($Notification->"link")); + } + + :do { + :if ($NtfyServer = "ntfy.sh") do={ + :if ([ $CertificateAvailable "R3" ] = false) do={ + $LogPrint warning $0 ("Downloading required certificate failed."); + :error false; + } + } + /tool/fetch check-certificate=yes-without-crl output=none http-method=post \ + http-header-field=$Headers http-data=$Text $Url user=$User password=$Pass as-value; + } on-error={ + $LogPrint info $0 ("Failed sending ntfy notification! Queuing..."); + + :if ([ :typeof $NtfyQueue ] = "nothing") do={ + :set NtfyQueue ({}); + } + :set Text ($Text . "\n" . [ $SymbolForNotification "alarm-clock" ] . \ + "This message was queued since " . [ /system/clock/get date ] . " " . \ + [ /system/clock/get time ] . " and may be obsolete."); + :set ($NtfyQueue->[ :len $NtfyQueue ]) \ + { url=$Url; user=$User; pass=$Pass; headers=$Headers; text=$Text }; + :if ([ :len [ /system/scheduler/find where name="_FlushNtfyQueue" ] ] = 0) do={ + /system/scheduler/add name="_FlushNtfyQueue" interval=1m start-time=startup \ + on-event=(":global FlushNtfyQueue; \$FlushNtfyQueue;"); + } + } +} + +# purge the Ntfy queue +:set PurgeNtfyQueue do={ + :global NtfyQueue; + + /system/scheduler/remove [ find where name="_FlushNtfyQueue" ]; + :set NtfyQueue; +} + +# send notification via ntfy - expects at least two string arguments +:set SendNtfy do={ + :global SendNtfy2; + + $SendNtfy2 ({ origin=$0; subject=$1; message=$2; link=$3; silent=$4 }); +} + +# send notification via ntfy - expects one array argument +:set SendNtfy2 do={ + :local Notification $1; + + :global NotificationFunctions; + + ($NotificationFunctions->"ntfy") ("\$NotificationFunctions->\"ntfy\"") $Notification; +} diff --git a/mod/notification-telegram b/mod/notification-telegram deleted file mode 100644 index 8c4cd65..0000000 --- a/mod/notification-telegram +++ /dev/null @@ -1,170 +0,0 @@ -#!rsc by RouterOS -# RouterOS script: mod/notification-telegram -# Copyright (c) 2013-2022 Christian Hesse <mail@eworm.de> -# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md - -:global FlushTelegramQueue; -:global NotificationFunctions; -:global SendTelegram; -:global SendTelegram2; - -# flush telegram queue -:set FlushTelegramQueue do={ - :global TelegramQueue; - - :global IsFullyConnected; - :global LogPrintExit2; - - :if ([ $IsFullyConnected ] = false) do={ - $LogPrintExit2 debug $0 ("System is not fully connected, not flushing.") false; - :return false; - } - - :local AllDone true; - :local QueueLen [ :len $TelegramQueue ]; - - :if ([ :len [ /system/scheduler/find where name="FlushTelegramQueue" ] ] > 0 && $QueueLen = 0) do={ - $LogPrintExit2 warning $0 ("Flushing Telegram messages from scheduler, but queue is empty.") false; - } - - :foreach Id,Message in=$TelegramQueue do={ - :if ([ :typeof $Message ] = "array" ) do={ - :do { - /tool/fetch check-certificate=yes-without-crl output=none http-method=post \ - ("https://api.telegram.org/bot" . ($Message->"tokenid") . "/sendMessage") \ - http-data=("chat_id=" . ($Message->"chatid") . \ - "&disable_notification=" . ($Message->"silent") . \ - "&disable_web_page_preview=true&parse_mode=" . ($Message->"parsemode") . \ - "&text=" . ($Message->"text")) as-value; - :set ($TelegramQueue->$Id); - } on-error={ - $LogPrintExit2 debug $0 ("Sending queued Telegram message failed.") false; - :set AllDone false; - } - } - } - - :if ($AllDone = true && $QueueLen = [ :len $TelegramQueue ]) do={ - /system/scheduler/remove [ find where name="FlushTelegramQueue" ]; - :set TelegramQueue; - } -} - -# send notification via telegram - expects one array argument -:set ($NotificationFunctions->"telegram") do={ - :local Notification $1; - - :global Identity; - :global TelegramChatId; - :global TelegramChatIdOverride; - :global TelegramFixedWidthFont; - :global TelegramQueue; - :global TelegramTokenId; - :global TelegramTokenIdOverride; - - :global CertificateAvailable; - :global CharacterReplace; - :global EitherOr; - :global IfThenElse; - :global LogPrintExit2; - :global SymbolForNotification; - :global UrlEncode; - - :local EscapeMD do={ - :global TelegramFixedWidthFont; - - :global CharacterReplace; - :global IfThenElse; - - :if ($TelegramFixedWidthFont != true) do={ - :return ($1 . [ $IfThenElse ($2 = "body") ("\n") "" ]); - } - - :local Return $1; - :local Chars { - "body"={ "\\"; "`" }; - "plain"={ "_"; "*"; "["; "]"; "("; ")"; "~"; "`"; ">"; - "#"; "+"; "-"; "="; "|"; "{"; "}"; "."; "!" }; - } - :foreach Char in=($Chars->$2) do={ - :set Return [ $CharacterReplace $Return $Char ("\\" . $Char) ]; - } - - :if ($2 = "body") do={ - :return ("```\n" . $Return . "\n```"); - } - - :return $Return; - } - - :local ChatId [ $EitherOr ($TelegramChatIdOverride->($Notification->"origin")) $TelegramChatId ]; - :local TokenId [ $EitherOr ($TelegramTokenIdOverride->($Notification->"origin")) $TelegramTokenId ]; - - :if ([ :len $TokenId ] = 0 || [ :len $ChatId ] = 0) do={ - :return false; - } - - :local Truncated false; - :local Text ("*__" . [ $EscapeMD ("[" . $Identity . "] " . ($Notification->"subject")) "plain" ] . "__*\n\n"); - :local LenSubject [ :len $Text ]; - :local LenMessage [ :len ($Notification->"message") ]; - :local LenLink [ :len ($Notification->"link") ]; - :local LenSum ($LenSubject + $LenMessage + $LenLink); - :if ($LenSum > 3968) do={ - :set Text ($Text . [ $EscapeMD ([ :pick ($Notification->"message") 0 (3840 - $LenSubject - $LenLink) ] . "...") "body" ]); - :set Truncated true; - } else={ - :set Text ($Text . [ $EscapeMD ($Notification->"message") "body" ]); - } - :if ($LenLink > 0) do={ - :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . [ $EscapeMD ($Notification->"link") "plain" ]); - } - :if ($Truncated = true) do={ - :set Text ($Text . "\n" . [ $SymbolForNotification "scissors" ] . \ - [ $EscapeMD ("The Telegram message was too long and has been truncated, cut off " . \ - (($LenSum - [ :len $Text ]) * 100 / $LenSum) . "%!") "plain" ]); - } - :set Text [ $UrlEncode $Text ]; - :local ParseMode [ $IfThenElse ($TelegramFixedWidthFont = true) "MarkdownV2" "" ]; - - :do { - :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={ - $LogPrintExit2 warning $0 ("Downloading required certificate failed.") true; - } - /tool/fetch check-certificate=yes-without-crl output=none http-method=post \ - ("https://api.telegram.org/bot" . $TokenId . "/sendMessage") \ - http-data=("chat_id=" . $ChatId . "&disable_notification=" . ($Notification->"silent") . \ - "&disable_web_page_preview=true&parse_mode=" . $ParseMode . "&text=" . $Text) as-value; - } on-error={ - $LogPrintExit2 info $0 ("Failed sending telegram notification! Queuing...") false; - - :if ([ :typeof $TelegramQueue ] = "nothing") do={ - :set TelegramQueue ({}); - } - :set Text ($Text . [ $UrlEncode ("\n" . [ $SymbolForNotification "alarm-clock" ] . \ - [ $EscapeMD ("This message was queued since " . [ /system/clock/get date ] . \ - " " . [ /system/clock/get time ] . " and may be obsolete.") "plain" ]) ]); - :set ($TelegramQueue->[ :len $TelegramQueue ]) { chatid=$ChatId; tokenid=$TokenId; - parsemode=$ParseMode; text=$Text; silent=($Notification->"silent") }; - :if ([ :len [ /system/scheduler/find where name="FlushTelegramQueue" ] ] = 0) do={ - /system/scheduler/add name=FlushTelegramQueue interval=1m start-time=startup \ - on-event=(":global FlushTelegramQueue; \$FlushTelegramQueue;"); - } - } -} - -# send notification via telegram - expects at least two string arguments -:set SendTelegram do={ - :global SendTelegram2; - - $SendTelegram2 ({ subject=$1; message=$2; link=$3; silent=$4 }); -} - -# send notification via telegram - expects one array argument -:set SendTelegram2 do={ - :local Notification $1; - - :global NotificationFunctions; - - ($NotificationFunctions->"telegram") ("\$NotificationFunctions->\"telegram\"") $Notification; -} diff --git a/mod/notification-telegram.rsc b/mod/notification-telegram.rsc new file mode 100644 index 0000000..9a628ce --- /dev/null +++ b/mod/notification-telegram.rsc @@ -0,0 +1,196 @@ +#!rsc by RouterOS +# RouterOS script: mod/notification-telegram +# Copyright (c) 2013-2024 Christian Hesse <mail@eworm.de> +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# send notifications via Telegram +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-telegram.md + +:global FlushTelegramQueue; +:global NotificationFunctions; +:global PurgeTelegramQueue; +:global SendTelegram; +:global SendTelegram2; + +# flush telegram queue +:set FlushTelegramQueue do={ + :global TelegramQueue; + :global TelegramMessageIDs; + + :global IsFullyConnected; + :global LogPrint; + :global UrlEncode; + + :if ([ $IsFullyConnected ] = false) do={ + $LogPrint debug $0 ("System is not fully connected, not flushing."); + :return false; + } + + :local AllDone true; + :local QueueLen [ :len $TelegramQueue ]; + + :if ([ :len [ /system/scheduler/find where name="_FlushTelegramQueue" ] ] > 0 && $QueueLen = 0) do={ + $LogPrint warning $0 ("Flushing Telegram messages from scheduler, but queue is empty."); + } + + :foreach Id,Message in=$TelegramQueue do={ + :if ([ :typeof $Message ] = "array" ) do={ + :do { + :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user http-method=post \ + ("https://api.telegram.org/bot" . ($Message->"tokenid") . "/sendMessage") \ + http-data=("chat_id=" . ($Message->"chatid") . "&disable_notification=" . ($Message->"silent") . \ + "&reply_to_message_id=" . ($Message->"replyto") . "&disable_web_page_preview=true" . \ + "&parse_mode=MarkdownV2&text=" . [ $UrlEncode ($Message->"text") ]) as-value ]->"data"); + :set ($TelegramQueue->$Id); + :set ($TelegramMessageIDs->[ :tostr ([ :deserialize from=json value=$Data ]->"result"->"message_id") ]) 1; + } on-error={ + $LogPrint debug $0 ("Sending queued Telegram message failed."); + :set AllDone false; + } + } + } + + :if ($AllDone = true && $QueueLen = [ :len $TelegramQueue ]) do={ + /system/scheduler/remove [ find where name="_FlushTelegramQueue" ]; + :set TelegramQueue; + } +} + +# send notification via telegram - expects one array argument +:set ($NotificationFunctions->"telegram") do={ + :local Notification $1; + + :global Identity; + :global IdentityExtra; + :global TelegramChatId; + :global TelegramChatIdOverride; + :global TelegramMessageIDs; + :global TelegramQueue; + :global TelegramTokenId; + :global TelegramTokenIdOverride; + + :global CertificateAvailable; + :global CharacterReplace; + :global EitherOr; + :global IfThenElse; + :global LogPrint; + :global ProtocolStrip; + :global SymbolForNotification; + :global UrlEncode; + + :local EscapeMD do={ + :local Text [ :tostr $1 ]; + :local Mode [ :tostr $2 ]; + :local Excl [ :tostr $3 ]; + + :global CharacterReplace; + :global IfThenElse; + + :local Chars { + "body"={ "\\"; "`" }; + "plain"={ "_"; "*"; "["; "]"; "("; ")"; "~"; "`"; ">"; + "#"; "+"; "-"; "="; "|"; "{"; "}"; "."; "!" }; + } + :foreach Char in=($Chars->$Mode) do={ + :if ([ :typeof [ :find $Excl $Char ] ] = "nil") do={ + :set Text [ $CharacterReplace $Text $Char ("\\" . $Char) ]; + } + } + + :if ($Mode = "body") do={ + :return ("```\n" . $Text . "\n```"); + } + + :return $Text; + } + + :local ChatId [ $EitherOr ($Notification->"chatid") \ + [ $EitherOr ($TelegramChatIdOverride->($Notification->"origin")) $TelegramChatId ] ]; + :local TokenId [ $EitherOr ($TelegramTokenIdOverride->($Notification->"origin")) $TelegramTokenId ]; + + :if ([ :len $TokenId ] = 0 || [ :len $ChatId ] = 0) do={ + :return false; + } + + :if ([ :typeof $TelegramMessageIDs ] = "nothing") do={ + :set TelegramMessageIDs ({}); + } + + :local Truncated false; + :local Text ("*__" . [ $EscapeMD ("[" . $IdentityExtra . $Identity . "] " . \ + ($Notification->"subject")) "plain" ] . "__*\n\n"); + :local LenSubject [ :len $Text ]; + :local LenMessage [ :len ($Notification->"message") ]; + :local LenLink ([ :len ($Notification->"link") ] * 2); + :local LenSum ($LenSubject + $LenMessage + $LenLink); + :if ($LenSum > 3968) do={ + :set Text ($Text . [ $EscapeMD ([ :pick ($Notification->"message") 0 (3840 - $LenSubject - $LenLink) ] . "...") "body" ]); + :set Truncated true; + } else={ + :set Text ($Text . [ $EscapeMD ($Notification->"message") "body" ]); + } + :if ($LenLink > 0) do={ + :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . \ + "[" . [ $EscapeMD [ $ProtocolStrip ($Notification->"link") ] "plain" ] . "]" . \ + "(" . [ $EscapeMD ($Notification->"link") "plain" ] . ")"); + } + :if ($Truncated = true) do={ + :set Text ($Text . "\n" . [ $SymbolForNotification "scissors" ] . \ + [ $EscapeMD ("The message was too long and has been truncated, cut off _" . \ + (($LenSum - [ :len $Text ]) * 100 / $LenSum) . "%_!") "plain" "_" ]); + } + + :do { + :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={ + $LogPrint warning $0 ("Downloading required certificate failed."); + :error false; + } + :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user http-method=post \ + ("https://api.telegram.org/bot" . $TokenId . "/sendMessage") \ + http-data=("chat_id=" . $ChatId . "&disable_notification=" . ($Notification->"silent") . \ + "&reply_to_message_id=" . ($Notification->"replyto") . "&disable_web_page_preview=true" . \ + "&parse_mode=MarkdownV2&text=" . [ $UrlEncode $Text ]) as-value ]->"data"); + :set ($TelegramMessageIDs->[ :tostr ([ :deserialize from=json value=$Data ]->"result"->"message_id") ]) 1; + } on-error={ + $LogPrint info $0 ("Failed sending Telegram notification! Queuing..."); + + :if ([ :typeof $TelegramQueue ] = "nothing") do={ + :set TelegramQueue ({}); + } + :set Text ($Text . "\n" . [ $SymbolForNotification "alarm-clock" ] . \ + [ $EscapeMD ("This message was queued since _" . [ /system/clock/get date ] . \ + " " . [ /system/clock/get time ] . "_ and may be obsolete.") "plain" "_" ]); + :set ($TelegramQueue->[ :len $TelegramQueue ]) { chatid=$ChatId; tokenid=$TokenId; + text=$Text; silent=($Notification->"silent"); replyto=($Notification->"replyto") }; + :if ([ :len [ /system/scheduler/find where name="_FlushTelegramQueue" ] ] = 0) do={ + /system/scheduler/add name="_FlushTelegramQueue" interval=1m start-time=startup \ + on-event=(":global FlushTelegramQueue; \$FlushTelegramQueue;"); + } + } +} + +# purge the Telegram queue +:set PurgeTelegramQueue do={ + :global TelegramQueue; + + /system/scheduler/remove [ find where name="_FlushTelegramQueue" ]; + :set TelegramQueue; +} + +# send notification via telegram - expects at least two string arguments +:set SendTelegram do={ + :global SendTelegram2; + + $SendTelegram2 ({ origin=$0; subject=$1; message=$2; link=$3; silent=$4 }); +} + +# send notification via telegram - expects one array argument +:set SendTelegram2 do={ + :local Notification $1; + + :global NotificationFunctions; + + ($NotificationFunctions->"telegram") ("\$NotificationFunctions->\"telegram\"") $Notification; +} diff --git a/mod/scriptrunonce b/mod/scriptrunonce deleted file mode 100644 index 6cca175..0000000 --- a/mod/scriptrunonce +++ /dev/null @@ -1,46 +0,0 @@ -#!rsc by RouterOS -# RouterOS script: mod/scriptrunonece -# Copyright (c) 2020-2022 Christian Hesse <mail@eworm.de> -# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md - -:global ScriptRunOnce; - -# fetch and run script(s) once -:set ScriptRunOnce do={ - :local Scripts [ :toarray $1 ]; - - :global ScriptRunOnceBaseUrl; - :global ScriptRunOnceUrlSuffix; - - :global LogPrintExit2; - :global ValidateSyntax; - - :foreach Script in=$Scripts do={ - :if (!($Script ~ "^(ftp|https\?|sftp)://")) do={ - :if ([ :len $ScriptRunOnceBaseUrl ] = 0) do={ - $LogPrintExit2 warning $0 ("Script '" . $Script . "' is not an url and base url is not available.") true; - } - :set Script ($ScriptRunOnceBaseUrl . $Script . $ScriptRunOnceUrlSuffix); - } - - :local Source; - :do { - :set Source ([ /tool/fetch check-certificate=yes-without-crl $Script output=user as-value ]->"data"); - } on-error={ - $LogPrintExit2 warning $0 ("Failed fetching script '" . $Script . "'!") false; - } - - :if ([ :len $Source ] > 0) do={ - :if ([ $ValidateSyntax $Source ] = true) do={ - :do { - $LogPrintExit2 info $0 ("Running script '" . $Script . "' now.") false; - [ :parse $Source ]; - } on-error={ - $LogPrintExit2 warning $0 ("The script '" . $Script . "' failed to run!") false; - } - } else={ - $LogPrintExit2 warning $0 ("The script '" . $Script . "' failed syntax validation!") false; - } - } - } -} diff --git a/mod/scriptrunonce.rsc b/mod/scriptrunonce.rsc new file mode 100644 index 0000000..c3972a0 --- /dev/null +++ b/mod/scriptrunonce.rsc @@ -0,0 +1,52 @@ +#!rsc by RouterOS +# RouterOS script: mod/scriptrunonece +# Copyright (c) 2020-2024 Christian Hesse <mail@eworm.de> +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# download script and run it once +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/scriptrunonce.md + +:global ScriptRunOnce; + +# fetch and run script(s) once +:set ScriptRunOnce do={ + :local Scripts [ :toarray $1 ]; + + :global ScriptRunOnceBaseUrl; + :global ScriptRunOnceUrlSuffix; + + :global LogPrint; + :global ValidateSyntax; + + :foreach Script in=$Scripts do={ + :if (!($Script ~ "^(ftp|https?|sftp)://")) do={ + :if ([ :len $ScriptRunOnceBaseUrl ] = 0) do={ + $LogPrint warning $0 ("Script '" . $Script . "' is not an url and base url is not available."); + :return false; + } + :set Script ($ScriptRunOnceBaseUrl . $Script . ".rsc" . $ScriptRunOnceUrlSuffix); + } + + :local Source; + :do { + :set Source ([ /tool/fetch check-certificate=yes-without-crl $Script output=user as-value ]->"data"); + } on-error={ + $LogPrint warning $0 ("Failed fetching script '" . $Script . "'!"); + } + + :if ([ :len $Source ] > 0) do={ + :if ([ $ValidateSyntax $Source ] = true) do={ + :do { + $LogPrint info $0 ("Running script '" . $Script . "' now."); + [ :parse $Source ]; + } on-error={ + $LogPrint warning $0 ("The script '" . $Script . "' failed to run!"); + } + } else={ + $LogPrint warning $0 ("The script '" . $Script . "' failed syntax validation!"); + } + } + } +} diff --git a/mod/ssh-keys-import.rsc b/mod/ssh-keys-import.rsc new file mode 100644 index 0000000..6272a93 --- /dev/null +++ b/mod/ssh-keys-import.rsc @@ -0,0 +1,114 @@ +#!rsc by RouterOS +# RouterOS script: mod/ssh-keys-import +# Copyright (c) 2020-2024 Christian Hesse <mail@eworm.de> +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# +# requires RouterOS, version=7.13 +# +# import ssh keys for public key authentication +# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/ssh-keys-import.md + +:global SSHKeysImport; +:global SSHKeysImportFile; + +# import single key passed as string +:set SSHKeysImport do={ + :local Key [ :tostr $1 ]; + :local User [ :tostr $2 ]; + + :global CharacterReplace; + :global GetRandom20CharAlNum; + :global LogPrint; + :global MkDir; + :global WaitForFile; + + :if ([ :len $Key ] = 0 || [ :len $User ] = 0) do={ + $LogPrint warning $0 ("Missing argument(s), please pass key and user!"); + :return false; + } + + :if ([ :len [ /user/find where name=$User ] ] = 0) do={ + $LogPrint warning $0 ("User '" . $User . "' does not exist."); + :return false; + } + + :local KeyVal [ :toarray [ $CharacterReplace $Key " " "," ] ]; + :if (!($KeyVal->0 = "ssh-ed25519" || $KeyVal->0 = "ssh-rsa")) do={ + $LogPrint warning $0 ("SSH key of type '" . $KeyVal->0 . "' is not supported."); + :return false; + } + + :local FingerPrintMD5 [ :convert from=base64 transform=md5 to=hex ($KeyVal->1) ]; + + :if ([ :len [ /user/ssh-keys/find where user=$User key-owner~("\\bmd5=" . $FingerPrintMD5 . "\\b") ] ] > 0) do={ + $LogPrint warning $0 ("The ssh public key (MD5:" . $FingerPrintMD5 . \ + ") is already available for user '" . $User . "'."); + :return false; + } + + :if ([ $MkDir "tmpfs/ssh-keys-import" ] = false) do={ + $LogPrint warning $0 ("Creating directory 'tmpfs/ssh-keys-import' failed!"); + :return false; + } + + :local FileName ("tmpfs/ssh-keys-import/key-" . [ $GetRandom20CharAlNum 6 ] . ".pub"); + /file/add name=$FileName contents=($Key . ", md5=" . $FingerPrintMD5); + $WaitForFile $FileName; + + :do { + /user/ssh-keys/import public-key-file=$FileName user=$User; + $LogPrint info $0 ("Imported ssh public key (" . $KeyVal->2 . ", " . $KeyVal->0 . ", " . \ + "MD5:" . $FingerPrintMD5 . ") for user '" . $User . "'."); + /file/remove "tmpfs/ssh-keys-import"; + } on-error={ + $LogPrint warning $0 ("Failed importing key."); + /file/remove "tmpfs/ssh-keys-import"; + :return false; + } +} + +# import keys from a file +:set SSHKeysImportFile do={ + :local FileName [ :tostr $1 ]; + :local User [ :tostr $2 ]; + + :global CharacterReplace; + :global EitherOr; + :global LogPrint; + :global ParseKeyValueStore; + :global SSHKeysImport; + + :if ([ :len $FileName ] = 0 || [ :len $User ] = 0) do={ + $LogPrint warning $0 ("Missing argument(s), please pass file name and user!"); + :return false; + } + + :local File [ /file/find where name=$FileName ]; + :if ([ :len $File ] = 0) do={ + $LogPrint warning $0 ("File '" . $FileName . "' does not exist."); + :return false; + } + :local Keys ([ /file/get $FileName contents ] . "\n"); + + :do { + :local Continue false; + :local Line [ :pick $Keys 0 [ :find $Keys "\n" ] ]; + :set Keys [ :pick $Keys ([ :find $Keys "\n" ] + 1) [ :len $Keys ] ]; + :local KeyVal [ :toarray [ $CharacterReplace $Line " " "," ] ]; + :if ($KeyVal->0 = "ssh-ed25519" || $KeyVal->0 = "ssh-rsa") do={ + :do { + $SSHKeysImport $Line $User; + } on-error={ + $LogPrint warning $0 ("Failed importing key for user '" . $User . "'."); + } + :set Continue true; + } + :if ($Continue = false && $KeyVal->0 = "#") do={ + :set User [ $EitherOr ([ $ParseKeyValueStore [ :pick $Line 2 [ :len $Line ] ] ]->"user") $User ]; + :set Continue true; + } + :if ($Continue = false && [ :len ($KeyVal->0) ] > 0) do={ + $LogPrint warning $0 ("SSH key of type '" . $KeyVal->0 . "' is not supported."); + } + } while=([ :len $Keys ] > 0); +} |