Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Environment.SetEnvironmentVariable("GODEBUG", "cgocheck=0"); //如果DLL有返回数组(切片),这一行是必须的,并且必须在DLL文件加载前设置.

            Hello();                                                     //调用Hello

            Console.WriteLine(Sum(5, 15));                               //调用Sum

            GoString str = GetStr();                                     //调用GetStr

            //以下为GoString转String
            byte[] bytes = new byte[str.n];
            for (int i = 0; i < str.n; i++)
            {
                bytes[i] = Marshal.ReadByte(str.p, i);
            }
            string s = Encoding.UTF8.GetString(bytes);

            Console.WriteLine(s);     //输出结果

            GoSlice arr = GetBytes(); //调用GetBytes

            //以下为GoSlice转Array
            bytes = new byte[arr.len];
            for (int i = 0; i < arr.len; i++)
            {
                bytes[i] = Marshal.ReadByte(arr.data, i);
            }
            //Byte[] to String
            s = Encoding.UTF8.GetString(bytes);
            Console.WriteLine(s); //输出结果
        }
Ejemplo n.º 2
0
        public static byte[] GenerateVerifier(string password, string signedModulus, byte[] rawSalt, int bitLength = 2048)
        {
            GoString goPassword      = password.ToGoString();
            GoString goSignedModulus = signedModulus.ToGoString();
            GoSlice  goRawSalt       = rawSalt.ToGoSlice();
            GoSlice  outBytes        = NativeGenerateVerifier(goPassword, goSignedModulus, goRawSalt, bitLength);

            byte[] bytes = outBytes.ConvertToBytes();
            using (MemoryStream memStream = new MemoryStream(bytes))
            {
                BinaryReader reader = new BinaryReader(memStream);
                byte         v      = reader.ReadByte();
                byte         type   = reader.ReadByte();

                if (type == 0)
                {
                    UInt16 size   = reader.ReadUInt16();
                    byte[] bmsg   = reader.ReadBytes(size);
                    string result = Encoding.UTF8.GetString(bmsg);
                    throw new Exception("go-srp: " + result);
                }
                else if (type == 1)
                {
                    UInt16 size     = reader.ReadUInt16();
                    byte[] verifier = reader.ReadBytes(size);
                    return(verifier);
                }

                return(null);
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            Environment.SetEnvironmentVariable("GODEBUG", "cgocheck=0");

            Console.WriteLine(Sum(5, 15));

            GoString str = GetStr("C#");

            byte[] bytes = new byte[str.n];
            for (int i = 0; i < str.n; i++)
            {
                bytes[i] = Marshal.ReadByte(str.p, i);
            }
            string s = Encoding.UTF8.GetString(bytes);

            Console.WriteLine(s);

            GoSlice arr = GetBytes();

            bytes = new byte[arr.len];
            for (int i = 0; i < arr.len; i++)
            {
                bytes[i] = Marshal.ReadByte(arr.data, i);
            }

            s = Encoding.UTF8.GetString(bytes);
            Console.WriteLine(s);
        }
Ejemplo n.º 4
0
        public static int TestUrlMatch(string url, string host, string headersRaw)
        {
            GoString gsUrl        = GoString.FromString(url);
            GoString gsHost       = GoString.FromString(host);
            GoString gsHeadersRaw = GoString.FromString(headersRaw);

            return(TestUrlMatch(gsUrl, gsHost, gsHeadersRaw));
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            long     add    = SpikeLibrary.Add(12, 99);
            double   cosine = SpikeLibrary.Cosine(1);
            string   msg    = "Hello from C#!";
            GoString str    = new GoString(msg, msg.Length);

            Console.WriteLine("awesome.Add(12,99) = " + add);
            Console.WriteLine("awesome.Cosine(1) = " + cosine);
        }
Ejemplo n.º 6
0
        public static string ConvertToString(this GoString goStr)
        {
            var length = goStr.n.ToInt32();

            // becarefull the encoding. use utf8 for now but maybe ascii better
            byte[] bytes = new byte[length];
            for (int i = 0; i < length; i++)
            {
                bytes[i] = Marshal.ReadByte(goStr.p, i);
            }
            string s = Encoding.UTF8.GetString(bytes);

            return(s);
        }
Ejemplo n.º 7
0
        private void CallRoutineTY(out GoProperty currentGoProperty)
        {
            switch (_iterator.Current.TokenType)
            {
            case TokenType.Array:
                MatchToken(TokenType.Array);
                CallRoutineTY(out GoProperty childGoProperty);
                GoArray currentGoArray = new GoArray();
                currentGoArray.ArrayProperty = childGoProperty;
                currentGoProperty            = currentGoArray;
                break;

            case TokenType.Int:
                MatchToken(TokenType.Int);
                currentGoProperty = new GoInt();
                break;

            case TokenType.String:
                MatchToken(TokenType.String);
                currentGoProperty = new GoString();
                break;

            case TokenType.Float64:
                MatchToken(TokenType.Float64);
                currentGoProperty = new GoFloat();
                break;

            case TokenType.Bool:
                MatchToken(TokenType.Bool);
                currentGoProperty = new GoBool();
                break;

            case TokenType.Id:
                var dslMatch             = MatchToken(TokenType.Id);
                var currentGoPropertyKey = dslMatch.Value;
                currentGoProperty = new GoTypeKey(currentGoPropertyKey, dslMatch.LineNumber);
                break;

            case TokenType.Struct:
                MatchToken(TokenType.Struct);
                MatchToken(TokenType.StructLeftKey);
                CallRoutineSTR(out GoStruct goStructProperty);
                currentGoProperty = goStructProperty;
                MatchToken(TokenType.StructRightKey);
                break;

            default:
                throw new System.Exception("Invalid property token");
            }
        }
Ejemplo n.º 8
0
        public static GoProofs GenerateProofs(int version, string username, SecureString password, string salt,
                                              string signedModulus, string serverEphemeral, int bitLength = 2048)
        {
            byte[] bytes;

            using (GoString goUsername = username.ToGoString())
                using (DisposableGoBytes goPassword = password.ToDisposableGoBytes())
                    using (GoString goSalt = salt.ToGoString())
                        using (GoString goModulus = signedModulus.ToGoString())
                            using (GoString goEphemeral = serverEphemeral.ToGoString())
                            {
                                bytes = NativeGenerateProofs(version, goUsername, goPassword, goSalt, goModulus, goEphemeral, bitLength)
                                        .ConvertToBytes();
                            }

            using (var memStream = new MemoryStream(bytes))
            {
                var reader = new BinaryReader(memStream);
                reader.ReadByte();
                byte type = reader.ReadByte();

                if (type == 0)
                {
                    ushort size = reader.ReadUInt16();
                    byte[] bmsg = reader.ReadBytes(size);
                    throw new Exception("go-srp: " + Encoding.UTF8.GetString(bmsg));
                }

                if (type == 1)
                {
                    ushort size        = reader.ReadUInt16();
                    byte[] clientProof = reader.ReadBytes(size);
                    size = reader.ReadUInt16();
                    byte[] clientEphemeral = reader.ReadBytes(size);
                    size = reader.ReadUInt16();
                    byte[] expectedServerProof = reader.ReadBytes(size);

                    return(new GoProofs
                    {
                        ClientProof = clientProof,
                        ClientEphemeral = clientEphemeral,
                        ExpectedServerProof = expectedServerProof
                    });
                }
            }

            return(null);
        }
Ejemplo n.º 9
0
        public static GoString ToGoString(this string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str); // not null terminated
            //Array.Resize(ref buffer, buffer.Length + 1);
            //buffer[buffer.Length - 1] = 0; // terminating 0
            IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);

            Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
            GoString goStr = new GoString
            {
                p = nativeUtf8,
                n = (IntPtr)buffer.Length
            };

            return(goStr);
        }
