File: TdsComm.cs

package info (click to toggle)
mono 1.2.2.1-1etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 142,720 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,327; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (596 lines) | stat: -rw-r--r-- 15,341 bytes parent folder | download | duplicates (2)
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
//
// Mono.Data.Tds.Protocol.TdsComm.cs
//
// Author:
//   Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) 2002 Tim Coleman
//

//
// 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.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Mono.Data.Tds.Protocol {
        internal sealed class TdsComm
	{
		#region Fields

		NetworkStream stream;
		int packetSize;
		TdsPacketType packetType = TdsPacketType.None;
		Encoding encoder;

		string dataSource;
		int commandTimeout;
		int connectionTimeout;

		byte[] outBuffer;
		int outBufferLength;
		int nextOutBufferIndex = 0;

		byte[] inBuffer;
		int inBufferLength;
		int inBufferIndex = 0;

		static int headerLength = 8;

		byte[] tmpBuf = new byte[8];
		byte[] resBuffer = new byte[256];

		int packetsSent = 0;
		int packetsReceived = 0;

		Socket socket;
		TdsVersion tdsVersion;

		ManualResetEvent connected = new ManualResetEvent (false);
		
		#endregion // Fields
		
		#region Constructors

		[MonoTODO ("Fix when asynchronous socket connect works on Linux.")]		
		public TdsComm (string dataSource, int port, int packetSize, int timeout, TdsVersion tdsVersion)
		{
			this.packetSize = packetSize;
			this.tdsVersion = tdsVersion;
			this.dataSource = dataSource;
			this.connectionTimeout = timeout;

			outBuffer = new byte[packetSize];
			inBuffer = new byte[packetSize];

			outBufferLength = packetSize;
			inBufferLength = packetSize;

			IPEndPoint endPoint;
			
			try {
				socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				IPHostEntry hostEntry = Dns.Resolve (dataSource);
				endPoint = new IPEndPoint (hostEntry.AddressList [0], port);

				// This replaces the code below for now
				socket.Connect (endPoint);

				/*
				  FIXME: Asynchronous socket connection doesn't work right on linux, so comment 
				  this out for now.  This *does* do the right thing on windows

				  connected.Reset ();
				  IAsyncResult asyncResult = socket.BeginConnect (endPoint, new AsyncCallback (ConnectCallback), socket);

				  if (timeout > 0 && !connected.WaitOne (new TimeSpan (0, 0, timeout), true))
				  throw Tds.CreateTimeoutException (dataSource, "Open()");
				  else if (timeout > 0 && !connected.WaitOne ())
				  throw Tds.CreateTimeoutException (dataSource, "Open()");
				*/

				stream = new NetworkStream (socket);
			} catch (SocketException e) {
				throw new TdsInternalException ("Server does not exist or connection refused.", e);
			}
		}
		
		#endregion // Constructors
		
		#region Properties

		public int CommandTimeout {
			get { return commandTimeout; }
			set { commandTimeout = value; }
		}

		internal Encoding Encoder {
			get { return encoder; }
			set { encoder = value; }
		}
		
		public int PacketSize {
			get { return packetSize; }
			set { packetSize = value; }
		}
		
		#endregion // Properties
		
		#region Methods

		public byte[] Swap(byte[] toswap) {
			byte[] ret = new byte[toswap.Length];
			for(int i = 0; i < toswap.Length; i++)
				ret [toswap.Length - i - 1] = toswap[i];

			return ret;
		}
		public void Append (object o)
		{
			switch (o.GetType ().ToString ()) {
			case "System.Byte":
				Append ((byte) o);
				return;
			case "System.Byte[]":
				Append ((byte[]) o);
				return;
			case "System.Int16":
				Append ((short) o);
				return;
			case "System.Int32":
				Append ((int) o);
				return;
			case "System.String":
				Append ((string) o);
				return;
			case "System.Double":
				Append ((double) o);
				return;
			case "System.Int64":
				Append ((long) o);
				return;
			}
		}

		public void Append (byte b)
		{
			if (nextOutBufferIndex == outBufferLength) {
				SendPhysicalPacket (false);
				nextOutBufferIndex = headerLength;
			}
			Store (nextOutBufferIndex, b);
			nextOutBufferIndex++;
		}	
		
		public void Append (byte[] b)
		{
			Append (b, b.Length, (byte) 0);
		}		

		public void Append (byte[] b, int len, byte pad)
		{
			int i = 0;
			for ( ; i < b.Length && i < len; i++)
			    Append (b[i]);

			for ( ; i < len; i++)
			    Append (pad);
		}	

		public void Append (short s)
		{
			if(!BitConverter.IsLittleEndian)
				Append (Swap (BitConverter.GetBytes(s)));
			else 
				Append (BitConverter.GetBytes (s));
		}

		public void Append (int i)
		{
			if(!BitConverter.IsLittleEndian)
				Append (Swap (BitConverter.GetBytes(i)));
			else
				Append (BitConverter.GetBytes (i));
		}

		public void Append (string s)
		{
			if (tdsVersion < TdsVersion.tds70) 
				Append (encoder.GetBytes (s));
			else 
				foreach (char c in s)
					if(!BitConverter.IsLittleEndian)
						Append (Swap (BitConverter.GetBytes (c)));
					else
						Append (BitConverter.GetBytes (c));
		}	

		// Appends with padding
		public byte[] Append (string s, int len, byte pad)
		{
			if (s == null)
				return new byte[0];

			byte[] result = encoder.GetBytes (s);
			Append (result, len, pad);
			return result;
		}

		public void Append (double value)
		{
			Append (BitConverter.DoubleToInt64Bits (value));
		}

		public void Append (long l)
		{
			if (tdsVersion < TdsVersion.tds70) {
				Append ((byte) (((byte) (l >> 56)) & 0xff));
				Append ((byte) (((byte) (l >> 48)) & 0xff));
				Append ((byte) (((byte) (l >> 40)) & 0xff));
				Append ((byte) (((byte) (l >> 32)) & 0xff));
				Append ((byte) (((byte) (l >> 24)) & 0xff));
				Append ((byte) (((byte) (l >> 16)) & 0xff));
				Append ((byte) (((byte) (l >> 8)) & 0xff));
				Append ((byte) (((byte) (l >> 0)) & 0xff));
			}
			else 
				if (!BitConverter.IsLittleEndian)
					Append (Swap (BitConverter.GetBytes (l)));
				else
					Append (BitConverter.GetBytes (l));
		}

		public void Close ()
		{
			stream.Close ();
		}

		private void ConnectCallback (IAsyncResult ar)
		{
			Socket s = (Socket) ar.AsyncState;
			if (Poll (s, connectionTimeout, SelectMode.SelectWrite)) {
				socket.EndConnect (ar);
				connected.Set ();
			}
                }

		public byte GetByte ()
		{
			byte result;

			if (inBufferIndex >= inBufferLength) {
				// out of data, read another physical packet.
				GetPhysicalPacket ();
			}

			result = inBuffer[inBufferIndex++];
			return result;
		}

		public byte[] GetBytes (int len, bool exclusiveBuffer)
		{
			byte[] result = null;
			int i;

			// Do not keep an internal result buffer larger than 16k.
			// This would unnecessarily use up memory.
			if (exclusiveBuffer || len > 16384)
				result = new byte[len];
			else
			{
				if (resBuffer.Length < len)
					resBuffer = new byte[len];
				result = resBuffer;
			}

			for (i = 0; i<len; )
			{
				if (inBufferIndex >= inBufferLength)
					GetPhysicalPacket ();

				int avail = inBufferLength - inBufferIndex;
				avail = avail>len-i ? len-i : avail;

				System.Array.Copy (inBuffer, inBufferIndex, result, i, avail);
				i += avail;
				inBufferIndex += avail;
			}

			return result;
		}

		public string GetString (int len)
		{
			if (tdsVersion == TdsVersion.tds70) 
				return GetString (len, true);
			else
				return GetString (len, false);
		}

		public string GetString (int len, bool wide)
		{
			if (wide) {
				char[] chars = new char[len];
				for (int i = 0; i < len; ++i) {
					int lo = ((byte) GetByte ()) & 0xFF;
					int hi = ((byte) GetByte ()) & 0xFF;
					chars[i] = (char) (lo | ( hi << 8));
				}
				return new String (chars);
			}
			else {
				byte[] result = new byte[len];
				Array.Copy (GetBytes (len, false), result, len);
				return (encoder.GetString (result));
			}
		}

		public int GetNetShort ()
		{
			byte[] tmp = new byte[2];
			tmp[0] = GetByte ();
			tmp[1] = GetByte ();
			return Ntohs (tmp, 0);
		}

		public short GetTdsShort ()
		{
			byte[] input = new byte[2];

			for (int i = 0; i < 2; i += 1)
				input[i] = GetByte ();
			if(!BitConverter.IsLittleEndian)
				return (BitConverter.ToInt16 (Swap (input), 0));
			else
				return (BitConverter.ToInt16 (input, 0));
		}


		public int GetTdsInt ()
		{
			byte[] input = new byte[4];
			for (int i = 0; i < 4; i += 1)
				input[i] = GetByte ();
			if(!BitConverter.IsLittleEndian)
				return (BitConverter.ToInt32 (Swap (input), 0));
			else
				return (BitConverter.ToInt32 (input, 0));
		}

		public long GetTdsInt64 ()
		{
			byte[] input = new byte[8];
			for (int i = 0; i < 8; i += 1)
				input[i] = GetByte ();
			if(!BitConverter.IsLittleEndian)
				return (BitConverter.ToInt64 (Swap (input), 0));
			else
				return (BitConverter.ToInt64 (input, 0));
		}

		private void GetPhysicalPacket ()
		{
                        int dataLength = GetPhysicalPacketHeader ();
                        GetPhysicalPacketData (dataLength);
		}

                private int GetPhysicalPacketHeader ()
                {
                        int nread = 0;
                                                
			// read the header
			while (nread < 8)
				nread += stream.Read (tmpBuf, nread, 8 - nread);

			TdsPacketType packetType = (TdsPacketType) tmpBuf[0];
			if (packetType != TdsPacketType.Logon && packetType != TdsPacketType.Query && packetType != TdsPacketType.Reply) 
			{
				throw new Exception (String.Format ("Unknown packet type {0}", tmpBuf[0]));
			}

			// figure out how many bytes are remaining in this packet.
			int len = Ntohs (tmpBuf, 2) - 8;

			if (len >= inBuffer.Length) 
				inBuffer = new byte[len];

			if (len < 0) {
				throw new Exception (String.Format ("Confused by a length of {0}", len));
			}
                        
                        return len;

                }
                
                private void GetPhysicalPacketData (int length)
                {
                        // now get the data
			int nread = 0;
			while (nread < length) {
				nread += stream.Read (inBuffer, nread, length - nread);
			}

			packetsReceived++;

			// adjust the bookkeeping info about the incoming buffer
			inBufferLength = length;
			inBufferIndex = 0;
                }
                

		private static int Ntohs (byte[] buf, int offset)
		{
			int lo = ((int) buf[offset + 1] & 0xff);
			int hi = (((int) buf[offset] & 0xff ) << 8);

			return hi | lo;
			// return an int since we really want an _unsigned_
		}		

		public byte Peek ()
		{
			// If out of data, read another physical packet.
			if (inBufferIndex >= inBufferLength)
				GetPhysicalPacket ();

			return inBuffer[inBufferIndex];
		}

		public bool Poll (int seconds, SelectMode selectMode)
		{
			return Poll (socket, seconds, selectMode);
		}

		private bool Poll (Socket s, int seconds, SelectMode selectMode)
		{
			long uSeconds = seconds * 1000000;
			bool bState = false;

			while (uSeconds > (long) Int32.MaxValue) {
				bState = s.Poll (Int32.MaxValue, selectMode);
				if (bState) 
					return true;
				uSeconds -= Int32.MaxValue;
			}
			return s.Poll ((int) uSeconds, selectMode);
		}

		internal void ResizeOutBuf (int newSize)
		{
			if (newSize != outBufferLength) {
				byte[] newBuf = new byte [newSize];
				Array.Copy (outBuffer, 0, newBuf, 0, newSize);
				outBufferLength = newSize;
				outBuffer = newBuf;
			}
		}

		public void SendPacket ()
		{
			SendPhysicalPacket (true);
			nextOutBufferIndex = 0;
			packetType = TdsPacketType.None;
		}
		
		private void SendPhysicalPacket (bool isLastSegment)
		{
			if (nextOutBufferIndex > headerLength || packetType == TdsPacketType.Cancel) {
				// packet type
				Store (0, (byte) packetType);
				Store (1, (byte) (isLastSegment ? 1 : 0));
				Store (2, (short) nextOutBufferIndex );
				Store (4, (byte) 0);
				Store (5, (byte) 0);
				Store (6, (byte) (tdsVersion == TdsVersion.tds70 ? 0x1 : 0x0));
				Store (7, (byte) 0);

				stream.Write (outBuffer, 0, nextOutBufferIndex);
				stream.Flush ();
				packetsSent++;
			}
		}
		
		public void Skip (long i)
		{
			for ( ; i > 0; i--)
				GetByte ();
		}

		public void StartPacket (TdsPacketType type)
		{
			if (type != TdsPacketType.Cancel && inBufferIndex != inBufferLength)
				inBufferIndex = inBufferLength;

			packetType = type;
			nextOutBufferIndex = headerLength;
		}

		private void Store (int index, byte value)
		{
			outBuffer[index] = value;
		}		

		private void Store (int index, short value)
		{
			outBuffer[index] = (byte) (((byte) (value >> 8)) & 0xff);
			outBuffer[index + 1] = (byte) (((byte) (value >> 0)) & 0xff);
		}

		#endregion // Methods
#if NET_2_0
                #region Async Methods

                public IAsyncResult BeginReadPacket (AsyncCallback callback, object stateObject)
		{
                        TdsAsyncResult ar = new TdsAsyncResult (callback, stateObject);

                        stream.BeginRead (tmpBuf, 0, 8, new AsyncCallback(OnReadPacketCallback), ar);
                        return ar;
		}
                
                /// <returns>Packet size in bytes</returns>
                public int EndReadPacket (IAsyncResult ar)
                {
                        if (!ar.IsCompleted)
                                ar.AsyncWaitHandle.WaitOne ();
                        return (int) ((TdsAsyncResult) ar).ReturnValue;
                }
                

                public void OnReadPacketCallback (IAsyncResult socketAsyncResult)
                {
                        TdsAsyncResult ar = (TdsAsyncResult) socketAsyncResult.AsyncState;
                        int nread = stream.EndRead (socketAsyncResult);
                        
                        while (nread < 8)
                                nread += stream.Read (tmpBuf, nread, 8 - nread);

			TdsPacketType packetType = (TdsPacketType) tmpBuf[0];
			if (packetType != TdsPacketType.Logon && packetType != TdsPacketType.Query && packetType != TdsPacketType.Reply) 
			{
				throw new Exception (String.Format ("Unknown packet type {0}", tmpBuf[0]));
			}

			// figure out how many bytes are remaining in this packet.
			int len = Ntohs (tmpBuf, 2) - 8;

			if (len >= inBuffer.Length) 
				inBuffer = new byte[len];

			if (len < 0) {
				throw new Exception (String.Format ("Confused by a length of {0}", len));
			}

                        GetPhysicalPacketData (len);
                        int value = len + 8;
                        ar.ReturnValue = ((object)value); // packet size
                        ar.MarkComplete ();
                }
                
                #endregion // Async Methods
#endif // NET_2_0

	}

}