-
Notifications
You must be signed in to change notification settings - Fork 92
/
ProgramExamples.cs
369 lines (321 loc) · 14.4 KB
/
ProgramExamples.cs
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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using tik4net.Api;
using tik4net.Objects;
using tik4net.Objects.Ip;
using tik4net.Objects.Ip.Dns;
using tik4net.Objects.Ip.Firewall;
using tik4net.Objects.Queue;
using tik4net.Objects.System;
namespace tik4net.examples
{
class ProgramExamples
{
static void Main(string[] args)
{
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
connection.OnReadRow += Connection_OnReadRow; // logging commands to cosole
connection.OnWriteRow += Connection_OnWriteRow; // logging commands to cosole
connection.Open(ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]);
//------------------------------------------------
// LOW LEVEL API (hint: uncomment any example call and debug)
Identity(connection);
Torch(connection);
Log(connection);
//-------------------------------------------------
// HIGHLEVEL API (hint: uncomment any example call and debug)
PrintAddressList(connection);
CreateOrUpdateAddressList(connection);
PrintAddressList(connection);
CreateOrUpdateAddressList(connection);
PrintAddressList(connection);
DeleteAddressList(connection);
PrintAddressList(connection);
PrintAddressList(connection);
CreateOrUpdateAddressListMulti(connection);
PrintAddressList(connection);
CreateOrUpdateAddressListMulti(connection);
PrintAddressList(connection);
DeleteAddressListMulti(connection);
PrintAddressList(connection);
PrintIpAddresses(connection);
PrintSystemResource(connection);
ModifyIpAccounting(connection);
AddFirewalFilter(connection);
DhcpClientRelease(connection);
DnsCachePrint(connection);
//---------------------------------------------------------
// Advanced merge support (hint: uncomment any example call and debug)
QueueTreeMerge(connection);
FirewallMangleMerge(connection);
Console.WriteLine("Finito - press ENTER");
Console.ReadLine();
}
}
private static void Connection_OnWriteRow(object sender, TikConnectionCommCallbackEventArgs args)
{
Console.BackgroundColor = ConsoleColor.Magenta;
Console.WriteLine(">" + args.Word);
Console.BackgroundColor = ConsoleColor.Black;
}
private static void Connection_OnReadRow(object sender, TikConnectionCommCallbackEventArgs args)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.WriteLine("<" + args.Word);
Console.BackgroundColor = ConsoleColor.Black;
}
private static void Identity(ITikConnection connection)
{
ITikCommand cmd = connection.CreateCommand("/system/identity/print");
var identity = cmd.ExecuteScalar(); //cmd.ExecuteSIngleRow()
Console.WriteLine("Identity: " + /*identity.GetResponseField("name")*/ identity);
Console.WriteLine("Press ENTER");
Console.ReadLine();
}
private static void Torch(ITikConnection connection)
{
ITikCommand torchCmd = connection.CreateCommand("/tool/torch",
connection.CreateParameter("interface", "ether1"),
connection.CreateParameter("port", "any"),
connection.CreateParameter("src-address", "0.0.0.0/0"),
connection.CreateParameter("dst-address", "0.0.0.0/0")
);
torchCmd.ExecuteAsync(response =>
{
Console.WriteLine("Row: " + response.GetResponseField("tx"));
});
Console.WriteLine("Press ENTER");
Console.ReadLine();
torchCmd.CancelAndJoin();
}
private static void Log(ITikConnection connection)
{
var logs = connection.LoadList<Log>();
foreach (Log log in logs)
{
Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message);
}
}
const string listName = "TEST_LIST";
const string ipAddress = "192.168.1.1";
const string ipAddress2 = "192.168.1.2";
private static void PrintAddressList(ITikConnection connection)
{
var addressLists = connection.LoadList<FirewallAddressList>(
connection.CreateParameter("list", listName));
foreach (FirewallAddressList addressList in addressLists)
{
Console.WriteLine("{0}{1}: {2} {3} ({4})", addressList.Disabled ? "X" : " ", addressList.Dynamic ? "D" : " ", addressList.Address, addressList.List, addressList.Comment);
}
}
private static void CreateOrUpdateAddressList(ITikConnection connection)
{
var existingAddressList = connection.LoadList<FirewallAddressList>(
connection.CreateParameter("list", listName),
connection.CreateParameter("address", ipAddress)).SingleOrDefault();
if (existingAddressList == null)
{
//Create
var newAddressList = new FirewallAddressList()
{
Address = ipAddress,
List = listName,
};
connection.Save(newAddressList);
}
else
{
//Update
existingAddressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();
connection.Save(existingAddressList);
}
}
private static void DeleteAddressList(ITikConnection connection)
{
var existingAddressList = connection.LoadList<FirewallAddressList>(
connection.CreateParameter("list", listName),
connection.CreateParameter("address", ipAddress)).SingleOrDefault();
if (existingAddressList != null)
connection.Delete(existingAddressList);
}
private static void CreateOrUpdateAddressListMulti(ITikConnection connection)
{
var existingAddressList = connection.LoadList<FirewallAddressList>(
connection.CreateParameter("list", listName)).ToList();
var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list
if (existingAddressList.Count() <= 0)
{
//Create (just in memory)
existingAddressList.Add(
new FirewallAddressList()
{
Address = ipAddress,
List = listName,
});
existingAddressList.Add(
new FirewallAddressList()
{
Address = ipAddress2,
List = listName,
});
}
else
{
//Update (just in memory)
foreach (var addressList in existingAddressList)
{
addressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();
}
}
//save differences into mikrotik (existingAddressList=modified, listClonedBackup=unmodified)
connection.SaveListDifferences(existingAddressList, listClonedBackup);
}
private static void DeleteAddressListMulti(ITikConnection connection)
{
var existingAddressList = connection.LoadList<FirewallAddressList>(
connection.CreateParameter("list", listName)).ToList();
var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list
existingAddressList.Clear();
//save differences into mikrotik (existingAddressList=modified, listClonedBackup=unmodified)
connection.SaveListDifferences(existingAddressList, listClonedBackup);
}
private static void PrintIpAddresses(ITikConnection connection)
{
var ipAddresses = connection.LoadList<IpAddress>();
foreach(var addr in ipAddresses)
{
Console.WriteLine(addr.EntityToString());
}
}
private static void PrintSystemResource(ITikConnection connection)
{
var sysRes = connection.LoadSingle<SystemResource>();
Console.WriteLine(sysRes.EntityToString());
}
private static void QueueTreeMerge(ITikConnection connection)
{
var original = connection.LoadAll<QueueTree>().Where(q=> q.Name == "Q1" || q.Name == "Q2" || q.Name.StartsWith("Q3"));
string unique = Guid.NewGuid().ToString();
List<QueueTree> expected = new List<QueueTree>()
{
new QueueTree() { Name = "Q1", Parent = "global", PacketMark = "PM1" },
new QueueTree() { Name = "Q2", Parent = "global", PacketMark = "PM2", Comment = unique }, //always update
new QueueTree() { Name = "Q3 " + unique, Parent = "global", PacketMark = "PM3" }, // always insert + delete from previous run
};
//Merge with Name as key - can not save via SaveListDifferences because all items in 'expected' are new (.id=null) => insert will be done, not CUD
connection.CreateMerge(expected, original)
.WithKey(queue => queue.Name)
.Field(q => q.Parent)
.Field(q => q.PacketMark)
.Field(q => q.Comment)
.Save();
}
private static void FirewallMangleMerge(ITikConnection connection)
{
//manage just subset before rules marked with comment =START= and =END=
//Create subset boundaries if not present
const string startComment = "=START=";
const string endComment = "=END=";
var startMangle = connection.LoadSingleOrDefault<FirewallMangle>(connection.CreateParameter("comment", startComment));
if (startMangle == null)
{
startMangle = new FirewallMangle()
{
Chain = "forward",
Action = FirewallMangle.ActionType.Passthrough,
Comment = startComment,
Disabled = true,
};
connection.Save(startMangle);
};
var endMangle = connection.LoadSingleOrDefault<FirewallMangle>(connection.CreateParameter("comment", endComment));
if (endMangle == null)
{
endMangle = new FirewallMangle()
{
Chain = "forward",
Action = FirewallMangle.ActionType.Passthrough,
Comment = endComment,
Disabled = true,
};
connection.Save(endMangle);
};
//Merge subset between boundaries
string unique = Guid.NewGuid().ToString();
List<FirewallMangle> original = connection.LoadAll<FirewallMangle>().SkipWhile(m=>m.Comment != startComment).TakeWhile(m=>m.Comment != endComment)
.Concat(new List<FirewallMangle> { endMangle})
.ToList(); //just subset between =START= and =END= (not very elegant but functional and short ;-) )
List<FirewallMangle> expected = new List<FirewallMangle>();
expected.Add(startMangle);
expected.Add(new FirewallMangle()
{
Chain = "forward",
SrcAddress = "192.168.1.1",
Action = FirewallMangle.ActionType.MarkPacket,
NewPacketMark = "mark-001",
Passthrough = false,
});
expected.Add(new FirewallMangle()
{
Chain = "forward",
SrcAddress = "192.168.1.2",
Action = FirewallMangle.ActionType.MarkPacket,
NewPacketMark = "mark-002" + "-" + unique,
Passthrough = false,
});
expected.Add(new FirewallMangle()
{
Chain = "forward",
SrcAddress = "192.168.1.3",
Action = FirewallMangle.ActionType.MarkPacket,
NewPacketMark = "mark-003",
Passthrough = false,
Comment = unique,
});
expected.Add(endMangle);
connection.CreateMerge(expected, original)
.WithKey(mangle => mangle.SrcAddress + ":" + mangle.Comment) //Use src-address as key
.Field(q => q.Chain)
.Field(q => q.SrcAddress) //Do not forget include also key fields !!!
.Field(q => q.Action)
.Field(q => q.NewPacketMark)
.Field(q => q.Passthrough)
.Field(q => q.Comment)
.Save();
}
private static void ModifyIpAccounting(ITikConnection connection)
{
var accounting = connection.LoadSingle<IpAccounting>();
accounting.Threshold = 257;
connection.Save(accounting);
}
private static void AddFirewalFilter(ITikConnection connection)
{
var firewallFilter = new FirewallFilter()
{
Chain = FirewallFilter.ChainType.Forward,
Action = FirewallFilter.ActionType.Accept,
};
connection.Save(firewallFilter);
var loaded = connection.LoadAll<FirewallFilter>().First();
loaded.Comment = "TEST";
connection.Save(loaded);
}
private static void DhcpClientRelease(ITikConnection connection)
{
connection.LoadAll<IpDhcpClient>().First().Release(connection);
}
private static void DnsCachePrint(ITikConnection connection)
{
var cache = connection.LoadAll<DnsCache>();
foreach(var c in cache)
{
Console.WriteLine(c.EntityToString());
}
}
}
}