Ejemplo n.º 10
0
        public static GoProofs GenerateProofs(int version, string username, string password, string salt, string signedModulus, string serverEphemeral, int bitLength = 2048)
        {
            GoString goUsername  = username.ToGoString();
            GoString goPassword  = password.ToGoString();
            GoString goSalt      = salt.ToGoString();
            GoString goModulus   = signedModulus.ToGoString();
            GoString goEphemeral = serverEphemeral.ToGoString();
            GoSlice  outBytes    = NativeGenerateProofs(version, goUsername, goPassword, goSalt, goModulus, goEphemeral, bitLength);

            byte[] bytes = outBytes.ConvertToBytes();
            using (MemoryStream memStream = new MemoryStream(bytes))
            {
                BinaryReader reader = new BinaryReader(memStream);
                byte         v      = reader.ReadByte();
                byte         type   = reader.ReadByte();

                if (type == 0)
                {
                    UInt16 size   = reader.ReadUInt16();
                    byte[] bmsg   = reader.ReadBytes(size);
                    string result = Encoding.UTF8.GetString(bmsg);
                    throw new Exception("go-srp: " + result);
                }
                else if (type == 1)
                {
                    UInt16 size        = reader.ReadUInt16();
                    byte[] clientProof = reader.ReadBytes(size);
                    size = reader.ReadUInt16();
                    byte[] clientEphemeral = reader.ReadBytes(size);
                    size = reader.ReadUInt16();
                    byte[] expectedServerProof = reader.ReadBytes(size);

                    GoProofs proofs = new GoProofs
                    {
                        ClientProof         = clientProof,
                        ClientEphemeral     = clientEphemeral,
                        ExpectedServerProof = expectedServerProof
                    };
                    return(proofs);
                }
            }

            return(null);
        }
