File: NamedPipeSocket.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (367 lines) | stat: -rw-r--r-- 11,600 bytes parent folder | download | duplicates (5)
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
//
// System.Runtime.Remoting.Channels.Ipc.Win32.NamedPipeSocket.cs
//
// Author: Robert Jordan (robertj@gmx.net)
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
//
// 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.IO;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;

namespace System.Runtime.Remoting.Channels.Ipc.Win32
{
    /// <summary>
    /// Implements a local Named Pipe socket.
    /// </summary>
    internal class NamedPipeSocket : IDisposable
    {
        IntPtr hPipe;

        /// <summary>
        /// Creates a new socket instance form the specified local Named Pipe handle.
        /// </summary>
        /// <param name="hPipe">The handle.</param>
        internal NamedPipeSocket(IntPtr hPipe)
        {
            this.hPipe = hPipe;
            this.info = new NamedPipeSocketInfo(hPipe);
        }

        ~NamedPipeSocket() 
        {
            ((IDisposable)this).Dispose();
        }

        /// <summary>
        /// Gets the NamedPipeSocketInfo of this instance.
        /// </summary>
        /// <returns></returns>
        public NamedPipeSocketInfo Info
        {
            get 
            {
                return info;
            }
        }

        NamedPipeSocketInfo info;

        /// <summary>
        /// Closes the socket.
        /// </summary>
        public void Close() 
        {
            ((IDisposable)this).Dispose();
        }

        /// <summary>
        /// Disposes the object.
        /// </summary>
        void IDisposable.Dispose()
        {
            if (hPipe != IntPtr.Zero) 
            {
                try 
                {
                    // disconnect the pipe
                    if (Info.IsServer) 
                    {
                        NamedPipeHelper.FlushFileBuffers(hPipe);
                        NamedPipeHelper.DisconnectNamedPipe(hPipe);
                    }
                }
                catch (NamedPipeException) 
                {
                }

                NamedPipeHelper.CloseHandle(hPipe);
                hPipe = IntPtr.Zero;
                GC.SuppressFinalize(this);
            }
        }

        /// <summary>
        /// Returns the stream used to send and receive data.
        /// </summary>
        /// <returns></returns>
        public Stream GetStream() 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);

