-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathSnmpMessageExtension.cs
869 lines (751 loc) · 32.7 KB
/
SnmpMessageExtension.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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
// SNMP message extension class.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
#if NETSTANDARD2_0
using System.Runtime.InteropServices;
#endif
using System.Threading;
using System.Threading.Tasks;
using Lextm.SharpSnmpLib.Security;
namespace Lextm.SharpSnmpLib.Messaging
{
/// <summary>
/// Extension methods for <see cref="ISnmpMessage"/>.
/// </summary>
public static class SnmpMessageExtension
{
/// <summary>
/// Gets the <see cref="SnmpType"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <returns></returns>
public static SnmpType TypeCode(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Pdu().TypeCode;
}
/// <summary>
/// Variables.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
public static IList<Variable> Variables(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
var code = message.TypeCode();
return code == SnmpType.Unknown ? new List<Variable>(0) : message.Scope.Pdu.Variables;
}
/// <summary>
/// Request ID.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
public static int RequestId(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Scope.Pdu.RequestId.ToInt32();
}
/// <summary>
/// Gets the message ID.
/// </summary>
/// <value>The message ID.</value>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <remarks>For v3, message ID is different from request ID. For v1 and v2c, they are the same.</remarks>
public static int MessageId(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Header == Header.Empty ? message.RequestId() : message.Header.MessageId;
}
/// <summary>
/// PDU.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pdu")]
public static ISnmpPdu Pdu(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Scope.Pdu;
}
/// <summary>
/// Community name.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
public static OctetString Community(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Parameters.UserName;
}
#region sync methods
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
public static void Send(this ISnmpMessage message, EndPoint manager)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
var code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
using (var socket = manager.GetSocket())
{
message.Send(manager, socket);
}
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
/// <param name="socket">The socket.</param>
public static void Send(this ISnmpMessage message, EndPoint manager, Socket socket)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
var code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
var bytes = message.ToBytes();
socket.SendTo(bytes, 0, bytes.Length, SocketFlags.None, manager);
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Port number.</param>
/// <param name="registry">User registry.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry)
{
// TODO: make more usage of UserRegistry.
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
var code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (var socket = receiver.GetSocket())
{
return request.GetResponse(timeout, receiver, registry, socket);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Port number.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
var code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (var socket = receiver.GetSocket())
{
return request.GetResponse(timeout, receiver, socket);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
var registry = new UserRegistry();
if (request.Version == VersionCode.V3)
{
registry.Add(request.Parameters.UserName, request.Privacy);
}
return request.GetResponse(timeout, receiver, registry, udpSocket);
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <param name="registry">The user registry.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
var requestCode = request.TypeCode();
if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
}
var bytes = request.ToBytes();
var bufSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
var reply = new byte[bufSize];
// Whatever you change, try to keep the Send and the Receive close to each other.
udpSocket.SendTo(bytes, receiver);
udpSocket.ReceiveTimeout = timeout;
int count;
try
{
count = udpSocket.Receive(reply, 0, bufSize, SocketFlags.None);
}
catch (SocketException ex)
{
// IMPORTANT: Mono behavior.
if (IsRunningOnMono && ex.SocketErrorCode == SocketError.WouldBlock)
{
throw TimeoutException.Create(receiver.Address, timeout);
}
if (ex.SocketErrorCode == SocketError.TimedOut)
{
throw TimeoutException.Create(receiver.Address, timeout);
}
throw;
}
// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
var response = MessageFactory.ParseMessages(reply, 0, count, registry)[0];
var responseCode = response.TypeCode();
if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
{
var requestId = request.MessageId();
var responseId = response.MessageId();
if (responseId != requestId)
{
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
}
return response;
}
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
}
#endregion
#region async methods
#if NET471
/// <summary>
/// Ends a pending asynchronous read.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="asyncResult">An <see cref="IAsyncResult"/> that stores state information and any user defined data for this asynchronous operation.</param>
/// <returns></returns>
[Obsolete("Please use GetResponseAsync and await on it.")]
public static ISnmpMessage EndGetResponse(this ISnmpMessage request, IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
var ar = (SnmpMessageAsyncResult)asyncResult;
var s = ar.WorkSocket;
var count = s.EndReceive(ar.Inner);
// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
var response = MessageFactory.ParseMessages(ar.GetBuffer(), 0, count, ar.Users)[0];
var responseCode = response.TypeCode();
if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
{
var requestId = request.MessageId();
var responseId = response.MessageId();
if (responseId != requestId)
{
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), ar.Receiver.Address);
}
return response;
}
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), ar.Receiver.Address);
}
/// <summary>
/// Begins to asynchronously send an <see cref="ISnmpMessage"/> to an <see cref="IPEndPoint"/>.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Agent.</param>
/// <param name="registry">The user registry.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <param name="callback">The callback.</param>
/// <param name="state">The state object.</param>
/// <returns></returns>
[Obsolete("Please use GetResponseAsync and await on it.")]
public static IAsyncResult BeginGetResponse(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket, AsyncCallback callback, object state)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
var requestCode = request.TypeCode();
if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
}
// Whatever you change, try to keep the Send and the Receive close to each other.
udpSocket.SendTo(request.ToBytes(), receiver);
var bufferSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
var buffer = new byte[bufferSize];
// https://sharpsnmplib.codeplex.com/workitem/7234
if (callback != null)
{
AsyncCallback wrapped = callback;
callback = asyncResult =>
{
var result = new SnmpMessageAsyncResult(asyncResult, udpSocket, registry, receiver, buffer);
wrapped(result);
};
}
var ar = udpSocket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, callback, state);
return new SnmpMessageAsyncResult(ar, udpSocket, registry, receiver, buffer);
}
#endif
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
public static async Task SendAsync(this ISnmpMessage message, EndPoint manager)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
var code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
using (var socket = manager.GetSocket())
{
await message.SendAsync(manager, socket).ConfigureAwait(false);
}
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
/// <param name="socket">The socket.</param>
public static async Task SendAsync(this ISnmpMessage message, EndPoint manager, Socket socket)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
var code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
var buffer = new ArraySegment<byte>(message.ToBytes());
await socket.SendToAsync(buffer, SocketFlags.None, manager);
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Port number.</param>
/// <param name="registry">User registry.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry)
{
// TODO: make more usage of UserRegistry.
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
var code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (var socket = receiver.GetSocket())
{
return await request.GetResponseAsync(receiver, registry, socket).ConfigureAwait(false);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Port number.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
var code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (var socket = receiver.GetSocket())
{
return await request.GetResponseAsync(receiver, socket).ConfigureAwait(false);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
var registry = new UserRegistry();
if (request.Version == VersionCode.V3)
{
registry.Add(request.Parameters.UserName, request.Privacy);
}
return await request.GetResponseAsync(receiver, registry, udpSocket).ConfigureAwait(false);
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <param name="registry">The user registry.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
var requestCode = request.TypeCode();
if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
}
var bytes = request.ToBytes();
var bufSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
// Whatever you change, try to keep the Send and the Receive close to each other.
var buffer = new ArraySegment<byte>(bytes);
await udpSocket.SendToAsync(buffer, SocketFlags.None, receiver ?? throw new ArgumentNullException(nameof(receiver)));
int count;
byte[] reply = new byte[bufSize];
// IMPORTANT: follow http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx
var remoteAddress = udpSocket.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any;
EndPoint remote = new IPEndPoint(remoteAddress, 0);
try
{
var result = await udpSocket.ReceiveMessageFromAsync(new ArraySegment<byte>(reply), SocketFlags.None, remote);
count = result.ReceivedBytes;
}
catch (SocketException ex)
{
// IMPORTANT: Mono behavior (https://bugzilla.novell.com/show_bug.cgi?id=599488)
if (IsRunningOnMono && ex.SocketErrorCode == SocketError.WouldBlock)
{
throw TimeoutException.Create(receiver.Address, 0);
}
if (ex.SocketErrorCode == SocketError.TimedOut)
{
throw TimeoutException.Create(receiver.Address, 0);
}
throw;
}
// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
var response = MessageFactory.ParseMessages(reply, 0, count, registry)[0];
var responseCode = response.TypeCode();
if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
{
var requestId = request.MessageId();
var responseId = response.MessageId();
if (responseId != requestId)
{
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
}
return response;
}
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
}
#endregion
/// <summary>
/// Tests if running on Mono.
/// </summary>
/// <returns></returns>
public static bool IsRunningOnMono
{
get { return Type.GetType("Mono.Runtime") != null; }
}
/// <summary>
/// Gets a value indicating whether it is
/// running on Windows.
/// </summary>
/// <value><c>true</c> if is running on Windows; otherwise, <c>false</c>.</value>
public static bool IsRunningOnWindows
{
get
{
#if NET471
return !IsRunningOnMono;
#elif NETSTANDARD2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#else
return false;
#endif
}
}
/// <summary>
/// Gets a value indicating whether it is running on macOS.
/// </summary>
/// <value><c>true</c> if is running on macOS; otherwise, <c>false</c>.</value>
public static bool IsRunningOnMac
{
get
{
#if NET471
return IsRunningOnMono;
#elif NETSTANDARD2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#else
return false;
#endif
}
}
/// <summary>
/// Gets a value indicating whether it is running on iOS.
/// </summary>
/// <value><c>true</c> if is running on iOS; otherwise, <c>false</c>.</value>
public static bool IsRunningOnIOS
{
get
{
#if NET471
return false;
#elif NETSTANDARD2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#elif XAMARINIOS1_0
return true;
#else
return false;
#endif
}
}
/// <summary>
/// Packs up the <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="length">The length bytes.</param>
/// <returns></returns>
internal static Sequence PackMessage(this ISnmpMessage message, byte[] length)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return ByteTool.PackMessage(
length,
message.Version,
message.Header,
message.Parameters,
message.Privacy.GetScopeData(message.Header, message.Parameters, message.Scope.GetData(message.Version)));
}
private sealed class SnmpMessageAsyncResult : IAsyncResult
{
private readonly byte[] _buffer;
public SnmpMessageAsyncResult(IAsyncResult inner, Socket socket, UserRegistry users, IPEndPoint receiver, byte[] buffer)
{
_buffer = buffer;
WorkSocket = socket;
Users = users;
Receiver = receiver;
Inner = inner;
}
public IAsyncResult Inner { get; private set; }
public Socket WorkSocket { get; private set; }
public UserRegistry Users { get; private set; }
public byte[] GetBuffer()
{
return _buffer;
}
public IPEndPoint Receiver { get; private set; }
public bool IsCompleted
{
get { return Inner.IsCompleted; }
}
public WaitHandle AsyncWaitHandle
{
get { return Inner.AsyncWaitHandle; }
}
public object AsyncState
{
get { return Inner.AsyncState; }
}
public bool CompletedSynchronously
{
get { return Inner.CompletedSynchronously; }
}
}
}
}