Ejemplo n.º 11
0
        public async Task <bool> Ping(string ip, int port, string serverKeyBase64, Task timeoutTask)
        {
            try
            {
                bool result = await Task.Run(() =>
                {
                    using GoString ipGoString = ip.ToGoString();
                    using GoString serverKeyBase64GoString = serverKeyBase64.ToGoString();
                    return(PInvoke.Ping(ipGoString, port, serverKeyBase64GoString, TimeoutInMilliseconds));
                }).WithTimeout(timeoutTask);

                return(result);
            }
            catch (Exception e) when(e is TimeoutException or TaskCanceledException)
            {
                return(false);
            }
        }
    }
Ejemplo n.º 12
0
    static void Main()
    {
        long   add    = Add(12, 99);
        double cosine = Cosine(1);

        long[] data     = { 77, 12, 5, 99, 28, 23 };
        IntPtr data_ptr = Marshal.AllocHGlobal(Buffer.ByteLength(data));

        Marshal.Copy(data, 0, data_ptr, data.Length);
        var nums = new GoSlice(data_ptr, data.Length, data.Length);

        Sort(nums);
        Marshal.Copy(nums.data, data, 0, data.Length);

        string   msg = "Hello from C#!";
        GoString str = new GoString(msg, msg.Length);

        Console.WriteLine("awesome.Add(12,99) = " + add);
        Console.WriteLine("awesome.Cosine(1) = " + cosine);
        Console.WriteLine("awesome.Sort(77,12,5,99,28,23): " + string.Join(", ", data));
        Log(str);
    }
Ejemplo n.º 13
0
 public static extern void Log(GoString msg);
Ejemplo n.º 14
0
 public static extern CStringHandle GO_WriteStamp(GoString stampStr);
Ejemplo n.º 15
0
 private static extern GoBytes NativeGenerateProofs(int version, GoString username, DisposableGoBytes password,
                                                    GoString salt, GoString signedModulus, GoString serverEphemeral, int bits);
Ejemplo n.º 16
0
 internal static extern int TestUrlMatch(GoString url, GoString host, GoString headersRaw);
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            // CGO checks
            // Go code may not store a Go pointer in C memory.
            // C code may store Go pointers in C memory,
            // subject to the rule above: it must stop storing the Go pointer when
            // the C function returns.

            Environment.SetEnvironmentVariable("GODEBUG", "cgocheck=2");

            // define parameters

            int    a = 10;
            int    b = 2;
            double x = 100;

            Int64[] t = new Int64[] { 35, 56, 1, 3, 2, 88, 14 };

            // Allocate unmanaged memory for
            // the GoSlice

            int      n  = t.Length;
            GCHandle h  = GCHandle.Alloc(t, GCHandleType.Pinned);
            GoSlice  gs = new GoSlice
            {
                data = h.AddrOfPinnedObject(),
                cap  = n,
                len  = n
            };

            // Allocate unmanaged memory for the
            // GoString

            string   msg = "I am the Hal 9000";
            GoString s   = new GoString
            {
                p = Marshal.StringToHGlobalAnsi(msg),
                n = msg.Length
            };

            // call the external functions

            int    addResult    = GoMath.Add(a, b);
            int    subResult    = GoMath.Sub(a, b);
            double cosineResult = GoMath.Cosine(x);
            int    sumResult    = GoMath.Sum(gs);
            var    helloResult  = GoHello.HelloWorld(s);

            GoMath.Sort(gs);

            // Read the Sorted GoSlice

            n = (int)gs.len;
            Int64[] arr = new Int64[n];

            for (int i = 0; i < n; i++)
            {
                arr[i] = Marshal.ReadInt64(gs.data, i * Marshal.SizeOf(typeof(Int64)));
            }

            // Read the size of the data returned by HelloWorld
            // The size is an int32, so we read 4 bytes

            byte *buf = (byte *)helloResult;

            byte[] lenBytes = new byte[4];

            for (int i = 0; i < 4; i++)
            {
                lenBytes[i] = *buf++;
            }

            // Read the result itself

            n = BitConverter.ToInt32(lenBytes, 0);
            int j = 0;

            byte[] bytes = new byte[n];

            for (int i = 0; i < n; i++)
            {
                // Skip the first 4 bytes because
                // they hold the size

                if (i < 4)
                {
                    *buf++ = 0;
                }
                else
                {
                    bytes[j] = *buf++;
                    j++;
                }
            }

            // Print results

            Console.WriteLine(
                "#########################################" +
                "\n### .NET Calling Shared-C Golang .dll ###" +
                "\n#########################################\n"
                );
            Console.WriteLine($"HelloWorld: {Encoding.UTF8.GetString(bytes)}");
            Console.WriteLine($"Add: {addResult}");
            Console.WriteLine($"Sub: {subResult}");
            Console.WriteLine($"Cos: {cosineResult}");
            Console.WriteLine($"Sum: {sumResult}");
            Console.WriteLine(Int64ArrayToString(arr));

            // free up allocated unmanaged memory

            if (h.IsAllocated)
            {
                h.Free();
            }
        }