            return stream == null
                ? stream = new NamedPipeStream(this, false)
                : stream;
        }

        Stream stream;

        /// <summary>
        /// Returns the stream used to send and receive data. The stream disposes
        /// the socket on close.
        /// </summary>
        /// <returns></returns>
        public Stream GetClosingStream() 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);
            
            return new NamedPipeStream(this, true);
        }

        /// <summary>
        /// Flushes the socket.
        /// </summary>
        public void Flush() 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);

            NamedPipeHelper.FlushFileBuffers(hPipe);
        }

        /// <summary>
        /// Receives the specified number of bytes from a socket into
        /// the specified offset position of the receive buffer.
        /// </summary>
        /// <param name="buffer">An array of type Byte that is the storage
        /// location for received data.</param>
        /// <param name="offset">The location in buffer to store the received data.</param>
        /// <param name="count">The number of bytes to receive.</param>
        /// <returns>The number of bytes received.</returns>
        public int Receive(byte[] buffer, int offset, int count) 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (offset < 0 || count < 0)
                throw new ArgumentOutOfRangeException("offset and/or count");
            if (buffer.Length - offset < count)
                throw new ArgumentException();

            uint read = 0;

            GCHandle gch  = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            try 
            {
                bool res = NamedPipeHelper.ReadFile(
                    hPipe,
                    Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
                    (uint) count,
                    out read,
                    IntPtr.Zero
                    );

                if (!res && read == 0) throw new NamedPipeException();

                return (int) read;
            }
            finally 
            {
                gch.Free();
            }
        }

        delegate int ReceiveMethod(byte[] buffer, int offset, int count);

        public IAsyncResult BeginReceive(byte[] buffer, int offset, int count,
            AsyncCallback callback, object state)
        {
            return new ReceiveMethod(Receive).BeginInvoke(buffer, offset, count, callback, state);
        }

        public int EndReceive(IAsyncResult asyncResult) 
        {
            AsyncResult ar = asyncResult as AsyncResult;
            return ((ReceiveMethod)ar.AsyncDelegate).EndInvoke(asyncResult);
        }

        /// <summary>
        /// Sends the specified number of bytes of data to a connected socket,
        /// starting at the specified offset.
        /// </summary>
        /// <param name="buffer">An array of type Byte that contains the data to be sent.</param>
        /// <param name="offset">The position in the data buffer at which to begin sending data. </param>
        /// <param name="count">The number of bytes to send.</param>
        /// <returns>The number of bytes sent.</returns>
        public int Send(byte[] buffer, int offset, int count) 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (offset < 0 || count < 0)
                throw new ArgumentOutOfRangeException("offset and/or count");
            if (buffer.Length - offset < count)
                throw new ArgumentException();

            uint written = 0;

            GCHandle gch  = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            try 
            {
                bool res = NamedPipeHelper.WriteFile(
                    hPipe,
                    Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
                    (uint) count,
                    out written,
                    IntPtr.Zero
                    );

                if (!res) throw new NamedPipeException();
                return (int) written;
            }
            finally 
            {
                gch.Free();
            }
        }

        delegate int SendMethod(byte[] buffer, int offset, int count);

        public IAsyncResult BeginSend(byte[] buffer, int offset, int count,
            AsyncCallback callback, object state)
        {
            return new SendMethod(Send).BeginInvoke(buffer, offset, count, callback, state);
        }

        public int EndSend(IAsyncResult asyncResult) 
        {
            AsyncResult ar = asyncResult as AsyncResult;
            return ((SendMethod)ar.AsyncDelegate).EndInvoke(asyncResult);
        }

        /// <summary>
        /// Returns the current NamedPipeSocketState of this instance.
        /// </summary>
        /// <returns></returns>
        public NamedPipeSocketState GetSocketState() 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);

            return new NamedPipeSocketState(hPipe);
        }

        /// <summary>
        /// Impersonates the client.
        /// </summary>
        public void Impersonate() 
        {
            if (hPipe == IntPtr.Zero)
                throw new ObjectDisposedException(GetType().FullName);

            if (Info.IsServer)
                if (!NamedPipeHelper.ImpersonateNamedPipeClient(hPipe))
                    throw new NamedPipeException();
        }

        /// <summary>
        /// Reverts the impersonation.
        /// </summary>
        public static bool RevertToSelf() 
        {
            return NamedPipeHelper.RevertToSelf();
        }

    }


    /// <summary>
    /// Represents local Named Pipe informations.
    /// </summary>
    internal class NamedPipeSocketInfo
    {
        public readonly int Flags;
        public readonly int OutBufferSize;
        public readonly int InBufferSize;
        public readonly int MaxInstances;

        public bool IsServer 
        {
            get 
            {
                return (Flags & NamedPipeHelper.PIPE_SERVER_END) != 0;
            }
        }

        internal NamedPipeSocketInfo(IntPtr hPipe) 
        {
            bool res = NamedPipeHelper.GetNamedPipeInfo(
                hPipe,
                out Flags,
                out OutBufferSize,
                out InBufferSize,
                out MaxInstances
                );
            
            if (!res) 
            {
                throw new NamedPipeException();
            }
        }
    }


    /// <summary>
    /// Represents local Named Pipe state informations.
    /// </summary>
    internal class NamedPipeSocketState 
    {
        public readonly int State;
        public readonly int CurrentInstances;
        public readonly int MaxCollectionCount;
        public readonly int CollectDataTimeout;
        public readonly string UserName;

        internal NamedPipeSocketState(IntPtr hPipe) 
        {
            StringBuilder userName = new StringBuilder(256);
            bool res = NamedPipeHelper.GetNamedPipeHandleState(
                hPipe,
                out State,
                out CurrentInstances,
                out MaxCollectionCount,
                out CollectDataTimeout,
                userName,
                userName.Capacity
                );
            
            if (res) 
            {
                UserName = userName.ToString();
            }
            else 
            {
                throw new NamedPipeException();
            }
        }
    }
}