-
Notifications
You must be signed in to change notification settings - Fork 7
/
RouterOSAPI.pas
694 lines (568 loc) · 19.2 KB
/
RouterOSAPI.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
{*******************************************************************************
Author: Pavel Skuratovich (aka Chupaka), Minsk, Belarus
Description: Implementation of MikroTik RouterOS API Client
Version: 1.3
E-Mail: chupaka@gmail.com
Support: http://forum.mikrotik.com/viewtopic.php?t=31555
Dependencies: Uses Ararat Synapse Library (http://synapse.ararat.cz/)
Legal issues: Copyright © by Pavel Skuratovich
This source code is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
********************************************************************************
API over TLS notes:
Added in RouterOS v6.1. Only TLS without certificate is currently supported.
Add 'ssl_openssl' to your project uses
(http://synapse.ararat.cz/doku.php/public:howto:sslplugin)
and then call TRosApiClient.SSLConnect() instead of TRosApiClient.Connect()
********************************************************************************
Version history:
1.3 June 04, 2018
Added support for RouterOS 6.43+ API login method
1.2 June 12, 2013
Added basic support for API over TLS
1.1 November 5, 2009
Delphi 2009 compatibility (thanks to Anton Ekermans for testing)
Requires Synapse Release 39
1.0 May 1, 2009
First public release
0.1 April 18, 2009
Unit was rewritten to implement database-like interface
0.0 May 10, 2008
The beginning
*******************************************************************************}
unit RouterOSAPI;
interface
uses
SysUtils, Classes, StrUtils, blcksock, synautil, synsock, synacode;
type
TRosApiWord = record
Name,
Value: AnsiString;
end;
TRosApiSentence = array of TROSAPIWord;
TRosApiClient = class;
TRosApiResult = class
private
Client: TROSAPIClient;
Tag: AnsiString;
Sentences: array of TRosApiSentence;
FTrap: Boolean;
FTrapMessage: AnsiString;
FDone: Boolean;
constructor Create;
function GetValueByName(const Name: AnsiString): AnsiString;
function GetValues: TRosApiSentence;
function GetEof: Boolean;
function GetRowsCount: Integer;
public
property ValueByName[const Name: AnsiString]: AnsiString read GetValueByName; default;
property Values: TRosApiSentence read GetValues;
function GetOne(const Wait: Boolean): Boolean;
function GetAll: Boolean;
property RowsCount: Integer read GetRowsCount;
property Eof: Boolean read GetEof;
property Trap: Boolean read FTrap;
property Done: Boolean read FDone;
procedure Next;
procedure Cancel;
end;
TRosApiClient = class
private
FNextTag: Cardinal;
FSock: TTCPBlockSocket;
FTimeout: Integer;
FLastError: AnsiString;
Sentences: array of TRosApiSentence;
function SockRecvByte(out b: Byte; const Wait: Boolean = True): Boolean;
function SockRecvBufferStr(Length: Cardinal): AnsiString;
procedure SendWord(s: AnsiString);
function RecvWord(const Wait: Boolean; out w: AnsiString): Boolean;
function RecvSentence(const Wait: Boolean; out se: TROSAPISentence): Boolean;
function GetSentenceWithTag(const Tag: AnsiString; const Wait: Boolean; out Sentence: TROSAPISentence): Boolean;
procedure ClearSentenceTag(var Sentence: TRosApiSentence);
function DoLogin(const Username, Password: AnsiString): Boolean;
public
function Connect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8728'): Boolean;
function SSLConnect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8729'): Boolean;
function Query(const Request: array of AnsiString;
const GetAllAfterQuery: Boolean): TROSAPIResult;
function Execute(const Request: array of AnsiString): Boolean;
property Timeout: Integer read FTimeout write FTimeout;
property LastError: AnsiString read FLastError;
constructor Create;
destructor Destroy; override;
procedure Disconnect;
function GetWordValueByName(Sentence: TROSAPISentence; Name: AnsiString;
RaiseErrorIfNotFound: Boolean = False): AnsiString;
end;
implementation
{******************************************************************************}
function HexToStr(hex: AnsiString): AnsiString;
const
Convert: array['0'..'f'] of SmallInt =
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15);
var
i: Integer;
begin
Result := '';
if Length(hex) mod 2 <> 0 then
raise Exception.Create('Invalid hex value') at @HexToStr;
SetLength(Result, Length(hex) div 2);
for i := 1 to Length(hex) div 2 do
begin
if not (hex[i * 2 - 1] in ['0'..'9', 'a'..'f']) or not (hex[i * 2] in ['0'..'9', 'a'..'f']) then
raise Exception.Create('Invalid hex value') at @HexToStr;
Result[i] := AnsiChar((Convert[hex[i * 2 - 1]] shl 4) + Convert[hex[i * 2]]);
end;
end;
{******************************************************************************}
constructor TRosApiResult.Create;
begin
inherited Create;
FTrap := False;
FTrapMessage := '';
FDone := False;
SetLength(Sentences, 0);
end;
{******************************************************************************}
constructor TRosApiClient.Create;
begin
inherited Create;
FNextTag := 1;
FTimeout := 30000;
FLastError := '';
FSock := TTCPBlockSocket.Create;
end;
{******************************************************************************}
destructor TRosApiClient.Destroy;
begin
FSock.Free;
inherited Destroy;
end;
{******************************************************************************}
function TRosApiClient.Connect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8728'): Boolean;
begin
FLastError := '';
FSock.CloseSocket;
FSock.LineBuffer := '';
FSock.Connect(Hostname, Port);
Result := FSock.LastError = 0;
FLastError := FSock.LastErrorDesc;
if not Result then Exit;
Result := DoLogin(Username, Password);
end;
{******************************************************************************}
function TRosApiClient.SSLConnect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8729'): Boolean;
begin
if FSock.SSL.LibName = 'ssl_none' then
begin
FLastError := 'No SSL/TLS support compiled';
Result := False;
Exit;
end;
FLastError := '';
FSock.CloseSocket;
FSock.LineBuffer := '';
FSock.Connect(Hostname, Port);
Result := FSock.LastError = 0;
FLastError := FSock.LastErrorDesc;
if not Result then Exit;
FSock.SSL.Ciphers := 'ADH';
FSock.SSL.SSLType := LT_TLSv1;
FSock.SSLDoConnect;
Result := FSock.LastError = 0;
FLastError := FSock.LastErrorDesc;
if not Result then Exit;
Result := DoLogin(Username, Password);
end;
{******************************************************************************}
function TRosApiClient.DoLogin(const Username, Password: AnsiString): Boolean;
var
Res, Res2: TRosApiResult;
begin
Result := False;
// post-6.43 login method
Res := Query(['/login', '=name=' + Username, '=password=' + Password], True);
if Res.Trap then
// login error
FSock.CloseSocket
else
if Res.Done then
begin
if High(Res.Sentences) <> -1 then
begin
// fallback to pre-6.43 login method
Res2 := Query(['/login', '=name=' + Username, '=response=00' +
StrToHex(MD5(#0 + Password + HexToStr(Res['=ret'])))], True);
if Res2.Trap then
FSock.CloseSocket
else
Result := True;
Res2.Free;
end
else
Result := True;
end
else
raise Exception.Create('Invalid response: ''' + Res.Values[0].Name + ''', expected ''!done''');
Res.Free;
end;
{******************************************************************************}
procedure TRosApiClient.Disconnect;
begin
FSock.CloseSocket;
FSock.LineBuffer := '';
end;
{******************************************************************************}
function TRosApiClient.SockRecvByte(out b: Byte; const Wait: Boolean = True): Boolean;
begin
Result := True;
if Wait then
b := FSock.RecvByte(FTimeout)
else
b := FSock.RecvByte(0);
if (FSock.LastError = WSAETIMEDOUT) and (not Wait) then
Result := False;
if (FSock.LastError = WSAETIMEDOUT) and Wait then
raise Exception.Create('Socket recv timeout in SockRecvByte');
end;
{******************************************************************************}
function TRosApiClient.SockRecvBufferStr(Length: Cardinal): AnsiString;
begin
Result := FSock.RecvBufferStr(Length, FTimeout);
if FSock.LastError = WSAETIMEDOUT then
begin
Result := '';
raise Exception.Create('Socket recv timeout in SockRecvBufferStr');
end;
end;
{******************************************************************************}
procedure TRosApiClient.SendWord(s: AnsiString);
var
l: Cardinal;
begin
l := Length(s);
if l < $80 then
FSock.SendByte(l) else
if l < $4000 then begin
l := l or $8000;
FSock.SendByte((l shr 8) and $ff);
FSock.SendByte(l and $ff); end else
if l < $200000 then begin
l := l or $c00000;
FSock.SendByte((l shr 16) and $ff);
FSock.SendByte((l shr 8) and $ff);
FSock.SendByte(l and $ff); end else
if l < $10000000 then begin
l := l or $e0000000;
FSock.SendByte((l shr 24) and $ff);
FSock.SendByte((l shr 16) and $ff);
FSock.SendByte((l shr 8) and $ff);
FSock.SendByte(l and $ff); end
else begin
FSock.SendByte($f0);
FSock.SendByte((l shr 24) and $ff);
FSock.SendByte((l shr 16) and $ff);
FSock.SendByte((l shr 8) and $ff);
FSock.SendByte(l and $ff);
end;
FSock.SendString(s);
end;
{******************************************************************************}
function TRosApiClient.Query(const Request: array of AnsiString;
const GetAllAfterQuery: Boolean): TROSAPIResult;
var
i: Integer;
begin
FLastError := '';
//Result := nil;
// if not FSock.Connected then Exit;
Result := TRosApiResult.Create;
Result.Client := Self;
Result.Tag := IntToHex(FNextTag, 4);
Inc(FNextTag);
for i := 0 to High(Request) do
SendWord(Request[i]);
SendWord('.tag=' + Result.Tag);
SendWord('');
if GetAllAfterQuery then
if not Result.GetAll then
raise Exception.Create('Cannot GetAll: ' + LastError);
end;
{******************************************************************************}
function TRosApiClient.RecvWord(const Wait: Boolean; out w: AnsiString): Boolean;
var
l: Cardinal;
b: Byte;
begin
Result := False;
if not SockRecvByte(b, Wait) then Exit;
Result := True;
l := b;
if l >= $f8 then
raise Exception.Create('Reserved control byte received, cannot proceed') else
if (l and $80) = 0 then
else
if (l and $c0) = $80 then begin
l := (l and not $c0) shl 8;
SockRecvByte(b);
l := l + b; end else
if (l and $e0) = $c0 then begin
l := (l and not $e0) shl 8;
SockRecvByte(b);
l := (l + b) shl 8;
SockRecvByte(b);
l := l + b; end else
if (l and $f0) = $e0 then begin
l := (l and not $f0) shl 8;
SockRecvByte(b);
l := (l + b) shl 8;
SockRecvByte(b);
l := (l + b) shl 8;
SockRecvByte(b);
l := l + b; end else
if (l and $f8) = $f0 then begin
SockRecvByte(b);
l := b shl 8;
SockRecvByte(b);
l := (l + b) shl 8;
SockRecvByte(b);
l := (l + b) shl 8;
SockRecvByte(b);
l := l + b;
end;
w := SockRecvBufferStr(l);
end;
{******************************************************************************}
function TRosApiClient.RecvSentence(const Wait: Boolean; out se: TROSAPISentence): Boolean;
var
p: Integer;
w: AnsiString;
begin
repeat
if RecvWord(Wait, w) then
begin
SetLength(se, 1);
se[0].Name := w;
end
else
begin
Result := False;
Exit;
end;
until w <> '';
repeat
if RecvWord(True, w) then
begin
if w = '' then
begin
Result := True;
Exit;
end
else
begin
SetLength(se, High(se) + 2);
p := PosEx('=', w, 2);
if p = 0 then
se[High(se)].Name := w
else
begin
se[High(se)].Name := Copy(w, 1, p - 1);
se[High(se)].Value := Copy(w, p + 1, Length(w) - p);
end;
end;
end
else
begin
Result := False;
Exit;
end;
until False;
end;
{******************************************************************************}
function TRosApiClient.GetSentenceWithTag(const Tag: AnsiString; const Wait: Boolean; out Sentence: TROSAPISentence): Boolean;
var
i, j: Integer;
se: TRosApiSentence;
begin
Result := False;
for i := 0 to High(Sentences) do
begin
if GetWordValueByName(Sentences[i], '.tag') = Tag then
begin
Sentence := Sentences[i];
ClearSentenceTag(Sentence);
for j := i to High(Sentences) - 1 do
Sentences[j] := Sentences[j + 1];
SetLength(Sentences, High(Sentences));
Result := True;
Exit;
end;
end;
repeat
if RecvSentence(Wait, se) then
begin
if GetWordValueByName(se, '.tag', True) = Tag then
begin
Sentence := se;
ClearSentenceTag(Sentence);
Result := True;
Exit;
end;
SetLength(Sentences, High(Sentences) + 2);
Sentences[High(Sentences)] := se;
end
else
Exit;
until False;
end;
{******************************************************************************}
procedure TRosApiClient.ClearSentenceTag(var Sentence: TRosApiSentence);
var
i, j: Integer;
begin
for i := High(Sentence) downto 0 do
if Sentence[i].Name = '.tag' then
begin
for j := i to High(Sentence) - 1 do
Sentence[j] := Sentence[j + 1];
SetLength(Sentence, High(Sentence));
end;
end;
{******************************************************************************}
function TRosApiClient.GetWordValueByName(Sentence: TROSAPISentence; Name: AnsiString;
RaiseErrorIfNotFound: Boolean = False): AnsiString;
var
i: Integer;
begin
Result := '';
for i := 1 to High(Sentence) do
if (Sentence[i].Name = '=' + Name) or (Sentence[i].Name = Name) then
begin
Result := Sentence[i].Value;
Exit;
end;
if RaiseErrorIfNotFound then
raise Exception.Create('API Word ''' + Name + ''' not found in sentence');
end;
{******************************************************************************}
function TRosApiResult.GetValueByName(const Name: AnsiString): AnsiString;
begin
if High(Sentences) = -1 then
raise Exception.Create('No values - use Get* first?')
else
Result := Client.GetWordValueByName(Sentences[0], Name);
end;
{******************************************************************************}
function TRosApiResult.GetValues: TRosApiSentence;
begin
if High(Sentences) = -1 then
raise Exception.Create('No values - use Get* first?')
else
Result := Sentences[0];
end;
{******************************************************************************}
function TRosApiResult.GetOne(const Wait: Boolean): Boolean;
begin
Client.FLastError := '';
FTrap := False;
SetLength(Sentences, 1);
Result := Client.GetSentenceWithTag(Tag, Wait, Sentences[0]);
if not Result then Exit;
if Sentences[0][0].Name = '!trap' then
begin
FTrap := True;
Client.FLastError := Self['=message'];
end;
FDone := Sentences[0][0].Name = '!done';
end;
{******************************************************************************}
function TRosApiResult.GetAll: Boolean;
var
se: TRosApiSentence;
begin
Client.FLastError := '';
FTrap := False;
repeat
Result := Client.GetSentenceWithTag(Tag, True, se);
if Result then
begin
if se[0].Name = '!trap' then
begin
FTrap := True;
if Client.FLastError <> '' then
Client.FLastError := Client.FLastError + '; ';
Client.FLastError := Client.FLastError + Client.GetWordValueByName(se, '=message');
end else
if se[0].Name = '!done' then
begin
FDone := True;
if High(se) > 0 then
begin
SetLength(Sentences, High(Sentences) + 2);
Sentences[High(Sentences)] := se;
end;
Exit;
end
else
begin
SetLength(Sentences, High(Sentences) + 2);
Sentences[High(Sentences)] := se;
end;
end;
until False;
end;
{******************************************************************************}
function TRosApiResult.GetEof: Boolean;
begin
Result := High(Sentences) = -1;
end;
{******************************************************************************}
function TRosApiResult.GetRowsCount: Integer;
begin
Result := Length(Sentences);
end;
{******************************************************************************}
procedure TRosApiResult.Next;
var
i: Integer;
begin
Client.FLastError := '';
for i := 0 to High(Sentences) - 1 do
Sentences[i] := Sentences[i + 1];
SetLength(Sentences, High(Sentences));
end;
{******************************************************************************}
procedure TRosApiResult.Cancel;
begin
if not Client.Execute(['/cancel', '=tag=' + Tag]) then
raise Exception.Create('Cannot cancel: ' + Client.LastError);
end;
{******************************************************************************}
function TRosApiClient.Execute(const Request: array of AnsiString): Boolean;
var
Res: TRosApiResult;
begin
Res := Query(Request, True);
Result := not Res.Trap;
Res.Free;
end;
{******************************************************************************}
end.