tik4net .NET Library for MikroTik RouterOS

repository·master·Indexed 41 days ago

https://github.com/danikf/tik4net

A comprehensive .NET library for interacting with MikroTik RouterOS devices. It provides a unified ITikConnection interface supporting multiple protocols, including the native API, REST, SSH, Telnet, MAC-Telnet, and WinBox. The library includes a low-level ADO.NET-like API and a high-level O/R mapper for performing CRUD operations on router entities.

Tokens
82.6K
Snippets
140
Records
351
Agent score
49%

What's inside tik4net

  1. Overview of tik4net.ssh capabilities

    master

    The tik4net.ssh package is an SSH transport satellite designed to drive the RouterOS CLI over an SSH shell (TCP 22). It provides the following capabilities:

    • Crud: Basic Create, Read, Update, Delete operations.
    • Listen (polled): Ability to listen for changes via polling.
    • SafeMode: Execution in a safe mode.
    • RawCommand: Execution of raw commands.
    • AsyncCommands: Support for asynchronous command execution.
  2. Overview of tik4net.objects O/R mapper

    master

    The tik4net.objects library is a high-level, attribute-driven Object-Relational (O/R) mapper built on top of tik4net. It provides strongly typed entities with support for:

    • Full CRUD operations.
    • Change tracking (sending only modified fields).
    • List merging.
    • Efficient reflection via metadata caching.

    Technical Details:

    • Target Framework: netstandard2.0
    • Runtime Namespace: tik4net.Objects (Note the capital O).
  3. Understand the tik4net developer documentation structure

    master

    The Docs/ directory contains protocol ground truth for the transports implemented by tik4net. This documentation is based on live probing and reading MikroTik's own clients.

    Important Distinctions:

    • Not End-User Documentation: For usage guides and tutorials, refer to the official wiki.
    • Present Tense: Documentation describes how the router behaves now.
    • History: For reasoning, incidents, and historical context, refer to HISTORY.md or specific <doc>-history.md files.

    Key Documentation Areas:

    • Transport Findings: Details on CLI, REST API, MAC-Telnet, and WinBox behaviors.
    • WinBox Native (M2): Details on the structured M2 protocol, handler/command models, and the .jg catalog format.
    • Cross-transport: Information on protocol coverage, throughput ceilings, and the entity catalog.
  4. Understand the tik4net.samples subcommands

    master

    The sample application is divided into three distinct modes to showcase different library behaviors:

    CommandPurposeKey Behavior
    consoleRaw API interactionEchoes every word in both directions; useful for seeing exact router replies.
    torchStreaming dataDemonstrates how rows arrive on a callback and how to end a stream by cancelling the loading context.
    crudO/R MappingDemonstrates that an outgoing /set command carries only the field that changed.

    Note that the API surface remains consistent regardless of the --transport chosen (e.g., Api, Rest, Telnet, or WinboxNative).

  5. Overview of the MACTelnet Protocol

    master

    MACTelnet is a proprietary MikroTik protocol designed for terminal access over Layer 2 (MAC address). It allows for the recovery and bootstrapping of routers that do not have an IP address assigned.

    Key Specifications:

    • Transport: UDP broadcast to 255.255.255.255 on port 20561.
    • Max Packet Size: 1500 bytes.
    • Security: The protocol is not encrypted and should only be used on isolated networks.
    • Reliability: Because UDP is connectionless, clients must explicitly send an END packet to close a session; otherwise, the router will keep the login active in its active users list.
  6. Understand the MAC Layer M2 Transport

    master

    The WinboxMacM2Session provides an M2 multiplexing interface over the MAC layer.

    Key Characteristics:

    • Payload: M2 messages are carried as encrypted blobs inside PKT_DATA payloads.
    • Concurrency: It supports multiple requests in flight because the MacLayerTransport uses a retransmit buffer (a queue where the oldest packets are resent first) rather than a single slot.
    • Initialization: Like the TCP version, it performs a one-time handover on the first ReceiveNextFrame call to clear the chunk-reassembly buffer left over from the authentication phase.
    • Limitations: SupportsStaleDrain is false on the MAC channel because UDP traffic (ACKs/PINGs) is too frequent; attempting to drain stale frames would result in noise rather than clearing actual data.
  7. Manage optional (`opt`) fields and unsetting values

    master

    Optional fields in the M2 protocol require an explicit boolean flag to be sent.

    1. To set a value: You must emit the opt/not boolean before the typed value. If the flag is omitted, the router ignores the field entirely (e.g., adding a firewall rule without a src-address will succeed but create a rule matching everything).
    2. To unset a value: You must emit the boolean flag alongside the empty value. Sending only the flag is insufficient for a proper unset operation.
  8. Map RouterOS paths to tik4net classes

    master

    tik4net provides a mapping between RouterOS paths and C# classes. When interacting with the RouterOS API, you can use these classes to represent specific entities. The classes are organized into namespaces that correspond to the RouterOS hierarchy.

    Common namespaces include:

    • tik4net.Objects.CapsMan for CAPsMAN entities.
    • tik4net.Objects.Ip for IP-related configuration and monitoring.
    • tik4net.Objects.System for system-level settings like files and clock.
    • tik4net.Objects.Interface for network interfaces and bridges.
    • tik4net.Objects.Tool for diagnostic tools like ping and traceroute.
  9. Understand Request ID allocation and the Quarantine mechanism

    master

    Request IDs are single bytes (0-255), meaning the counter wraps every 256 requests. To prevent a stale reply from a previous request being incorrectly matched to a new request that happens to use the same ID, the WinboxM2Multiplexer uses a strict allocation strategy.

    Reserved and Protected IDs

    The multiplexer will never hand out an ID that is:

    • 0: Reserved for "no id".
    • Pending: Currently registered with a caller waiting for a reply.
    • Quarantined: An ID whose caller timed out or cancelled, but the router might still send a reply for it.

    The Quarantine Mechanism

    When a request times out or is cancelled, its ID is placed in a quarantine. This prevents the ID from being reused immediately.

    • Purpose: It protects against "stale replies" where a router responds to an abandoned request just as a new request takes that same ID.
    • Duration: The AbandonedIdQuarantineMs is set to 120 seconds by default. This is intentionally generous to account for slow router responses (e.g., large table continuations).
    • Recovery: If a frame arrives for a quarantined ID, the reader loop reports it via OnUnmatchedFrame and releases the ID immediately.

    Exhaustion

    If all 255 possible IDs are either pending or in quarantine, the multiplexer throws an error and the connection is considered spent, requiring a reconnect.

  10. Resolve arguments for Action invocations

    master

    When invoking an action (e.g., a doit command), arguments must be resolved against the action itself, not just the parent handler's record map.

    In scenarios where a handler contains both a read-only column and a writable action argument with the same name (e.g., 'Key Size'), the action's field definition takes precedence. Use WinboxJgCatalog.GetActionFields and WinboxFieldResolver to ensure arguments are correctly attributed to the specific action being dispatched.

    // Example of an action (doit) sharing a name with a handler field
    {name:'IPsec Key',title:'Keys',type:'map',path:[ 85,5 ],c:[
      {name:'Name',type:'string',id:'sfe0010',min:1},
      {name:'Key Size',type:'number',id:'u1',ro:1}, // list COLUMN, read-only
      {name:'Generate Key',type:'doit',cmd:1,global:1,c:[
        {name:'Name',type:'string',id:'sfe0010',min:1},
        {name:'Key Size',type:'enm',id:'u1', // ARGUMENT, writable
         values:{type:'static',map:{1024:'1024',2048:'2048',4096:'4096'}}}]}]}
  11. Understand the tik4net CLI architecture

    master

    The CLI parsing and translation logic is integrated directly into the tik4net core (namespace Tik4Net.Cli) rather than a separate package. This layer is shared across all terminal-based transport packages (tik4net.ssh, tik4net.mactelnet, and tik4net.telnet).

    Key components include:

    • CliCommandBuilder: Converts ITikCommand into CLI strings.
    • CliOutputParser: Parses as-value text into IEnumerable<ITikReSentence>.
    • CliErrorParser: Converts error text into tik4net exceptions.
    • VtStripper: Removes ANSI escape sequences (VT100) for MACTelnet and Telnet.
    • CliConnectionBase: An abstract base class that provides serialized command execution using a SemaphoreSlim to ensure only one command is processed at a time per connection.
  12. Understand the design of CLI-based terminal output parsing

    master
    The tik4net library implements ITikConnection over SSH or MACTelnet by parsing the RouterOS print as-value format. This format is machine-readable and maps 1:1 to the ITikReSentence structure used by the binary API. Because the keys and values (e.g., yes/no for booleans, address formats) are identical to the API, the tik4net.entities entity mapper works seamlessly regardless of whether the transport is the binary API or the CLI.