Ejemplo n.º 1
0
        /// <summary>
        /// Send a message to an arbitrary destination using the server's data
        /// socket.
        /// </summary>
        /// <param name="Message">Supplies the bytes to send.</param>
        /// <param name="Destination">Supplies the destination network address.
        /// </param>
        /// <param name="DestinationPort">Supplies the destination port.
        /// </param>
        public static void SendMessage(byte[] Message, IPAddress Destination, int DestinationPort)
        {
            sockaddr_in sin = new sockaddr_in()
            {
                sin_family = AF_INET,
                sin_port = (ushort)IPAddress.HostToNetworkOrder((short)DestinationPort),
#pragma warning disable 618
                sin_addr = (uint)Destination.Address,
#pragma warning restore 618
                sin_zero = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 }
            };

            SendMessage(Message, sin);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Send a message to an arbitrary destination using the server's data
        /// socket.
        /// </summary>
        /// <param name="Message">Supplies the bytes to send.</param>
        /// <param name="Destination">Supplies the destination address.</param>
        public static void SendMessage(byte[] Message, sockaddr_in Destination)
        {
            int Length;

            if (RecvfromSocket == IntPtr.Zero || Message == null || ((Length = Message.Length) == 0))
                return;

            IntPtr BounceBuffer = Marshal.AllocHGlobal(Length);

            try
            {
                Marshal.Copy(Message, 0, BounceBuffer, Length);
                sendto(RecvfromSocket, BounceBuffer, Length, 0, ref Destination, Marshal.SizeOf(typeof(sockaddr_in)));
            }
            finally
            {
                Marshal.FreeHGlobal(BounceBuffer);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// This routine handles ALFA datagram protocol messages that have been
        /// received over the network.
        /// </summary>
        /// <param name="buf">Supplies the received data payload.</param>
        /// <param name="len">Supplies the length of received data.</param>
        /// <param name="Sender">Supplies the sender's address.</param>
        private static void OnDatagramReceive(IntPtr buf, int len, sockaddr_in Sender)
        {
            IPAddress Address = new IPAddress(Sender.sin_addr);
            int Port = (int)IPAddress.NetworkToHostOrder((short)Sender.sin_port);
            ServerNetworkManager NetworkManager = ACR_ServerCommunicator.GetNetworkManager();
            byte[] Data = new byte[len];
            Marshal.Copy(buf, Data, 0, len);

            NetworkManager.OnDatagramReceive(Data, Address, Port);
        }
Ejemplo n.º 4
0
 static extern IntPtr SCNetworkReachabilityCreateWithAddress(IntPtr allocator, ref sockaddr_in sockaddr);
Ejemplo n.º 5
0
		static extern IntPtr SCNetworkReachabilityCreateWithAddress (IntPtr allocator, ref sockaddr_in sockaddr);
 private String sockAddrInToString(sockaddr_in sin)
 {
     string family = sin.sin_family.ToString();
     string remoteIp = new System.Net.IPAddress(sin.sin_addr.S_addr).ToString();
     string remotePort = ntohs(sin.sin_port).ToString();
     string w1 = sin.sin_addr.S_un_w.s_w1.ToString();
     string w2 = sin.sin_addr.S_un_w.s_w2.ToString();
     string b1 = sin.sin_addr.S_un_b.s_b1.ToString();
     string b2 = sin.sin_addr.S_un_b.s_b2.ToString();
     string b3 = sin.sin_addr.S_un_b.s_b3.ToString();
     string b4 = sin.sin_addr.S_un_b.s_b4.ToString();
     return "Family: " + family + " Remote Ip: " + remoteIp + " Remote Port: " + remotePort +
         " w1: " + w1 + " w2: " + w2 + " b1: " + b1 + " b2: " + b2 + " b3: " + b3 + " b4: " + b4; // w,b == zero padding
 }
Ejemplo n.º 7
0
 public int sceNetInetRecvfrom(int SocketId, void* BufferPointer, int BufferLength, SocketFlags SocketFlags, sockaddr_in* From, socklen_t* FromLength)
 {
     var Socket = Sockets.Get(SocketId);
     EndPoint EndPoint = new IPEndPoint(From->sin_addr.Address, From->sin_port);
     return Socket.ReceiveFrom(ArrayUtils.CreateArray<byte>(BufferPointer, BufferLength), SocketFlags, ref EndPoint);
 }
Ejemplo n.º 8
0
 public int sceNetInetConnect(int SocketId, sockaddr_in *serv_addr, socklen_t addrlen)
 {
     var Socket = Sockets.Get(SocketId);
     Console.WriteLine("{0}", serv_addr->sin_addr);
     Socket.Connect(new IPEndPoint(serv_addr->sin_addr.Address, serv_addr->sin_port));
     return 0;
 }
Ejemplo n.º 9
0
		extern static /* SCNetworkReachabilityRef __nullable */ IntPtr SCNetworkReachabilityCreateWithAddress (
			/* CFAllocatorRef __nullable */ IntPtr allocator, 
			/* const struct sockaddr * __nonnull */ ref sockaddr_in address);
Ejemplo n.º 10
0
		public NetworkReachability (IPAddress ip)
		{
			if (ip == null)
				throw new ArgumentNullException ("ip");
				
			var s = new sockaddr_in (ip);
			handle = SCNetworkReachabilityCreateWithAddress (IntPtr.Zero, ref s);
			if (handle == IntPtr.Zero)
				throw SystemConfigurationException.FromMostRecentCall ();
		}
Ejemplo n.º 11
0
        private unsafe IList <Device> GetAllDevices()
        {
            List <Device> deviceList    = new List <Device>();
            IntPtr        deviceListPtr = IntPtr.Zero;
            IntPtr        currentAddress;

            try
            {
                StringBuilder errorBuffer = new StringBuilder(PCAP_ERRBUF_SIZE);
                int           returnCode  = pcap_findalldevs(ref deviceListPtr, errorBuffer);
                if (returnCode != 0)
                {
                    throw new ApplicationException("Cannot enumerate devices: [" + errorBuffer.ToString() + "].");
                }

                IntPtr ip = deviceListPtr;
                while (ip != IntPtr.Zero)
                {
                    pcap_if dev = (pcap_if)Marshal.PtrToStructure(ip, typeof(pcap_if));

                    Device device = new Device();
                    device.Name        = dev.name;
                    device.Description = dev.description;
                    device.Addresses   = new List <uint>();
                    currentAddress     = dev.addresses;

                    while (currentAddress != IntPtr.Zero)
                    {
                        pcap_addr address = *(pcap_addr *)currentAddress;

                        if (address.addr != IntPtr.Zero)
                        {
                            sockaddr_in sockaddress = *(sockaddr_in *)address.addr;
                            if (sockaddress.sin_family == AF_INET)
                            {
                                device.Addresses.Add(sockaddress.sin_addr);
                            }
                        }

                        currentAddress = address.next;
                    }

                    deviceList.Add(device);

                    ip = dev.next;
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Unable to get WinPcap device list.", ex);
            }
            finally
            {
                // always release memory after getting device list.
                if (deviceListPtr != IntPtr.Zero)
                {
                    pcap_freealldevs(deviceListPtr);
                }
            }

            return(deviceList);
        }
Ejemplo n.º 12
0
 private static extern int sendto(IntPtr s, IntPtr buf, int len, int flags, ref sockaddr_in to, int tolen);
Ejemplo n.º 13
0
		public static extern int connect(IntPtr s, sockaddr_in addr, int addrsize);
Ejemplo n.º 14
0
        private void tCPClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpcodeWriter writer = new OpcodeWriter();
            WSAData wsaData = new WSAData();
            sockaddr_in sockaddr = new sockaddr_in();
            sockaddr_in Clientsockaddr = new sockaddr_in();
            VirtualAddress wsaDataAddr = writer.dataSection.CreateVariable(wsaData);
            VirtualAddress SockinAddress = writer.dataSection.CreateVariable(sockaddr);
            VirtualAddress ClientSockinAddress = writer.dataSection.CreateVariable(Clientsockaddr);
            VirtualAddress UsernameAddress = writer.dataSection.CreateVariable(ASCIIEncoding.ASCII.GetBytes("****************")); //the data we want to send when a client connects
            VirtualAddress PasswordAddress = writer.dataSection.CreateVariable(ASCIIEncoding.ASCII.GetBytes("****************")); //the data we want to send when a client connects
            VirtualAddress SocketAddress = writer.dataSection.CreateVariable(IntPtr.Zero);

            //socket initialization
            //set the WSADATA settings
            writer.codeSection.MOV_VARIABLE_VALUE(wsaDataAddr, "HighVersion", (ushort)2);
            writer.codeSection.MOV_VARIABLE_VALUE(wsaDataAddr, "Version", (ushort)2);

            //set the sockaddr_in settings, setting the family IPv4
            writer.codeSection.MOV_VARIABLE_VALUE(SockinAddress, "sin_family", (short)ValueCodes.InterNetworkv4);
            //setting port, we need to encode it first...
            writer.codeSection.PUSH_VALUE(1337); //1337=listen port
            writer.codeSection.CALL(Functions.ws2_32_htons);
            writer.codeSection.MOV_VARIABLE_REGISTER(SockinAddress, "sin_port", Register.EAX);

            
            writer.codeSection.PUSH_STRING("127.0.0.1"); //ip
            writer.codeSection.CALL(Functions.ws2_32_inet_addr);
            writer.codeSection.MOV_VARIABLE_REGISTER(SockinAddress, "sin_addr", Register.EAX);

            writer.codeSection.PUSH_VARIABLE(wsaDataAddr);
            writer.codeSection.PUSH_VALUE(36);
            writer.codeSection.CALL(Functions.ws2_32_WSAStartup);

            //started successfully ?
            writer.codeSection.MOV_ECX(0);
            writer.codeSection.CMP(CmpRegisterOpcodes.CMP_ECX_EAX);
            writer.codeSection.JNE("failed");

        //create a socket
            writer.codeSection.PUSH_VALUE(ValueCodes.Tcp, (int)0);
            writer.codeSection.PUSH_VALUE(ValueCodes.Stream, (int)0);
            writer.codeSection.PUSH_VALUE(ValueCodes.InterNetworkv4, (int)0);
            writer.codeSection.CALL(Functions.ws2_32_socket);
                
        //is socket > 0 ?
            writer.codeSection.MOV_ECX((int)ValueCodes.INVALID_SOCKET);
            writer.codeSection.CMP(CmpRegisterOpcodes.CMP_ECX_EAX);
            writer.codeSection.JE("failed");

        //lets move our socket handle to EBX
            writer.codeSection.MOV(MovRegisterOpcodes.MOV_EBX_EAX);

            
            writer.codeSection.PUSH_VALUE(Marshal.SizeOf(new sockaddr_in()));
            writer.codeSection.PUSH_VARIABLE(SockinAddress);
            writer.codeSection.PUSH_EBX();
            writer.codeSection.CALL(Functions.ws2_32_connect);

            
            writer.codeSection.MOV_ECX(0);
            writer.codeSection.CMP(CmpRegisterOpcodes.CMP_ECX_EAX);
            writer.codeSection.JNE("UnableToConnect");
            writer.codeSection.JMP("end");


            writer.codeSection.CreateLabel("failed");
            writer.codeSection.PUSH_VALUE(0);
            writer.codeSection.PUSH_STRING("Something went wrong... unable to connect?");
            writer.codeSection.PUSH_STRING("Something went wrong... unable to connect?");
            writer.codeSection.PUSH_VALUE(ValueCodes.MB_OK, (int)0);
            writer.codeSection.CALL(Functions.User32_MessageBoxA);
            writer.codeSection.JMP("end");

            
            writer.codeSection.CreateLabel("UnableToConnect");
            writer.codeSection.PUSH_VALUE(0);
            writer.codeSection.PUSH_STRING("unable to connect?");
            writer.codeSection.PUSH_STRING("unable to connect?");
            writer.codeSection.PUSH_VALUE(ValueCodes.MB_OK, (int)0);
            writer.codeSection.CALL(Functions.User32_MessageBoxA);
            writer.codeSection.JMP("end");


            writer.codeSection.CreateLabel("end");
            writer.codeSection.XOR(XorRegisterOpcodes.XOR_ECX_ECX);
            ExecuteCode(writer);
        }
Ejemplo n.º 15
0
        private void tCPServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpcodeWriter writer = new OpcodeWriter();

            WSAData wsaData = new WSAData();
            sockaddr_in sockaddr = new sockaddr_in();
            sockaddr_in Clientsockaddr = new sockaddr_in();
            VirtualAddress wsaDataAddr = writer.dataSection.CreateVariable(wsaData);
            VirtualAddress SockinAddress = writer.dataSection.CreateVariable(sockaddr);
            VirtualAddress ClientSockinAddress = writer.dataSection.CreateVariable(Clientsockaddr);
            VirtualAddress ArrayAddress = writer.dataSection.CreateVariable(ASCIIEncoding.ASCII.GetBytes(":)")); //the data we want to send when a client connects

            //socket initialization
            //set the WSADATA settings
            writer.codeSection.MOV_VARIABLE_VALUE(wsaDataAddr, "HighVersion", (ushort)2);
            writer.codeSection.MOV_VARIABLE_VALUE(wsaDataAddr, "Version", (ushort)2);

            //set the sockaddr_in settings, setting the family IPv4
            writer.codeSection.MOV_VARIABLE_VALUE(SockinAddress, "sin_family", (short)ValueCodes.InterNetworkv4);
            //setting port, we need to encode it first...
            writer.codeSection.PUSH_VALUE(1337); //1337=listen port
            writer.codeSection.CALL(Functions.ws2_32_htons);
            writer.codeSection.MOV_VARIABLE_REGISTER(SockinAddress, "sin_port", Register.EAX);

            writer.codeSection.PUSH_VARIABLE(wsaDataAddr);
            writer.codeSection.PUSH_VALUE(36);
            writer.codeSection.CALL(Functions.ws2_32_WSAStartup);

            //started successfully ?
            writer.codeSection.MOV_ECX(0);
            writer.codeSection.CMP(CmpRegisterOpcodes.CMP_ECX_EAX);
            writer.codeSection.JNE("failed");

        //create a socket
            writer.codeSection.PUSH_VALUE(ValueCodes.Tcp, (int)0);
            writer.codeSection.PUSH_VALUE(ValueCodes.Stream, (int)0);
            writer.codeSection.PUSH_VALUE(ValueCodes.InterNetworkv4, (int)0);
            writer.codeSection.CALL(Functions.ws2_32_socket);
                
        //is socket > 0 ?
            writer.codeSection.MOV_ECX((int)ValueCodes.INVALID_SOCKET);
            writer.codeSection.CMP(CmpRegisterOpcodes.CMP_ECX_EAX);
            writer.codeSection.JE("failed");

        //lets move our socket handle to EBX
            writer.codeSection.MOV(MovRegisterOpcodes.MOV_EBX_EAX);

        //lets bind our socket
            writer.codeSection.PUSH_VALUE(Marshal.SizeOf(sockaddr));
            writer.codeSection.PUSH_VARIABLE(SockinAddress); //our sockaddr_in
            writer.codeSection.PUSH_EBX(); //socket handle
            writer.codeSection.CALL(Functions.ws2_32_bind);

            //ok lets listen at a port
            writer.codeSection.PUSH_VALUE((int)100);
            writer.codeSection.PUSH_EBX(); //socket
            writer.codeSection.CALL(Functions.ws2_32_listen);


            //now a infinite loop for accept our connections but lets setup our console
            writer.codeSection.PUSH_VALUE(-11); //STD_OUTPUT_HANDLE
            writer.codeSection.CALL(Functions.Kernel32_GetStdHandle);
            writer.codeSection.MOV(MovRegisterOpcodes.MOV_EDX_EAX);

            writer.codeSection.CreateLabel("loop");
                //lets accept connections
                writer.codeSection.PUSH_VALUE(Marshal.SizeOf(Clientsockaddr));
                writer.codeSection.PUSH_VARIABLE(ClientSockinAddress);
                writer.codeSection.PUSH_EBX(); //server socket
                writer.codeSection.CALL(Functions.ws2_32_accept);
                writer.codeSection.MOV(MovRegisterOpcodes.MOV_EDI_EAX); //set client socket to EDI


                writer.codeSection.PUSH_VALUE(0);
                writer.codeSection.PUSH_VALUE(0);
                writer.codeSection.PUSH_VALUE(20);//char length
                writer.codeSection.PUSH_STRING("new client accepted\r\n");
                writer.codeSection.PUSH_EDX();
                writer.codeSection.CALL(Functions.Kernel32_WriteConsoleA);

                //lets send a packet
                writer.codeSection.PUSH_VALUE(0);
                writer.codeSection.PUSH_VALUE(2);
                writer.codeSection.PUSH_VARIABLE(ArrayAddress);
                writer.codeSection.PUSH_EDI(); //client socket
                writer.codeSection.CALL(Functions.ws2_32_send);

                //close our connection with the client...
                writer.codeSection.PUSH_EDI();
                writer.codeSection.CALL(Functions.ws2_32_closesocket);

            writer.codeSection.JMP("loop");

            writer.codeSection.PUSH_EBX();
            writer.codeSection.CALL(Functions.ws2_32_closesocket);

            writer.codeSection.CreateLabel("failed");
            writer.codeSection.XOR(XorRegisterOpcodes.XOR_ECX_ECX);
            ExecuteCode(writer);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Called when nwn2server receives a message from UDP.  The routine
        /// decides if the message should be internally handled, and, if so,
        /// packages it up for managed handling.  Otherwise, the original
        /// nwn2server handling is continued.
        /// </summary>
        /// <param name="s">Supplies the socket that received data.</param>
        /// <param name="buf">Supplies the buffer pointer (length of len).
        /// </param>
        /// <param name="len">Supplies the count of bytes received.</param>
        /// <param name="flags">Supplies the original recvfrom flags.</param>
        /// <param name="from">Supplies the sender address.  This is known to
        /// be at least the size of a sockaddr_in.</param>
        /// <param name="fromlen">Supplies the length of the sender address.
        /// </param>
        /// <returns>The new count of bytes to be considered as received.  If
        /// the routine internally handles the message then this should be set
        /// to zero.  Otherwise, len should be returned.</returns>
        private static int OnLowLevelReceive(IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen)
        {
            if (RecvfromSocket == IntPtr.Zero)
            {
                RecvfromSocket = s;
            }

            if (LocalDataPort == 0)
            {
                try
                {
                    sockaddr_in LocalSocketName;
                    int         NameLen = Marshal.SizeOf(typeof(sockaddr_in));

                    if (getsockname(RecvfromSocket, out LocalSocketName, ref NameLen) == 0)
                    {
                        //
                        // Use loopback (disable deprecation warning) if we have no
                        // bound address.
                        //

#pragma warning disable 618
                        if (LocalSocketName.sin_addr == 0)
                        {
                            LocalSocketName.sin_addr = (uint)(ulong)IPAddress.Loopback.Address;
                        }
#pragma warning restore 618

                        LocalDataPort        = (int)IPAddress.NetworkToHostOrder((short)LocalSocketName.sin_port);
                        LocalListenerAddress = (int)LocalSocketName.sin_addr;
                    }
                }
                catch
                {
                }
            }

            if (len < 5 || Marshal.ReadInt32(fromlen) < Marshal.SizeOf(typeof(sockaddr_in)))
            {
                return(len);
            }

            if (Marshal.ReadInt32(buf) != ALFAProtocolMagic)
            {
                return(len);
            }

            try
            {
                switch ((PROTOCOL_ID)Marshal.ReadByte(buf + 4))
                {
                case PROTOCOL_ID.PROTOCOL_DATAGRAM:
                    sockaddr_in Sender = (sockaddr_in)Marshal.PtrToStructure(from, typeof(sockaddr_in));

                    if (Sender.sin_family != AF_INET)
                    {
                        return(len);
                    }

                    OnDatagramReceive(buf, len, Sender);
                    return(0);

                default:
                    return(0);
                }
            }
            catch
            {
                return(0);
            }
        }
Ejemplo n.º 17
0
 private static extern int getsockname(IntPtr s, out sockaddr_in name, ref int namelen);
Ejemplo n.º 18
0
 private static extern int api_sendto(int s, ref object buf, int buflen, int flags, ref sockaddr_in toaddr, int tolen);
Ejemplo n.º 19
0
        private void readOptionalHeaders(PacketRecord packet, uint header_, StringBuilder packetHeadersStr, BinaryReader packetReader)
        {
            long readStartPos = packetReader.BaseStream.Position;

            if ((header_ & CServerSwitchStructHeader.mask) != 0)
            {
                CServerSwitchStruct serverSwitchStruct = CServerSwitchStruct.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Server Switch");
            }

            if ((header_ & LogonServerAddrHeader.mask) != 0)
            {
                sockaddr_in serverAddr = sockaddr_in.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Logon Server Addr");
            }

            if ((header_ & CEmptyHeader1.mask) != 0)
            {
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Empty Header 1");
            }

            if ((header_ & CReferralStructHeader.mask) != 0)
            {
                CReferralStruct referralStruct = CReferralStruct.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Referral");
            }

            if ((header_ & NakHeader.mask) != 0)
            {
                CSeqIDListHeader nakSeqIDs = NakHeader.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Nak");
            }

            if ((header_ & EmptyAckHeader.mask) != 0)
            {
                CSeqIDListHeader ackSeqIDs = EmptyAckHeader.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Empty Ack");
            }

            if ((header_ & PakHeader.mask) != 0)
            {
                PakHeader pakHeader = PakHeader.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Pak");
            }

            if ((header_ & CEmptyHeader2.mask) != 0)
            {
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Empty Header 2");
            }

            if ((header_ & CLogonHeader.mask) != 0)
            {
                CLogonHeader.HandshakeWireData handshakeData = CLogonHeader.HandshakeWireData.read(packetReader);
                byte[] authData = packetReader.ReadBytes((int)handshakeData.cbAuthData);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Logon");
            }

            if ((header_ & ULongHeader.mask) != 0)
            {
                ULongHeader ulongHeader = ULongHeader.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("ULong 1");
            }

            if ((header_ & CConnectHeader.mask) != 0)
            {
                CConnectHeader.HandshakeWireData handshakeData = CConnectHeader.HandshakeWireData.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Connect");
            }

            if ((header_ & ULongHeader2.mask) != 0)
            {
                ULongHeader2 ulongHeader = ULongHeader2.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("ULong 2");
            }

            if ((header_ & NetErrorHeader.mask) != 0)
            {
                NetError netError = NetError.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Net Error");
            }

            if ((header_ & NetErrorHeader_cs_DisconnectReceived.mask) != 0)
            {
                NetError netError = NetError.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Net Error Disconnect");
            }

            if ((header_ & CICMDCommandStructHeader.mask) != 0)
            {
                CICMDCommandStruct icmdStruct = CICMDCommandStruct.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("ICmd");
            }

            if ((header_ & CTimeSyncHeader.mask) != 0)
            {
                CTimeSyncHeader timeSyncHeader = CTimeSyncHeader.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Time Sync");
            }

            if ((header_ & CEchoRequestHeader.mask) != 0)
            {
                CEchoRequestHeader echoRequestHeader = CEchoRequestHeader.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Echo Request");
            }

            if ((header_ & CEchoResponseHeader.mask) != 0)
            {
                CEchoResponseHeader.CEchoResponseHeaderWireData echoResponseData = CEchoResponseHeader.CEchoResponseHeaderWireData.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Echo Response");
            }

            if ((header_ & CFlowStructHeader.mask) != 0)
            {
                CFlowStruct flowStruct = CFlowStruct.read(packetReader);
                if (packetHeadersStr.Length != 0)
                {
                    packetHeadersStr.Append(" | ");
                }
                packetHeadersStr.Append("Flow");
            }

            packet.optionalHeadersLen = (int)(packetReader.BaseStream.Position - readStartPos);
        }
Ejemplo n.º 20
0
		extern static /* SCNetworkReachabilityRef __nullable */ IntPtr SCNetworkReachabilityCreateWithAddressPair (
			/* CFAllocatorRef __nullable */ IntPtr allocator, 
			/* const struct sockaddr * __nullable */ ref sockaddr_in localAddress, 
			/* const struct sockaddr * __nullable */ IntPtr remoteAddress);
Ejemplo n.º 21
0
        private int WinsockConnectDetour(IntPtr s, IntPtr sockAddr, int addrsize)
        {
            lock (wSockLock)
            {
                // retrieve remote ip
                sockaddr_in structure  = (sockaddr_in)Marshal.PtrToStructure(sockAddr, typeof(sockaddr_in));
                string      remoteIp   = new System.Net.IPAddress(structure.sin_addr.S_addr).ToString();
                ushort      remotePort = ntohs(structure.sin_port);
                HookManager.Log("Ip: " + remoteIp + " Port: " + remotePort.ToString() + " Addrsize: " + addrsize);

                if (!remoteIp.Contains("127.0.0.1"))
                {
                    // connect to socks5 server
                    //IntPtr test = CreateAddr(proxyIp,proxyPort.ToString());
                    SetAddr(sockAddr, proxyIp, proxyPort.ToString());
                    var result = connect(s, sockAddr, addrsize);

                    // send socks 5 request
                    IntPtr socksProtocolRequest = SetUpSocks5Request();

                    result = -1;
                    while (result == -1)
                    {
                        result = send(s, socksProtocolRequest, 4, 0);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAENOTCONN && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Send failed, Error: + " + errorcode);
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }


                    // retrieve server repsonse
                    var response = IntPtr.Zero;
                    while (response == IntPtr.Zero)
                    {
                        response = Recieve(s, 2);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAEWOULDBLOCK && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Recieve FAILED response == IntPtr.Zero! Lasterror: " + errorcode.ToString());
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }

                    byte[] recvBytes = new byte[2] {
                        Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                    };
                    if (recvBytes[1] == 255)
                    {
                        HookManager.Log("No authentication method was accepted by the proxy server");
                        return(-1);
                    }
                    if (recvBytes[0] != 5)
                    {
                        HookManager.Log("No SOCKS5 proxy");
                        return(-1);
                    }

                    // if auth request response, send authenicate request
                    if (recvBytes[1] == 2)
                    {
                        int length = 0;
                        var authenticateRequest = SetUpAuthenticateRequest(proxyUser, proxyPass, out length);
                        result = -1;
                        while (result == -1)
                        {
                            result = send(s, authenticateRequest, length, 0);
                            var errorcode = WSAGetLastError();
                            if (errorcode != WSAENOTCONN && errorcode != WSANOERROR)
                            {
                                HookManager.Log("Send failed, Error: + " + errorcode);
                                return(-1);
                            }
                            Thread.Sleep(1);
                        }


                        response = IntPtr.Zero;
                        while (response == IntPtr.Zero)
                        {
                            response = Recieve(s, 2);
                            var errorcode = WSAGetLastError();
                            if (errorcode != WSAEWOULDBLOCK && errorcode != WSANOERROR)
                            {
                                HookManager.Log("Recieve FAILED response == IntPtr.Zero! Lasterror: " + errorcode.ToString());
                                return(-1);
                            }
                            Thread.Sleep(1);
                        }

                        recvBytes = new byte[2] {
                            Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                        };
                        if (recvBytes[1] != 0)
                        {
                            //HookManager.Log("Proxy: incorrect username/password");
                            HookManager.Log("Proxy: incorrect username/password");
                            return(-1);
                        }
                    }

                    // request bind with server
                    var bindRequest = SetUpBindWithRemoteHost(remoteIp, remotePort);
                    result = -1;
                    while (result == -1)
                    {
                        result = send(s, bindRequest, 10, 0);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAENOTCONN && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Send failed (bindRequest), Error: + " + errorcode);
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }


                    // bind response
                    response = IntPtr.Zero;
                    while (response == IntPtr.Zero)
                    {
                        response = Recieve(s, 10);
                        var errorcode = WSAGetLastError();
                        if (errorcode != WSAEWOULDBLOCK && errorcode != WSANOERROR)
                        {
                            HookManager.Log("Recieve FAILED response == IntPtr.Zero! Lasterror: " + errorcode.ToString());
                            return(-1);
                        }
                        Thread.Sleep(1);
                    }


                    if (!VerifyBindResponse(response))
                    {
                        HookManager.Log("VerifyBindResponse failed!");
                        return(-1);
                    }

                    // success
                    WSASetLastError(0);
                    SetLastError(0);

                    // clean memory
                    foreach (var ptr in allocatedMemory)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }

                    allocatedMemory.Clear();
                    return(0);
                }
                else
                {
                    return(connect(s, sockAddr, addrsize));
                }
            }
        }
Ejemplo n.º 22
0
		public NetworkReachability (IPAddress localAddress, IPAddress remoteAddress)
		{
			if (localAddress == null && remoteAddress == null)
				throw new ArgumentException ("At least one address is required");
				
			if (localAddress == null) {
				var remote = new sockaddr_in (remoteAddress);
				
				handle = SCNetworkReachabilityCreateWithAddressPair (IntPtr.Zero, IntPtr.Zero, ref remote);
			} else if (remoteAddress == null) {
				var local = new sockaddr_in (localAddress);
				
				handle = SCNetworkReachabilityCreateWithAddressPair (IntPtr.Zero, ref local, IntPtr.Zero);
			} else {
				var local = new sockaddr_in (localAddress);
				var remote = new sockaddr_in (remoteAddress);
			
				handle = SCNetworkReachabilityCreateWithAddressPair (IntPtr.Zero, ref local, ref remote);
			}
			
			if (handle == IntPtr.Zero)
				throw SystemConfigurationException.FromMostRecentCall ();
		} 
Ejemplo n.º 23
0
                public static SOCKET_ADDRESS_SAFE SocketAddressFromIPEndPoint(IPEndPoint endpoint)
                {
                    SOCKET_ADDRESS_SAFE socketAddress = new SOCKET_ADDRESS_SAFE();
                    if (endpoint == null)
                        return socketAddress;

                    if (endpoint.AddressFamily == AddressFamily.InterNetwork)
                    {
                        socketAddress.iSockaddrLength = Marshal.SizeOf(typeof(sockaddr_in));
                        socketAddress.lpSockAddr = CriticalAllocHandle.FromSize(socketAddress.iSockaddrLength);
                        sockaddr_in sa = new sockaddr_in();
                        sa.sin_family = (short)AddressFamily.InterNetwork;
                        sa.sin_port = (ushort)endpoint.Port;
                        sa.sin_addr = endpoint.Address.GetAddressBytes();
                        Marshal.StructureToPtr(sa, (IntPtr)socketAddress.lpSockAddr, false);
                    }
                    else if (endpoint.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        socketAddress.iSockaddrLength = Marshal.SizeOf(typeof(sockaddr_in6));
                        socketAddress.lpSockAddr = CriticalAllocHandle.FromSize(socketAddress.iSockaddrLength);
                        sockaddr_in6 sa = new sockaddr_in6();
                        sa.sin6_family = (short)AddressFamily.InterNetworkV6;
                        sa.sin6_port = (ushort)endpoint.Port;
                        sa.sin6_addr = endpoint.Address.GetAddressBytes();
                        sa.sin6_scope_id = (uint)endpoint.Address.ScopeId;
                        Marshal.StructureToPtr(sa, (IntPtr)socketAddress.lpSockAddr, false);
                    }
                    return socketAddress;
                }
Ejemplo n.º 24
0
 public int sceNetInetSendto(int SocketId, void *BufferPointer, int BufferLength, SocketFlags SocketFlags, sockaddr_in *To, socklen_t ToLength)
 {
     var Socket = Sockets.Get(SocketId);
     return Socket.SendTo(ArrayUtils.CreateArray<byte>(BufferPointer, BufferLength), SocketFlags, new IPEndPoint(To->sin_addr.Address, To->sin_port));
 }
Ejemplo n.º 25
0
        //Gets remote info from a sockaddr_in structure.
        private void GetRemoteInfoFromSI(ref sockaddr_in udtSockAddr, ref int lngRemotePort, ref string strRemoteHostIP, ref string strRemoteHost)
        {
            //Dim lngResult As Long
            //Dim udtHostent As HOSTENT

            lngRemotePort = modSocketMaster.IntegerToUnsigned(ref api_ntohs(udtSockAddr.sin_port));
            strRemoteHostIP = modSocketMaster.StringFromPointer(api_inet_ntoa(udtSockAddr.sin_addr));
            //lngResult = api_gethostbyaddr(udtSockAddr.sin_addr, 4&, AF_INET)

            //If lngResult <> 0 Then
            //    api_CopyMemory udtHostent, ByVal lngResult, LenB(udtHostent)
            //    strRemoteHost = StringFromPointer(udtHostent.hName)
            //Else
            m_strRemoteHost = "";
            //End If
        }
Ejemplo n.º 26
0
 private static extern int getsockname(IntPtr s, out sockaddr_in name, ref int namelen);
Ejemplo n.º 27
0
 private static extern int api_accept(int s, ref sockaddr_in addr, ref int addrlen);
 private IntPtr CreateAddr(string ip, string port)
 {
     var s = Marshal.AllocHGlobal(16);
     sockaddr_in sockAddr = new sockaddr_in();
     sockAddr.sin_addr.S_addr = inet_addr(ip);
     sockAddr.sin_port = htons(Convert.ToUInt16(port));
     sockAddr.sin_family = 2;
     Marshal.StructureToPtr(sockAddr, s, true);
     return s;
 }
Ejemplo n.º 29
0
 private static extern int api_bind(int s, ref sockaddr_in name, ref int namelen);
Ejemplo n.º 30
0
 private static extern int sendto(IntPtr s, IntPtr buf, int len, int flags, ref sockaddr_in to, int tolen);
Ejemplo n.º 31
0
 private static extern int api_connect(int s, ref sockaddr_in name, int namelen);
Ejemplo n.º 32
0
 private static extern int api_getsockname(int s, ref sockaddr_in name, ref int namelen);
Ejemplo n.º 33
0
 private static extern int api_recvfrom(int s, ref object buf, int buflen, int flags, ref sockaddr_in @from, ref int fromlen);
Ejemplo n.º 34
0
        //Removed, replace this functionality by using bind(IPAddress.Any, ... or IPAddress.IPv6Any);
        public static IPAddress GetLocalRoutingInterface(IPAddress ipAddress)
        {
            Socket sock = null;
            IntPtr ptrInAddr = IntPtr.Zero;
            IntPtr ptrOutAddr = IntPtr.Zero;

            if ( ipAddress.AddressFamily == AddressFamily.InterNetwork )
            {
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sockaddr_in inAddr = new sockaddr_in();
                sockaddr_in outAddr = new sockaddr_in();

                try 
                {
                    ipAddress.GetAddressBytes().CopyTo(inAddr.sin_addr, 0);

                    // create a sockaddr_in function for our destination IP address
                    inAddr.sin_port = IPAddress.HostToNetworkOrder(port);

                    // create an block of unmanaged memory for use by Marshal.StructureToPtr.  We seem to need to do this, even though
                    // StructureToPtr will go ahead and release/reallocate the memory
                    ptrInAddr = Marshal.AllocCoTaskMem(Marshal.SizeOf(inAddr));

                    // Copy inAddr from managed to unmanaged, reallocating the unmanaged memory
                    Marshal.StructureToPtr(inAddr, ptrInAddr, true);

                    // Create a managed byte array to hold the structure, but in byte array form
                    byte[] byteInAddr = new byte[Marshal.SizeOf(inAddr)];

                    // Copy the structure from unmanaged ptr into managed byte array
                    Marshal.Copy(ptrInAddr, byteInAddr, 0, byteInAddr.Length);

                    // Create a second managed byte array to hold the output sockaddr_in structure
                    byte[] byteOutAddr = new byte[Marshal.SizeOf(inAddr)];

                    // Make the call to IOControl, asking for the Interface we should use if we want to route a packet to inAddr
                    sock.IOControl(
                        SIO_ROUTING_INTERFACE_QUERY,
                        byteInAddr,
                        byteOutAddr
                        );

                    // create the memory placeholder for our local interface
          
                    // Copy the results from the byteOutAddr into an unmanaged pointer
                    ptrOutAddr = Marshal.AllocCoTaskMem(Marshal.SizeOf(outAddr));
                    Marshal.Copy(byteOutAddr, 0, ptrOutAddr, byteOutAddr.Length);
          
                    // Copy the data from the unmanaged pointer to the ourAddr structure
                    Marshal.PtrToStructure(ptrOutAddr, outAddr);
                }
                catch(SocketException se)
                {
                    // Perhaps there were no interfaces present, AKA No Network Adapters enabled/installed and connected to media (wired or wireless)
                    EventLog.WriteEntry("RtpListener", se.ToString(), EventLogEntryType.Warning, 99);
                }
                finally
                {
                    // Release the socket
                    sock = null;

                    Marshal.FreeCoTaskMem(ptrInAddr);
                    Marshal.FreeCoTaskMem(ptrOutAddr);
                }

                // Return an IPAddress structure that is initialized with the value of the IP address contained in the outAddr structure
                if (outAddr != null)
                {
                    int len = outAddr.sin_addr.Length;

                    // Have to convert the byte[] to a uint.  It turns out that the IPAddress ctor won't create an IPv4 address from four bytes, it only uses the byte[] ctor for 16 byte IPv6 construction?!?
                    uint ipAsInt = 0;

                    for (int i = len; i > 0; i--)
                    {
                        ipAsInt = ipAsInt * 256 + outAddr.sin_addr[i - 1];
                    }
                    externalInterface = new IPAddress(ipAsInt);
                    return(new IPAddress(ipAsInt));
                }
                else
                {
                    return null;
                }

            }

            if ( Socket.OSSupportsIPv6 && ipAddress.AddressFamily == AddressFamily.InterNetworkV6 )
            {
                sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
                sockaddr_in6 inAddr = new sockaddr_in6();
                sockaddr_in6 outAddr = new sockaddr_in6();

                try 
                {
                    ipAddress.GetAddressBytes().CopyTo(inAddr.sin_addr, 0);

                    // create a sockaddr_in function for our destination IP address
                    inAddr.sin_port = IPAddress.HostToNetworkOrder(port);

                    // create an block of unmanaged memory for use by Marshal.StructureToPtr.  We seem to need to do this, even though
                    // StructureToPtr will go ahead and release/reallocate the memory
                    ptrInAddr = Marshal.AllocCoTaskMem(Marshal.SizeOf(inAddr));

                    // Copy inAddr from managed to unmanaged, reallocating the unmanaged memory
                    Marshal.StructureToPtr(inAddr, ptrInAddr, true);

                    // Create a managed byte array to hold the structure, but in byte array form
                    byte[] byteInAddr = new byte[Marshal.SizeOf(inAddr)];

                    // Copy the structure from unmanaged ptr into managed byte array
                    Marshal.Copy(ptrInAddr, byteInAddr, 0, byteInAddr.Length);

                    // Create a second managed byte array to hold the output sockaddr_in structure
                    byte[] byteOutAddr = new byte[Marshal.SizeOf(inAddr)];

                    // Make the call to IOControl, asking for the Interface we should use if we want to route a packet to inAddr

                    sock.IOControl(
                        SIO_ROUTING_INTERFACE_QUERY,
                        byteInAddr,
                        byteOutAddr
                        );

                    // create the memory placeholder for our local interface
                    // Copy the results from the byteOutAddr into an unmanaged pointer
                    ptrOutAddr = Marshal.AllocCoTaskMem(Marshal.SizeOf(outAddr));
                    Marshal.Copy(byteOutAddr, 0, ptrOutAddr, byteOutAddr.Length);
          
                    // Copy the data from the unmanaged pointer to the ourAddr structure
                    Marshal.PtrToStructure(ptrOutAddr, outAddr);
                }
                catch (SocketException se)
                {
                    // Perhaps there were no interfaces present, AKA No Network Adapters enabled/installed and connected to media (wired or wireless)
                    EventLog.WriteEntry("RtpListener", se.ToString(), EventLogEntryType.Warning, 99);
                }
                finally
                {
                    // Release the socket
                    sock = null;

                    Marshal.FreeCoTaskMem(ptrInAddr);
                    Marshal.FreeCoTaskMem(ptrOutAddr);
                }

                // Return an IPAddress structure that is initialized with the value of the IP address contained in the outAddr structure
                if (outAddr != null)
                {
                    externalInterface = new IPAddress(outAddr.sin_addr, outAddr.sin6_scope_id);
                    return (new IPAddress(outAddr.sin_addr, outAddr.sin6_scope_id));
                }
                else
                {
                    return null;
                }

            }
            return null;

        }
Ejemplo n.º 35
0
        public TcpListener(Dispatcher dispatcher, Ipv4Address addr, uint16_t port)
        {
            this.dispatcher = dispatcher;
            string message;

            listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listener == -1)
            {
                message = "socket failed, " + lastErrorMessage();
            }
            else
            {
                int flags = fcntl(listener, F_GETFL, 0);
                if (flags == -1 || fcntl(listener, F_SETFL, flags | O_NONBLOCK) == -1)
                {
                    message = "fcntl failed, " + lastErrorMessage();
                }
                else
                {
                    int on = 1;
                    if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, on, sizeof(int)) == -1)
                    {
                        message = "setsockopt failed, " + lastErrorMessage();
                    }
                    else
                    {
                        sockaddr_in address = new sockaddr_in();
                        address.sin_family      = AF_INET;
                        address.sin_port        = htons(port);
                        address.sin_addr.s_addr = htonl(addr.getValue());
//C++ TO C# CONVERTER TODO TASK: There is no equivalent to 'reinterpret_cast' in C#:
                        if (bind(listener, reinterpret_cast <sockaddr>(address), sizeof(sockaddr_in)) != 0)
                        {
                            message = "bind failed, " + lastErrorMessage();
                        }
                        else if (listen(listener, SOMAXCONN) != 0)
                        {
                            message = "listen failed, " + lastErrorMessage();
                        }
                        else
                        {
                            epoll_event listenEvent = new epoll_event();
                            listenEvent.events   = EPOLLONESHOT;
                            listenEvent.data.ptr = null;

                            if (epoll_ctl(dispatcher.getEpoll(), EPOLL_CTL_ADD, listener, listenEvent) == -1)
                            {
                                message = "epoll_ctl failed, " + lastErrorMessage();
                            }
                            else
                            {
                                context = null;
                                return;
                            }
                        }
                    }
                }

                int result = close(listener);
                if (result != 0)
                {
                }
                Debug.Assert(result != -1);
            }

            throw new System.Exception("TcpListener::TcpListener, " + message);
        }