Ejemplo n.º 18
0
 public static extern unsafe void *HelloWorld(GoString s);
Ejemplo n.º 19
0
 public static extern bool Ping(GoString ip, int port, GoString serverKeyBase64, int timeoutInSeconds);
Ejemplo n.º 20
0
 public static extern bool GO_CheckSignature(GoString file);
Ejemplo n.º 21
0
 public static extern CStringHandle GO_ReadStamp(GoString stampStr);
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            Logger.SetLevel(LogLevel.DEBUG);

            Console.WriteLine("c# prog running");

            string serverId = System.Guid.NewGuid().ToString();

            SDConfig sdConfig = new SDConfig("127.0.0.1:2379", 30, "pitaya/", 30, true, 60);

            // NatsRPCClientConfig rpcClientConfig = new NatsRPCClientConfig("nats://localhost:4222", 10, 5000);
            // // TODO does it makes sense to give freedom to set reconnectionRetries and messagesBufferSize?
            // NatsRPCServerConfig rpcServerConfig = new NatsRPCServerConfig("nats://localhost:4222", 10, 75);
            // PitayaCluster.Init(
            //   sdConfig,
            //   rpcClientConfig,
            //   rpcServerConfig,
            //   new Server(
            //     serverId,
            //     "csharp",
            //     "{\"ip\":\"127.0.0.1\"}",
            //     false)
            // );

            GrpcRPCClientConfig grpcClientConfig = new GrpcRPCClientConfig(5000, 5000, "127.0.0.1:2379", "pitaya/");
            GrpcRPCServerConfig grpcServerConfig = new GrpcRPCServerConfig(5340);

            PitayaCluster.Init(
                sdConfig,
                grpcClientConfig,
                grpcServerConfig,
                new Server(
                    serverId,
                    "csharp",
                    "{\"ip\":\"127.0.0.1\",\"grpc-host\":\"127.0.0.1\",\"grpc-port\":\"5340\"}",
                    false)
                );

            PitayaCluster.ConfigureJaeger(1.0, GoString.fromString("test-svc"));

            TestRemote tr = new TestRemote();

            PitayaCluster.RegisterRemote(tr);

            // prevent from closing
            Console.ReadKey();

            Server sv = PitayaCluster.GetServer(serverId);

            Logger.Info("got server with id: {0}", sv.id);

            Protos.RPCMsg msg = new Protos.RPCMsg();
            msg.Msg = "hellow from bla";

            try{
                Protos.RPCRes res = PitayaCluster.RPC <Protos.RPCRes>(Pitaya.Route.fromString("connector.testremote.test"), msg);
                Logger.Info("received rpc res {0}", res);
            }catch (Exception e) {
                Logger.Error("deu ruim: {0}", e);
            }

            Console.ReadKey();
            PitayaCluster.Shutdown();
        }
Ejemplo n.º 23
0
 private static extern GoSlice NativeGenerateProofs(int version, GoString username, GoString password, GoString salt, GoString signedModulus, GoString serverEphemeral, int bits);
Ejemplo n.º 24
0
 public bool SendCustomResponse(int responseCode, string contentType, byte[] body)
 {
     return(ResponsetNativeWrapper.CreateResponse(handle, responseCode, GoString.FromString(contentType), GoString.FromBytes(body)));
 }
Ejemplo n.º 25
0
 public static extern void SetFeatures(GoString featuresJson);
Ejemplo n.º 26
0
 public static extern IntPtr GetOrganizationAsCtype(GoString str);
Ejemplo n.º 27
0
 public static extern int Log(GoString str);
Ejemplo n.º 28
0
 public static extern GoBytes Connect(GoString clientCertPem, GoString clientKeyPem, GoString serverCaPem,
                                      GoString host, GoString certServerName, GoString featuresJson, bool connectivity);
Ejemplo n.º 29
0
 public static extern IntPtr GetOrganizationAsJson(GoString str);
Ejemplo n.º 30
0
 public static extern bool GO_CreateSign(GoString file);