This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
libmonetra.cs
1931 lines (1626 loc) · 49.4 KB
/
libmonetra.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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018 Main Street Softworks, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY MAIN STREET SOFTWORKS INC ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MAIN STREET SOFTWORKS INC OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Main Street Softworks, Inc.
*/
/* Overview:
* This library attempts to emulate the libmonetra C API as closely as possible.
* It provides 3 different methods of integration:
* 1) API similar to the libmonetra C-API with one notable difference, that M_InitConn()
* returns an M_CONN class rather than passing in an object to be initialized.
* 2) A true class-based implementation where-as the 'conn' isn't passed back to
* any of the functions, as a reference to it is contained within the initialized
* class. So you could call Monetra conn = new Monetra(); conn.SetIP("localhost", 8333);
* Note the class methods remove the M_ prefix from the function names.
* 3) A P/Invoke 'unsafe' emulation. This should be a drop-in replacement for
* existing implementations which currently use the P/Invoke methods to the libmonetra.dll
*
* This library is designed to be Thread-Safe, but has not yet been extensively tested
* as such.
*
* Building:
* - Requires .Net 2.0 or higher for some SSL calls
* - Needs references to System and System.Net
* - If building using 'mono' use 'gmcs' rather than 'mcs'
* - If you want the P/Invoke 'unsafe' API emulation, uncomment the #define USE_UNSAFE_API below
*
* Migration from P/Invoke libmonetra API notes:
* * Recommended migration away from 'unsafe' API. Please see alternative method as well.
* - The connection pointer is no longer an IntPtr but rather an M_CONN class.
* - The connection pointer is no longer passed by reference (&) because classes are
* automatically passed by reference.
* - The connection pointer is now returned from M_InitConn() rather than passed in to
* be initialized.
* - The identifier returned by M_TransNew() is now of type 'int' rather than 'IntPtr'
* - M_SetDropFile() always returns false as it is unimplemented.
* - M_InitEngine() and M_DestroyEngine()s are No-Ops, they do not need to be called, but
* exist for compatibility purposes.
* - M_ValidateIdentifier() is a no-op, we always scan the hash table for a transaction
* as we are not returning direct pointers.
* - M_ResponseKeys() returns a string array, so there is no implementation for
* M_ResponseKeys_index() or M_FreeResponseKeys() as they are not necessary.
* - M_TransBinaryKeyVal() takes a byte array rather than a string as an argument and does not
* take a length argument.
* - M_GetBinaryCell() returns a byte array rather than a string, it also does not take
* an outlen parameter to store the result length as it is not necessary.
* * Alternative Migration from P/Invoke methods.
* - #define USE_UNSAFE_API below and compile this as an 'unsafe' library.
* - add 'using libmonetra;' to the top of your project and include this library in your project.
* - Remove the old P/Invoke class definitions from your project.
* - Note: it is still necessary to call M_DestroyConn(), M_FreeResponseKeys(), etc to
* clear up system resources when using the 'unsafe' methods since the class references
* are stored in a global Hashtable that the reference must be cleared.
*
* TODO:
* - Unit test
* - The 'cafile' specified by M_SetSSL_CAfile() is not honored, the default system
* certificate store is used instead.
* - The client certificates as provided by M_SetSSL_Files() are not currently honored.
*/
/* Notable references used in the creation of this library:
* TcpClient : http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
* SSLStream : http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx
* Socket : http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx
* Socket2Stream : http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx
* Connect Timeout: http://channel9.msdn.com/forums/TechOff/41602-TcpClient-or-Socket-Connect-timeout/
* Data Available : http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.dataavailable.aspx
*/
/* Whether or not to emulate the 'unsafe' API as used by the P/Invoke methods */
#define USE_UNSAFE_API
/* Whether or not to output assembly information */
#define USE_ASSEMBLY_INFO
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if USE_ASSEMBLY_INFO
[assembly: AssemblyTitle("libmonetra")]
[assembly: AssemblyDescription("Monetra .Net Interface Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Main Street Softworks, Inc")]
[assembly: AssemblyProduct("libmonetra")]
[assembly: AssemblyCopyright("Copyright (c) Main Street Softworks, Inc 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(true)]
[assembly: Guid("a2dd3a40-8c9b-4f4b-82f4-0e902a6e0e21")]
[assembly: AssemblyVersion("0.9.12.0")]
[assembly: AssemblyFileVersion("0.9.12.0")]
#endif
namespace libmonetra {
/* Interface for COM */
public interface IMonetra
{
/* CONSTANTS */
int ERROR { get; }
int FAIL { get; }
int SUCCESS { get; }
int DONE { get; }
int PENDING { get; }
bool SetIP(string host, int port);
bool SetSSL(string host, int port);
bool SetDropFile(string directory);
bool SetBlocking(bool tf);
int TransNew();
string ConnectionError();
bool MaxConnTimeout(int secs);
bool ValidateIdentifier(bool tf);
bool VerifyConnection(bool tf);
bool VerifySSLCert(bool tf);
bool SetSSL_CAfile(string cafile);
bool SetSSL_Files(string sslkeyfile, string sslcertfile);
bool SetTimeout(int secs);
bool TransKeyVal(int id, string key, string val);
bool TransBinaryKeyVal(int id, string key, byte[] val);
int CheckStatus(int id);
bool DeleteTrans(int id);
int CompleteAuthorizations(out int[] id_array);
int TransInQueue();
bool TransactionsSent();
void uwait(int usec);
string GetCell(int id, string col, int row);
byte[] GetBinaryCell(int id, string col, int row);
string GetCellByNum(int id, int col, int row);
string GetCommaDelimited(int id);
string GetHeader(int id, int col);
bool IsCommaDelimited(int id);
int NumColumns(int id);
int NumRows(int id);
string[] ResponseKeys(int id);
string ResponseParam(int id, string key);
int ReturnStatus(int id);
bool Connect();
void DestroyConn();
bool TransSend(int id);
bool Monitor(int timeoutMs);
bool Monitor();
bool ParseCommaDelimited(int id);
}
public class Monetra : IMonetra {
public const string version = "0.9.12";
/* Base implementation, emulate our libmonetra API as closely as possible */
private const int M_CONN_SSL = 1;
private const int M_CONN_IP = 2;
private const int M_TRAN_STATUS_NEW = 1;
private const int M_TRAN_STATUS_SENT = 2;
private const int M_TRAN_STATUS_DONE = 3;
public const int M_ERROR = -1;
public const int M_FAIL = 0;
public const int M_SUCCESS = 1;
public const int M_DONE = 2;
public const int M_PENDING = 3;
private static string init_cafile = null;
public class M_TRAN {
public int id;
public int status;
public bool comma_delimited;
public Hashtable in_params;
public Hashtable out_params;
public byte[] raw_response;
public string[][] csv;
};
public class M_CONN {
public bool blocking;
public string conn_error;
public int conn_timeout;
public string host;
public int last_id;
public int method;
public int port;
public byte[] readbuf;
public string ssl_cafile;
public bool ssl_verify;
public string ssl_cert;
public string ssl_key;
public int timeout;
public Hashtable tran_array;
public bool verify_conn;
public byte[] writebuf;
public Socket socket;
public NetworkStream fd;
public SslStream ssl;
public IAsyncResult readresult;
public byte[] async_read_buf;
};
public static int M_InitEngine(string cafile)
{
init_cafile = cafile;
return 1; /* Returning integer here for legacy reasons */
}
public static void M_DestroyEngine()
{
/* Do nothing */
}
public static M_CONN M_InitConn()
{
M_CONN conn = new M_CONN();
conn.blocking = false;
conn.conn_error = "";
conn.conn_timeout = 10;
conn.host = "";
conn.last_id = 0;
conn.method = M_CONN_IP;
conn.port = 0;
conn.readbuf = null;
conn.fd = null;
conn.socket = null;
conn.ssl = null;
conn.ssl_cafile = init_cafile;
conn.ssl_verify = false;
conn.ssl_cert = null;
conn.timeout = 0;
conn.tran_array = Hashtable.Synchronized(new Hashtable());
conn.verify_conn = true;
conn.writebuf = null;
conn.readresult = null;
conn.async_read_buf = new byte[8192];
return conn;
}
public static bool M_SetIP(M_CONN conn, string host, int port)
{
if (conn == null)
return false;
conn.host = host;
conn.port = port;
conn.method = M_CONN_IP;
return true;
}
public static bool M_SetSSL(M_CONN conn, string host, int port)
{
if (conn == null)
return false;
conn.host = host;
conn.port = port;
conn.method = M_CONN_SSL;
return true;
}
public static bool M_SetDropFile(M_CONN conn, string directory)
{
/* NOT SUPPORTED */
return false;
}
private static long time()
{
TimeSpan _TimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long)_TimeSpan.TotalSeconds;
}
public static bool M_SetBlocking(M_CONN conn, bool tf)
{
if (conn == null)
return false;
conn.blocking = tf;
return true;
}
public static int M_TransNew(M_CONN conn)
{
if (conn == null)
return -1;
M_TRAN tran = new M_TRAN();
tran.id = Interlocked.Increment(ref conn.last_id);
tran.status = M_TRAN_STATUS_NEW;
tran.comma_delimited = false;
/* No reason for these to be synchronized, right? */
tran.in_params = new Hashtable();
tran.out_params = new Hashtable();
tran.raw_response = null;
tran.csv = null;
conn.tran_array[tran.id] = tran;
return tran.id;
}
private static bool M_verifyping(M_CONN conn)
{
if (conn == null)
return false;
bool blocking = conn.blocking;
int id;
M_SetBlocking(conn, false);
id = M_TransNew(conn);
M_TransKeyVal(conn, id, "action", "ping");
if (!M_TransSend(conn, id)) {
M_DeleteTrans(conn, id);
return false;
}
long lasttime = time();
while (M_CheckStatus(conn, id) == M_PENDING && time()-lasttime <= 5) {
if (!M_Monitor(conn, 100))
break;
}
M_SetBlocking(conn, blocking);
int status = M_CheckStatus(conn, id);
M_DeleteTrans(conn, id);
if (status != M_DONE)
return false;
return true;
}
public static string M_ConnectionError(M_CONN conn)
{
if (conn == null)
return "uninitialized";
return conn.conn_error;
}
public static bool M_MaxConnTimeout(M_CONN conn, int secs)
{
if (conn == null)
return false;
conn.conn_timeout = secs;
return true;
}
public static bool M_ValidateIdentifier(M_CONN conn, bool tf)
{
if (conn == null)
return false;
/* Always validated, stub for compatibility */
return true;
}
public static bool M_VerifyConnection(M_CONN conn, bool tf)
{
if (conn == null)
return false;
conn.verify_conn = tf;
return true;
}
public static bool M_VerifySSLCert(M_CONN conn, bool tf)
{
if (conn == null)
return false;
conn.ssl_verify = tf;
return true;
}
public static bool M_SetSSL_CAfile(M_CONN conn, string cafile)
{
if (conn == null)
return false;
conn.ssl_cafile = cafile;
return true;
}
public static bool M_SetSSL_Files(M_CONN conn, string sslkeyfile, string sslcertfile)
{
if (conn == null)
return false;
if (sslkeyfile == null || sslkeyfile.Length == 0 || sslcertfile == null || sslcertfile.Length == 0)
return false;
conn.ssl_cert = sslcertfile;
conn.ssl_key = sslkeyfile;
return true;
}
public static bool M_SetTimeout(M_CONN conn, int secs)
{
if (conn == null)
return false;
conn.timeout = secs;
return true;
}
private static M_TRAN M_findtranbyid(M_CONN conn, int id)
{
if (conn == null || id == -1)
return null;
if (!conn.tran_array.ContainsKey(id))
return null;
return (M_TRAN)conn.tran_array[id];
}
public static bool M_TransKeyVal(M_CONN conn, int id, string key, string val)
{
M_TRAN tran = M_findtranbyid(conn, id);
/* Invalid ptr, or transaction has already been sent out */
if (tran == null || tran.status != M_TRAN_STATUS_NEW)
return false;
tran.in_params[key] = val;
return true;
}
public static bool M_TransBinaryKeyVal(M_CONN conn, int id, string key, byte[] val)
{
return M_TransKeyVal(conn, id, key, System.Convert.ToBase64String(val));
}
public static int M_CheckStatus(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return M_ERROR;
lock (tran) {
if (tran.status != M_TRAN_STATUS_SENT && tran.status != M_TRAN_STATUS_DONE)
return M_ERROR;
if (tran.status == M_TRAN_STATUS_SENT)
return M_PENDING;
}
return M_DONE;
}
public static bool M_DeleteTrans(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return false;
conn.tran_array.Remove(id);
return true;
}
public static int M_CompleteAuthorizations(M_CONN conn, out int[] id_array)
{
if (conn == null) {
id_array = null;
return 0;
}
int count = 0;
lock (conn) {
foreach (DictionaryEntry kv in conn.tran_array) {
M_TRAN tran = M_findtranbyid(conn, (int)kv.Key);
if (tran.status == M_TRAN_STATUS_DONE)
count++;
}
if (count > 0) {
id_array = new int[count];
count = 0;
foreach (DictionaryEntry kv in conn.tran_array) {
M_TRAN tran = M_findtranbyid(conn, (int)kv.Key);
if (tran.status == M_TRAN_STATUS_DONE)
id_array[count++] = (int)kv.Key;
}
} else {
id_array = null;
}
}
return count;
}
public static int M_TransInQueue(M_CONN conn)
{
if (conn == null)
return 0;
return conn.tran_array.Count;
}
public static bool M_TransactionsSent(M_CONN conn)
{
if (conn == null)
return false;
if (conn.writebuf.Length != 0)
return false;
return true;
}
public static void M_uwait(int usec)
{
System.Threading.Thread.Sleep(usec / 1000);
}
public static string M_GetCell(M_CONN conn, int id, string col, int row)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return null;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return null;
if (!tran.comma_delimited)
return null;
if (row+1 >= tran.csv.Length)
return null;
for (int i=0; i<tran.csv[0].Length; i++) {
if (String.Compare(tran.csv[0][i], col, true) == 0)
return tran.csv[row+1][i];
}
return null;
}
public static byte[] M_GetBinaryCell(M_CONN conn, int id, string col, int row)
{
byte[] ret = null;
string cell = M_GetCell(conn, id, col, row);
if (cell != null)
ret = System.Convert.FromBase64String(cell);
return ret;
}
public static string M_GetCellByNum(M_CONN conn, int id, int col, int row)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return null;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return null;
if (!tran.comma_delimited)
return null;
if (row+1 >= tran.csv.Length || col >= tran.csv[0].Length)
return null;
return tran.csv[row+1][col];
}
public static string M_GetCommaDelimited(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return null;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return null;
return Encoding.UTF8.GetString(tran.raw_response);
}
public static string M_GetHeader(M_CONN conn, int id, int col)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return null;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return null;
if (!tran.comma_delimited)
return null;
if (col >= tran.csv[0].Length)
return null;
return tran.csv[0][col];
}
public static bool M_IsCommaDelimited(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return false;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return false;
return tran.comma_delimited;
}
public static int M_NumColumns(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return 0;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return 0;
if (!tran.comma_delimited)
return 0;
return tran.csv[0].Length;
}
public static int M_NumRows(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return 0;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return 0;
if (!tran.comma_delimited)
return 0;
return tran.csv.Length-1;
}
public static string[] M_ResponseKeys(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return null;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return null;
string[] ret = new string[tran.out_params.Count];
int count = 0;
foreach (DictionaryEntry kv in tran.out_params) {
ret[count++] = (string)kv.Key;
}
return ret;
}
public static string M_ResponseParam(M_CONN conn, int id, string key)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return null;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return null;
if (!tran.out_params.ContainsKey(key))
return null;
return (string)tran.out_params[key];
}
public static int M_ReturnStatus(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
if (tran == null)
return M_ERROR;
/* Invalid ptr, or transaction has not returned */
if (M_CheckStatus(conn, id) != M_DONE)
return M_ERROR;
if (tran.comma_delimited)
return M_SUCCESS;
string code = M_ResponseParam(conn, id, "code");
if (String.Compare(code, "AUTH", true) == 0 || String.Compare(code, "SUCCESS", true) == 0)
return M_SUCCESS;
return M_FAIL;
}
private static bool ip_connect(M_CONN conn)
{
#if !OLD_WAY
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect(conn.host, conn.port, null, null);
#else
IPAddress ipAddress;
try {
ipAddress = Dns.Resolve(conn.host).AddressList[0];
} catch (SocketException se) {
conn.conn_error = "DNS failed: " + se.Message;
return false;
}
IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, conn.port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect(ipEndpoint, null, null);
#endif
bool success = result.AsyncWaitHandle.WaitOne(conn.conn_timeout * 1000, true);
if (!success) {
conn.conn_error = "Connection Timeout";
socket.Close();
return false;
}
try {
socket.EndConnect(result);
} catch (SocketException se) {
conn.conn_error = "Connection Failed: " + se.Message;
socket.Close();
return false;
}
/* Disable Nagle algorithm, will lower latency */
socket.NoDelay = true;
conn.socket = socket;
conn.fd = new NetworkStream(socket, false);
return true;
}
private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}
private static bool DontValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static bool M_Connect(M_CONN conn)
{
if (conn == null)
return false;
if (!ip_connect(conn))
return false;
if (conn.method == M_CONN_SSL) {
RemoteCertificateValidationCallback rcvc = null;
if (conn.ssl_verify) {
rcvc = new RemoteCertificateValidationCallback(ValidateServerCertificate);
} else {
rcvc = new RemoteCertificateValidationCallback(DontValidateServerCertificate);
}
conn.ssl = new SslStream(conn.fd, true, rcvc);
try {
/* XXX: client certificates too */
conn.ssl.AuthenticateAsClient(conn.host, null,
/* .Net 4.5 added TLS v1.1 and v1.2 support. We rely on build system preprocessor
* definitions that tell us the .Net version, but if those build system macros are
* not set (therefore not using the provided build system script), lets assume this
* is being compiled with v4.5, as really it should be */
#if (NET_45 || !NET_20)
SslProtocols.Tls11 | SslProtocols.Tls12,
#else
SslProtocols.Tls,
#endif
false /* No CRL verification */);
} catch (AuthenticationException e) {
conn.conn_error = "SSL Exception: " + e.Message;
closeConn(conn);
return false;
} catch (IOException e) {
conn.conn_error = "SSL Exception: " + e.Message;
closeConn(conn);
return false;
}
}
if (conn.verify_conn && !M_verifyping(conn)) {
conn.conn_error = "PING request failed";
closeConn(conn, true);
return false;
}
return true;
}
private static void closeConn(M_CONN conn, bool graceful)
{
/* Clean up SSL */
if (conn.method == M_CONN_SSL && conn.ssl != null) {
try {
conn.ssl.Close();
} catch (Exception e) {
/* Do nothing, was probably cleaned up by garbage collector */
}
}
/* Clean up Stream */
if (conn.fd != null) {
conn.fd.Close();
}
conn.readresult = null;
conn.ssl = null;
conn.fd = null;
/* Clean up raw socket */
if (conn.socket != null) {
try {
if (graceful) {
conn.socket.Shutdown(SocketShutdown.Send);
}
conn.socket.Close();
} catch (Exception e) {
/* Do nothing, was probably cleaned up by garbage collector */
}
}
conn.socket = null;
}
private static void closeConn(M_CONN conn)
{
closeConn(conn, false);
}
public static void M_DestroyConn(M_CONN conn)
{
if (conn == null)
return;
closeConn(conn, true);
conn = null;
}
private static byte[] byteArrayConcat(byte[] str1, byte[] str2, int str2_len)
{
int str1_len;
if (str1 == null)
str1_len = 0;
else
str1_len = str1.Length;
if (str2_len == -1) {
if (str2 == null)
str2_len = 0;
else
str2_len = str2.Length;
}
if (str1_len + str2_len == 0)
return null;
byte[] ret = new byte[str1_len + str2_len];
if (str1_len > 0)
System.Buffer.BlockCopy(str1, 0, ret, 0, str1_len);
if (str2_len > 0)
System.Buffer.BlockCopy(str2, 0, ret, str1_len, str2_len);
return ret;
}
private static int byteArrayChr(byte[] str, byte chr)
{
if (str == null || str.Length == 0)
return -1;
for (int i=0; i < str.Length; i++)
if (str[i] == chr)
return i;
return -1;
}
private static byte[] byteArraySubStr(byte[] str, int start, int length)
{
if (str == null || str.Length < length)
return null;
byte[] ret = new byte[length];
System.Buffer.BlockCopy(str, start, ret, 0, length);
return ret;
}
private static byte[] byteArrayTrim(byte[] str)
{
string mystr = Encoding.UTF8.GetString(str).Trim();
return Encoding.UTF8.GetBytes(mystr);
}
public static bool M_TransSend(M_CONN conn, int id)
{
M_TRAN tran = M_findtranbyid(conn, id);
/* Invalid ptr, or transaction has already been sent out */
if (tran == null || tran.status != M_TRAN_STATUS_NEW)
return false;
lock (tran) {
tran.status = M_TRAN_STATUS_SENT;
}
/* Structure Transaction */
string tran_str;
tran_str = "\x02" + tran.id.ToString() + "\x1c";
/* PING is specially formed */
if (tran.in_params.ContainsKey("action") &&
String.Compare((String)tran.in_params["action"], "ping", true) == 0) {
tran_str += "PING";
} else {
/* Each key/value pair in array as key="value" */
foreach (DictionaryEntry kv in tran.in_params) {
tran_str += (String)kv.Key + "=\"" + ((String)kv.Value).Replace("\"", "\"\"") + "\"\r\n";
}
/* Add timeout if necessary */
if (conn.timeout != 0) {
tran_str += "timeout=" + conn.timeout.ToString() + "\r\n";
}
}
/* ETX */
tran_str += "\x03";
lock(conn) {
/* Expand byte array to append new transaction */
conn.writebuf = byteArrayConcat(conn.writebuf, Encoding.UTF8.GetBytes(tran_str), -1);
}
if (conn.blocking) {