Welcome to mirror list, hosted at ThFree Co, Russian Federation.

UdpChannelBase.cs « Channels « ServiceModel « System « System.ServiceModel.Channels « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6e0f45677ef5f0d93367a14548b24bea60880393 (plain)
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
// <copyright>
// Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>

namespace System.ServiceModel.Channels
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime;
    using System.Runtime.Diagnostics;
    using System.ServiceModel.Diagnostics;
    using System.Threading;
    using System.Xml;

    internal abstract class UdpChannelBase<QueueItemType> : InputQueueChannel<QueueItemType>, IUdpReceiveHandler
        where QueueItemType : class, IDisposable
    {
        private bool cleanedUp;
        private long pendingMessagesTotalSize;
        private long maxPendingMessagesTotalSize;
        private int maxReceivedMessageSize;
        private UdpRetransmissionSettings retransmitSettings;
        private Uri via;
        
        protected UdpChannelBase(
            ChannelManagerBase channelManager, 
            MessageEncoder encoder, 
            BufferManager bufferManager,
            UdpSocket[] sockets, 
            UdpRetransmissionSettings retransmissionSettings,
            long maxPendingMessagesTotalSize, 
            EndpointAddress localAddress, 
            Uri via,
            bool isMulticast,
            int maxReceivedMessageSize)
            : base(channelManager)
        {
            Fx.Assert(encoder != null, "encoder shouldn't be null");
            Fx.Assert(bufferManager != null, "buffer manager shouldn't be null");
            Fx.Assert(sockets != null, "sendSockets can't be null");
            Fx.Assert(sockets.Length > 0, "sendSockets can't be empty");
            Fx.Assert(retransmissionSettings != null, "retransmissionSettings can't be null");
            Fx.Assert(maxPendingMessagesTotalSize >= 0, "maxPendingMessagesTotalSize must be >= 0");
            Fx.Assert(maxReceivedMessageSize > 0, "maxReceivedMessageSize must be > 0");
            Fx.Assert(localAddress != null, "localAddress can't be null");
            Fx.Assert(via != null, "via can't be null");

            this.maxPendingMessagesTotalSize = maxPendingMessagesTotalSize == UdpConstants.Defaults.DefaultMaxPendingMessagesTotalSize ? UdpConstants.Defaults.MaxPendingMessagesTotalSize : maxPendingMessagesTotalSize;
            this.Encoder = encoder;
            this.Sockets = sockets;
            this.BufferManager = bufferManager;
            this.retransmitSettings = retransmissionSettings;
            this.IsMulticast = isMulticast;
            this.DuplicateDetector = null;
            this.ReceiveManager = null;
            this.OwnsBufferManager = false;
            this.maxReceivedMessageSize = maxReceivedMessageSize;
            this.LocalAddress = localAddress;
            this.via = via;
        }

        public EndpointAddress LocalAddress
        {
            get;
            private set;
        }

        public Uri Via
        {
            get { return this.via; }
        }

        int IUdpReceiveHandler.MaxReceivedMessageSize
        {
            get { return this.maxReceivedMessageSize; }
        }

        protected abstract bool IgnoreSerializationException { get; }

        protected bool OwnsBufferManager { get; set; }

        protected DuplicateMessageDetector DuplicateDetector { get; set; }

        protected UdpSocketReceiveManager ReceiveManager { get; set; }

        protected BufferManager BufferManager
        {
            get;
            private set;
        }

        protected MessageEncoder Encoder
        {
            get;
            private set;
        }

        protected bool IsMulticast
        {
            get;
            private set;
        }

        protected UdpOutputChannel UdpOutputChannel { get; private set; }

        protected UdpSocket[] Sockets
        {
            get;
            private set;
        }

        [SuppressMessage("Microsoft.StyleCop.CSharp.ReadabilityRules", "SA1100:DoNotPrefixCallsWithBaseUnlessLocalImplementationExists", Justification = "StyleCop 4.5 does not validate this rule properly.")]
        public override T GetProperty<T>()
        {
            if (typeof(T) == typeof(IDuplexChannel))
            {
                return (T)(object)this;
            }

            T outputChannelProperty = this.UdpOutputChannel.GetProperty<T>();
            if (outputChannelProperty != null)
            {
                return outputChannelProperty;
            }

            T messageEncoderProperty = this.Encoder.GetProperty<T>();
            if (messageEncoderProperty != null)
            {
                return messageEncoderProperty;
            }

            return base.GetProperty<T>();
        }

        // returns false if the message was dropped because the max pending message count was hit.
        bool IUdpReceiveHandler.HandleDataReceived(ArraySegment<byte> data, EndPoint remoteEndpoint, int interfaceIndex, Action onMessageDequeuedCallback)
        {
            bool returnBuffer = true;
            string messageHash = null;
            Message message = null;
            bool continueReceiving = true;

            try
            {
                IPEndPoint remoteIPEndPoint = (IPEndPoint)remoteEndpoint;

                message = UdpUtility.DecodeMessage(
                    this.DuplicateDetector, 
                    this.Encoder, 
                    this.BufferManager,
                    data, 
                    remoteIPEndPoint, 
                    interfaceIndex, 
                    this.IgnoreSerializationException, 
                    out messageHash);

                if (message != null)
                {
                    // We pass in the length of the message buffer instead of the length of the message to keep track of the amount of memory that's been allocated
                    continueReceiving = this.EnqueueMessage(message, data.Array.Length, onMessageDequeuedCallback);
                    returnBuffer = !continueReceiving;
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    returnBuffer = false;
                    throw;
                }

                this.HandleReceiveException(e);
            }
            finally
            {
                if (returnBuffer)
                {
                    if (message != null)
                    {
                        if (this.DuplicateDetector != null)
                        {
                            Fx.Assert(messageHash != null, "message hash should always be available if duplicate detector is enabled");
                            this.DuplicateDetector.RemoveEntry(messageHash);
                        }

                        message.Close(); // implicitly returns the buffer
                    }
                    else
                    {
                        this.BufferManager.ReturnBuffer(data.Array);
                    }
                }
            }

            return continueReceiving;
        }

        void IUdpReceiveHandler.HandleAsyncException(Exception ex)
        {
            this.HandleReceiveException(ex);
        }

        internal virtual void HandleReceiveException(Exception ex)
        {
            this.EnqueueAndDispatch(UdpUtility.WrapAsyncException(ex), null, false);
        }

        // Since ChannelListener and channel lifetimes can be different, we need a 
        // way to transfer the socketReceiveManager and DuplicateMessageDetection 
        // objects to the channel if the listener gets closed.  If this method succeeds, then 
        // this also indicates that the bufferManager is no longer owned by the channel listener, 
        // so we have to clean that up also.
        internal bool TransferReceiveManagerOwnership(UdpSocketReceiveManager socketReceiveManager, DuplicateMessageDetector duplicateDetector)
        {
            bool success = false;
            if (this.State == CommunicationState.Opened)
            {
                lock (ThisLock)
                {
                    if (this.State == CommunicationState.Opened)
                    {
                        Fx.Assert(this.ReceiveManager == null, "ReceiveManager is already set to a non-null value");
                        Fx.Assert(this.DuplicateDetector == null, "DuplicateDetector is already set to a non-null value");

                        this.ReceiveManager = socketReceiveManager;
                        this.OwnsBufferManager = true;
                        this.ReceiveManager.SetReceiveHandler(this);
                        this.DuplicateDetector = duplicateDetector;
                        success = true;
                    }
                }
            }

            return success;
        }

        // returns false if the max pending messages total size was hit.
        internal bool EnqueueMessage(Message message, int messageBufferSize, Action messageDequeuedCallback)
        {
            Action onMessageDequeuedCallback = () =>
            {
                lock (this.ThisLock)
                {
                    this.pendingMessagesTotalSize -= messageBufferSize;
                    Fx.Assert(this.pendingMessagesTotalSize >= 0, "pendingMessagesTotalSize should not be negative.");
                }

                messageDequeuedCallback();
            };

            bool success = false;
            lock (this.ThisLock)
            {
                if (this.pendingMessagesTotalSize + messageBufferSize <= this.maxPendingMessagesTotalSize)
                {
                    message.Properties.Via = this.Via;
                    this.pendingMessagesTotalSize += messageBufferSize;
                    try
                    {
                        this.FinishEnqueueMessage(message, onMessageDequeuedCallback, false);
                        success = true;
                    }
                    finally
                    {
                        if (!success)
                        {
                            this.pendingMessagesTotalSize -= messageBufferSize;
                        }
                    }
                }
                else
                {
                    if (TD.MaxPendingMessagesTotalSizeReachedIsEnabled())
                    {
                        string messageIdString = string.Empty;
                        if (message.Headers.MessageId != null)
                        {
                            messageIdString = string.Format(CultureInfo.CurrentCulture, "'{0}' ", message.Headers.MessageId.ToString());
                        }

                        EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
                        TD.MaxPendingMessagesTotalSizeReached(eventTraceActivity, messageIdString, this.maxPendingMessagesTotalSize, typeof(TransportBindingElement).FullName);
                    }
                }
            }

            return success;
        }

        internal abstract void FinishEnqueueMessage(Message message, Action dequeuedCallback, bool canDispatchOnThisThread);

        protected virtual void AddHeadersTo(Message message)
        {
            Fx.Assert(message != null, "Message can't be null");

            if (message.Version.Addressing != AddressingVersion.None)
            {
                if (message.Headers.MessageId == null)
                {
                    message.Headers.MessageId = new UniqueId();
                }
            }
            else
            {
                if (this.retransmitSettings.Enabled == true)
                {
                    // we should only get here if some channel above us starts producing messages that don't match the encoder's message version.
                    throw FxTrace.Exception.AsError(new ProtocolException(SR.RetransmissionRequiresAddressingOnMessage(message.Version.Addressing.ToString())));
                }
            }
        }

        // Closes the channel ungracefully during error conditions.
        protected override void OnAbort()
        {
            this.Cleanup(true, TimeSpan.Zero);
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            this.OnOpen(timeout);
            return new CompletedAsyncResult(callback, state);
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            CompletedAsyncResult.End(result);
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            this.UdpOutputChannel.Open();
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new CloseAsyncResult<QueueItemType>(
                this, 
                new ChainedBeginHandler(base.OnBeginClose), 
                new ChainedEndHandler(base.OnEndClose),
                timeout, 
                callback, 
                state);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            CloseAsyncResult<QueueItemType>.End(result);
        }

        // Closes the channel gracefully during normal conditions.
        protected override void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.Cleanup(false, timeoutHelper.RemainingTime());
            base.OnClose(timeoutHelper.RemainingTime());
        }

        protected void SetOutputChannel(UdpOutputChannel udpOutputChannel)
        {
            Fx.Assert(this.UdpOutputChannel == null, "this.UdpOutputChannel must be null");
            Fx.Assert(udpOutputChannel != null, "udpOutputChannel can't be null, since SetOutputChannel should be called only once");

            this.UdpOutputChannel = udpOutputChannel;
        }

        // We're guaranteed by CommunicationObject that at most ONE of Close or BeginClose will be called once. 
        protected void Cleanup(bool aborting, TimeSpan timeout)
        {           
            if (this.cleanedUp)
            {
                return;
            }
                
            lock (ThisLock)
            {
                if (this.cleanedUp)
                {
                    return;
                }

                if (aborting)
                {
                    this.UdpOutputChannel.Abort();
                }
                else
                {
                    this.UdpOutputChannel.Close(timeout);
                }
               
                if (this.DuplicateDetector != null)
                {
                    this.DuplicateDetector.Dispose();
                }

                if (this.ReceiveManager != null)
                {
                    this.ReceiveManager.Close();
                }

                this.CleanupBufferManager();

                this.cleanedUp = true;
            }
        }

        private void CleanupBufferManager()
        {
            if (this.OwnsBufferManager)
            {
                this.BufferManager.Clear();
            }
        }

        // Control flow for async path
        // We use this mechanism to avoid initializing two async objects as logically cleanup+close is one operation. 
        // At any point in the Begin* methods, we may go async. The steps are: 
        // - Close inner UdpOutputChannel
        // - Cleanup channel
        // - Close channel
        private class CloseAsyncResult<T> : AsyncResult
            where T : class, IDisposable
        {
            private static AsyncCompletion completeCloseOutputChannelCallback = new AsyncCompletion(CompleteCloseOutputChannel);
            private static AsyncCompletion completeBaseCloseCallback = new AsyncCompletion(CompleteBaseClose);

            private UdpChannelBase<T> channel;
            private TimeoutHelper timeoutHelper;
            private ChainedBeginHandler baseBeginClose;
            private ChainedEndHandler baseEndClose;

            public CloseAsyncResult(UdpChannelBase<T> channel, ChainedBeginHandler baseBeginClose, ChainedEndHandler baseEndClose, TimeSpan timeout, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.channel = channel;
                this.baseBeginClose = baseBeginClose;
                this.baseEndClose = baseEndClose;
                this.timeoutHelper = new TimeoutHelper(timeout);

                if (this.BeginCloseOutputChannel())
                {
                    this.Complete(true);
                }
            }

            public static void End(IAsyncResult result)
            {
                AsyncResult.End<CloseAsyncResult<T>>(result);
            }

            private static bool CompleteBaseClose(IAsyncResult result)
            {
                // AsyncResult.AsyncCompletionWrapperCallback takes care of catching exceptions for us. 
                CloseAsyncResult<T> thisPtr = (CloseAsyncResult<T>)result.AsyncState;

                // We are completing the base class close operation at this point.
                thisPtr.baseEndClose(result);

                return true;
            }

            private static bool CompleteCloseOutputChannel(IAsyncResult result)
            {
                // AsyncResult.AsyncCompletionWrapperCallback takes care of catching exceptions for us. 
                CloseAsyncResult<T> thisPtr = (CloseAsyncResult<T>)result.AsyncState;

                // We are completing the base class close operation at this point.
                thisPtr.channel.UdpOutputChannel.EndClose(result);

                thisPtr.channel.Cleanup(false, thisPtr.timeoutHelper.RemainingTime());

                return thisPtr.BeginBaseClose();
            }

            private bool BeginCloseOutputChannel()
            {
                // AsyncResult.AsyncCompletionWrapperCallback takes care of catching the exceptions for us. 
                IAsyncResult result = this.channel.UdpOutputChannel.BeginClose(this.timeoutHelper.RemainingTime(), this.PrepareAsyncCompletion(completeCloseOutputChannelCallback), this);
                
                // SyncContinue calls CompleteCloseOutputChannel for us in sync case. 
                return this.SyncContinue(result);
            }

            private bool BeginBaseClose()
            {
                // AsyncResult.AsyncCompletionWrapperCallback takes care of catching the exceptions for us. 
                IAsyncResult result = this.baseBeginClose(this.timeoutHelper.RemainingTime(), this.PrepareAsyncCompletion(completeBaseCloseCallback), this);
                
                // SyncContinue calls CompleteBaseClose for us in sync case. 
                return this.SyncContinue(result);
            }
        }
    }
}