aboutsummaryrefslogtreecommitdiffstats
path: root/mod
diff options
context:
space:
mode:
Diffstat (limited to 'mod')
-rw-r--r--mod/bridge-port-to.rsc (renamed from mod/bridge-port-to)35
-rw-r--r--mod/bridge-port-vlan.rsc (renamed from mod/bridge-port-vlan)39
-rw-r--r--mod/inspectvar.rsc (renamed from mod/inspectvar)13
-rw-r--r--mod/ipcalc.rsc (renamed from mod/ipcalc)24
-rw-r--r--mod/notification-email.rsc240
-rw-r--r--mod/notification-matrix157
-rw-r--r--mod/notification-matrix.rsc265
-rw-r--r--mod/notification-ntfy.rsc148
-rw-r--r--mod/notification-telegram.rsc (renamed from mod/notification-telegram)103
-rw-r--r--mod/scriptrunonce46
-rw-r--r--mod/scriptrunonce.rsc52
-rw-r--r--mod/ssh-keys-import.rsc112
12 files changed, 955 insertions, 279 deletions
diff --git a/mod/bridge-port-to b/mod/bridge-port-to.rsc
index 36b827b..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,9 +14,10 @@
:local BridgePortTo [ :tostr $1 ];
:global IfThenElse;
- :global LogPrintExit2;
+ :global LogPrint;
:global ParseKeyValueStore;
+ :local InterfaceReEnable ({});
:foreach BridgePort in=[ /interface/bridge/port/find where !(comment=[]) ] do={
:local BridgePortVal [ /interface/bridge/port/get $BridgePort ];
:foreach Config,BridgeDefault in=[ $ParseKeyValueStore ($BridgePortVal->"comment") ] do={
@@ -23,35 +26,43 @@
: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;
}
- /interface/ethernet/disable [ find where name=$BridgePortVal->"interface" ];
+ :local Disable [ /interface/ethernet/find where name=$BridgePortVal->"interface" ];
+ :if ([ :len $Disable ] > 0) do={
+ /interface/ethernet/disable $Disable;
+ :set InterfaceReEnable ($InterfaceReEnable, $Disable);
+ }
/interface/bridge/port/set disabled=no bridge=$BridgeDefault $BridgePort;
- :delay 500ms;
- /interface/ethernet/enable [ find where name=$BridgePortVal->"interface" ];
} 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 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 b880c82..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,9 +14,10 @@
:local ConfigTo [ :tostr $1 ];
:global IfThenElse;
- :global LogPrintExit2;
+ :global LogPrint;
:global ParseKeyValueStore;
+ :local InterfaceReEnable ({});
:foreach BridgePort in=[ /interface/bridge/port/find where !(comment=[]) ] do={
:local BridgePortVal [ /interface/bridge/port/get $BridgePort ];
:foreach Config,Vlan in=[ $ParseKeyValueStore ($BridgePortVal->"comment") ] do={
@@ -23,42 +26,52 @@
: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;
}
} else={
+ :local VlanName $Vlan;
:if ($Vlan != [ :tostr [ :tonum $Vlan ] ]) do={
: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 . ", 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;
}
- /interface/ethernet/disable [ find where name=$BridgePortVal->"interface" ];
+ :local Disable [ /interface/ethernet/find where name=$BridgePortVal->"interface" ];
+ :if ([ :len $Disable ] > 0) do={
+ /interface/ethernet/disable $Disable;
+ :set InterfaceReEnable ($InterfaceReEnable, $Disable);
+ }
/interface/bridge/port/set disabled=no pvid=$Vlan $BridgePort;
- :delay 500ms;
- /interface/ethernet/enable [ find where name=$BridgePortVal->"interface" ];
} 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 5s;
+ $LogPrint info $0 ("Re-enabling interfaces...");
+ /interface/ethernet/enable $InterfaceReEnable;
+ }
}
diff --git a/mod/inspectvar b/mod/inspectvar.rsc
index 2130bb1..5adca0a 100644
--- a/mod/inspectvar
+++ b/mod/inspectvar.rsc
@@ -1,17 +1,22 @@
#!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;
# inspect variable and print on terminal
:set InspectVar do={
- :global CharacterReplace;
:global InspectVarReturn;
+ :global PrettyPrint;
- :put [ $CharacterReplace [ $InspectVarReturn $1 ] ("\n") ("\n\r") ];
+ $PrettyPrint [ $InspectVarReturn $1 ];
}
# inspect variable and return formatted string
@@ -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 a3e1e00..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,17 +15,19 @@
:set IPCalc do={
:local Input [ :tostr $1 ];
+ :global FormatLine;
:global IPCalcReturn;
+ :global PrettyPrint;
:local Values [ $IPCalcReturn $1 ];
- :put ( \
- "Address: " . $Values->"address" . "\n\r" . \
- "Netmask: " . $Values->"netmask" . "\n\r" . \
- "Network: " . $Values->"network" . "\n\r" . \
- "HostMin: " . $Values->"hostmin" . "\n\r" . \
- "HostMax: " . $Values->"hostmax" . "\n\r" . \
- "Broadcast: " . $Values->"broadcast");
+ $PrettyPrint ( \
+ [ $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
@@ -43,4 +50,3 @@
:return $Return;
}
-
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 c3cf24f..0000000
--- a/mod/notification-matrix
+++ /dev/null
@@ -1,157 +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 LogPrintExit2;
-
- :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"={ "\\\\"; "&quot;"; "<br/>"; "&amp;"; "&lt;"; "&gt;" };
- }
-
- :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 [ :toarray "" ];
- }
- :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 lease 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..9442f54
--- /dev/null
+++ b/mod/notification-matrix.rsc
@@ -0,0 +1,265 @@
+#!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 { "&quot;"; "<br/>"; "&amp;"; "&lt;"; "&gt;" };
+
+ :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 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 ]) { 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.rsc
index 230dd57..745367a 100644
--- a/mod/notification-telegram
+++ b/mod/notification-telegram.rsc
@@ -1,45 +1,59 @@
#!rsc by RouterOS
# RouterOS script: mod/notification-telegram
-# 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
+#
+# 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 LogPrintExit2;
+ :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={
- $LogPrintExit2 warning $0 ("Flushing Telegram messages from scheduler, but queue is empty.") false;
+ :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 {
- /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ :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") . \
- "&disable_web_page_preview=true&parse_mode=" . ($Message->"parsemode") . \
- "&text=" . ($Message->"text")) as-value;
+ 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={
- $LogPrintExit2 debug $0 ("Sending queued Telegram message failed.") false;
+ $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" ];
+ /system/scheduler/remove [ find where name="_FlushTelegramQueue" ];
:set TelegramQueue;
}
}
@@ -49,9 +63,10 @@
:local Notification $1;
:global Identity;
+ :global IdentityExtra;
:global TelegramChatId;
:global TelegramChatIdOverride;
- :global TelegramFixedWidthFont;
+ :global TelegramMessageIDs;
:global TelegramQueue;
:global TelegramTokenId;
:global TelegramTokenIdOverride;
@@ -60,20 +75,15 @@
:global CharacterReplace;
:global EitherOr;
:global IfThenElse;
- :global LogPrintExit2;
+ :global LogPrint;
+ :global ProtocolStrip;
: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"={ "\\"; "`" };
@@ -91,18 +101,24 @@
:return $Return;
}
- :local ChatId [ $EitherOr ($TelegramChatIdOverride->($Notification->"origin")) $TelegramChatId ];
+ :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 ("[" . $Identity . "] " . ($Notification->"subject")) "plain" ] . "__*\n\n");
+ :local Text ("*__" . [ $EscapeMD ("[" . $IdentityExtra . $Identity . "] " . \
+ ($Notification->"subject")) "plain" ] . "__*\n\n");
:local LenSubject [ :len $Text ];
:local LenMessage [ :len ($Notification->"message") ];
- :local LenLink [ :len ($Notification->"link") ];
+ :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" ]);
@@ -111,47 +127,58 @@
:set Text ($Text . [ $EscapeMD ($Notification->"message") "body" ]);
}
:if ($LenLink > 0) do={
- :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . [ $EscapeMD ($Notification->"link") "plain" ]);
+ :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 Telegram message was too long and has been truncated, cut off " . \
+ [ $EscapeMD ("The 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;
+ $LogPrint warning $0 ("Downloading required certificate failed.");
+ :error false;
}
- /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ :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") . \
- "&disable_web_page_preview=true&parse_mode=" . $ParseMode . "&text=" . $Text) as-value;
+ "&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={
- $LogPrintExit2 info $0 ("Failed sending telegram notification! Queuing...") false;
+ $LogPrint info $0 ("Failed sending telegram notification! Queuing...");
:if ([ :typeof $TelegramQueue ] = "nothing") do={
- :set TelegramQueue [ :toarray "" ];
+ :set TelegramQueue ({});
}
- :set Text ($Text . [ $UrlEncode ("\n" . [ $SymbolForNotification "alarm-clock" ] . \
+ :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" ]) ]);
+ " " . [ /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 \
+ 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;");
}
}
}
-# send notification via telegram - expects at lease two string arguments
+# 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 ({ subject=$1; message=$2; link=$3; silent=$4 });
+ $SendTelegram2 ({ origin=$0; subject=$1; message=$2; link=$3; silent=$4 });
}
# send notification via telegram - expects one array argument
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..f37c28b
--- /dev/null
+++ b/mod/ssh-keys-import.rsc
@@ -0,0 +1,112 @@
+#!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;
+ }
+
+ :if ([ $MkDir "tmpfs/ssh-keys-import" ] = false) do={
+ $LogPrint warning $0 ("Creating directory 'tmpfs/ssh-keys-import' failed!");
+ :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;
+ }
+
+ :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 . "'.");
+ } on-error={
+ $LogPrint warning $0 ("Failed importing key.");
+ :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);
+}