public override void Open (string path, bool @abstract) { if (String.IsNullOrEmpty (path)) throw new ArgumentException ("path"); if (@abstract) socket = OpenAbstractUnix (path); else socket = OpenUnix (path); //socket.Blocking = true; SocketHandle = (long)socket.Handle; //Stream = new UnixStream ((int)socket.Handle); Stream = new UnixStream (socket); }
bool AcceptClient(UnixSocket csock, out ServerConnection conn) { //TODO: use the right abstraction here, probably using the Server class UnixNativeTransport transport = new UnixNativeTransport(); //client.Client.Blocking = true; transport.socket = csock; transport.SocketHandle = (long)csock.Handle; transport.Stream = new UnixStream(csock); //Connection conn = new Connection (transport); //Connection conn = new ServerConnection (transport); //ServerConnection conn = new ServerConnection (transport); conn = new ServerConnection(transport); conn.Server = this; conn.Id = Id; if (conn.Transport.Stream.ReadByte() != 0) return false; conn.isConnected = true; SaslPeer remote = new SaslPeer(); remote.stream = transport.Stream; SaslServer local = new SaslServer(); local.stream = transport.Stream; local.Guid = Id; local.Peer = remote; remote.Peer = local; bool success = local.Authenticate(); Console.WriteLine("Success? " + success); if (!success) return false; conn.UserId = ((SaslServer)local).uid; conn.isAuthenticated = true; return true; }
//send peer credentials null byte //different platforms do this in different ways #if HAVE_CMSGCRED unsafe void WriteBsdCred() { //null credentials byte byte buf = 0; IOVector iov = new IOVector(); //iov.Base = (IntPtr)(&buf); iov.Base = &buf; iov.Length = 1; msghdr msg = new msghdr(); msg.msg_iov = &iov; msg.msg_iovlen = 1; cmsg cm = new cmsg(); msg.msg_control = (IntPtr)(&cm); msg.msg_controllen = (uint)sizeof(cmsg); cm.hdr.cmsg_len = (uint)sizeof(cmsg); cm.hdr.cmsg_level = 0xffff; //SOL_SOCKET cm.hdr.cmsg_type = 0x03; //SCM_CREDS int written = new UnixSocket((int)SocketHandle, false).SendMsg(&msg, 0); if (written != 1) { throw new Exception("Failed to write credentials"); } }
internal UnixSocket OpenAbstractUnix(string path) { byte[] sa = GetSockAddrAbstract(path); UnixSocket client = new UnixSocket(); client.Connect(sa); return(client); }
public override void Listen() { byte[] sa = isAbstract ? UnixNativeTransport.GetSockAddrAbstract(unixPath) : UnixNativeTransport.GetSockAddr(unixPath); UnixSocket usock = new UnixSocket(); usock.Bind(sa); usock.Listen(50); while (true) { Console.WriteLine("Waiting for client on " + (isAbstract ? "abstract " : String.Empty) + "path " + unixPath); UnixSocket csock = usock.Accept(); Console.WriteLine("Client connected"); ServerConnection conn; if (!AcceptClient(csock, out conn)) { Console.WriteLine("Client rejected"); csock.Close(); continue; } //GLib.Idle.Add (delegate { if (NewConnection != null) { NewConnection(conn); } //BusG.Init (conn); /* * conn.Iterate (); * Console.WriteLine ("done iter"); * BusG.Init (conn); * Console.WriteLine ("done init"); */ //GLib.Idle.Add (delegate { BusG.Init (conn); return false; }); #if USE_GLIB BusG.Init(conn); #else new Thread(new ThreadStart(delegate { while (conn.IsConnected) { conn.Iterate(); } })).Start(); #endif Console.WriteLine("done init"); //return false; //}); } }
private async Task SendUnixSocketMessages(IEnumerable <SmartBrickMessage> messages) { foreach (var message in messages.Where(x => x != null)) { //Unix socket might close during processing if (!UnixSocket.IsRunning) { log.Warn("Unix socket was closed during sending"); return; } await UnixSocket.SendCommand(message); } }
bool AcceptClient(UnixSocket csock, out ServerConnection conn) { //TODO: use the right abstraction here, probably using the Server class UnixNativeTransport transport = new UnixNativeTransport(); //client.Client.Blocking = true; transport.socket = csock; transport.SocketHandle = (long)csock.Handle; transport.Stream = new UnixStream(csock); //Connection conn = new Connection (transport); //Connection conn = new ServerConnection (transport); //ServerConnection conn = new ServerConnection (transport); conn = new ServerConnection(transport); conn.Server = this; //conn.Id = Id; if (conn.Transport.Stream.ReadByte() != 0) { return(false); } //conn.isConnected = true; SaslPeer remote = new SaslPeer(); remote.stream = transport.Stream; SaslServer local = new SaslServer(); local.stream = transport.Stream; local.Guid = Id; local.Peer = remote; remote.Peer = local; bool success = local.Authenticate(); Console.WriteLine("Success? " + success); if (!success) { return(false); } conn.UserId = ((SaslServer)local).uid; //conn.isAuthenticated = true; return(true); }
private GeneralSocket CreateSocket(AddressFamily sockType, string address, int port) { GeneralSocket socket = null; switch (sockType) { case AddressFamily.Unix: socket = new UnixSocket(address); break; case AddressFamily.InterNetwork: IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(address), port); socket = new TcpSocket(localEP); break; } return(socket); }
public override void Open(string path, bool @abstract) { if (String.IsNullOrEmpty(path)) { throw new ArgumentException("path"); } if (@abstract) { socket = OpenAbstractUnix(path); } else { socket = OpenUnix(path); } //socket.Blocking = true; SocketHandle = (long)socket.Handle; //Stream = new UnixStream ((int)socket.Handle); Stream = new UnixStream(socket); }
//TODO: complete this test daemon/server example, and a client //TODO: maybe generalise it and integrate it into the core public static void Main(string[] args) { bool isServer; if (args.Length == 1 && args[0] == "server") { isServer = true; } else if (args.Length == 1 && args[0] == "client") { isServer = false; } else { Console.Error.WriteLine("Usage: test-server [server|client]"); return; } //string addr = "unix:abstract=/tmp/dbus-ABCDEFGHIJ"; string addr = "unix:path=/tmp/dbus-ABCDEFGHIJ"; Connection conn; ObjectPath myOpath = new ObjectPath("/org/ndesk/test"); string myNameReq = "org.ndesk.test"; if (!isServer) { conn = new Connection(Transport.Create(AddressEntry.Parse(addr))); DemoObject demo = conn.GetObject <DemoObject> (myNameReq, myOpath); demo.GiveNoReply(); //float ret = demo.Hello ("hi from test client", 21); float ret = 200; while (ret > 5) { ret = demo.Hello("hi from test client", (int)ret); Console.WriteLine("Returned float: " + ret); System.Threading.Thread.Sleep(1000); } } else { string path; bool abstr; AddressEntry entry = AddressEntry.Parse(addr); path = entry.Properties["path"]; UnixSocket server = new UnixSocket(); byte[] p = Encoding.Default.GetBytes(path); byte[] sa = new byte[2 + p.Length + 1]; //we use BitConverter to stay endian-safe byte[] afData = BitConverter.GetBytes(UnixSocket.AF_UNIX); sa[0] = afData[0]; sa[1] = afData[1]; for (int i = 0; i != p.Length; i++) { sa[2 + i] = p[i]; } sa[2 + p.Length] = 0; //null suffix for domain socket addresses, see unix(7) server.Bind(sa); //server.Listen (1); server.Listen(5); while (true) { Console.WriteLine("Waiting for client on " + addr); UnixSocket client = server.Accept(); Console.WriteLine("Client accepted"); //client.Blocking = true; //PeerCred pc = new PeerCred (client); //Console.WriteLine ("PeerCred: pid={0}, uid={1}, gid={2}", pc.ProcessID, pc.UserID, pc.GroupID); UnixNativeTransport transport = new UnixNativeTransport(); transport.Stream = new UnixStream(client.Handle); conn = new Connection(transport); //ConnectionHandler.Handle (conn); //in reality a thread per connection is of course too expensive ConnectionHandler hnd = new ConnectionHandler(conn); new Thread(new ThreadStart(hnd.Handle)).Start(); Console.WriteLine(); } } }
public override void Listen() { byte[] sa = isAbstract ? UnixNativeTransport.GetSockAddrAbstract(unixPath) : UnixNativeTransport.GetSockAddr(unixPath); UnixSocket usock = new UnixSocket(); usock.Bind(sa); usock.Listen(50); while (true) { Console.WriteLine("Waiting for client on " + (isAbstract ? "abstract " : String.Empty) + "path " + unixPath); UnixSocket csock = usock.Accept(); Console.WriteLine("Client connected"); ServerConnection conn; if (!AcceptClient(csock, out conn)) { Console.WriteLine("Client rejected"); csock.Close(); continue; } //GLib.Idle.Add (delegate { if (NewConnection != null) NewConnection(conn); //BusG.Init (conn); /* conn.Iterate (); Console.WriteLine ("done iter"); BusG.Init (conn); Console.WriteLine ("done init"); */ //GLib.Idle.Add (delegate { BusG.Init (conn); return false; }); #if USE_GLIB BusG.Init (conn); #else new Thread(new ThreadStart(delegate { while (conn.IsConnected) conn.Iterate(); })).Start(); #endif Console.WriteLine("done init"); //return false; //}); } }
//TODO: complete this test daemon/server example, and a client //TODO: maybe generalise it and integrate it into the core public static void Main (string[] args) { bool isServer; if (args.Length == 1 && args[0] == "server") isServer = true; else if (args.Length == 1 && args[0] == "client") isServer = false; else { Console.Error.WriteLine ("Usage: test-server [server|client]"); return; } //string addr = "unix:abstract=/tmp/dbus-ABCDEFGHIJ"; string addr = "unix:path=/tmp/dbus-ABCDEFGHIJ"; Connection conn; ObjectPath myOpath = new ObjectPath ("/org/ndesk/test"); string myNameReq = "org.ndesk.test"; if (!isServer) { conn = new Connection (Transport.Create (AddressEntry.Parse (addr))); DemoObject demo = conn.GetObject<DemoObject> (myNameReq, myOpath); demo.GiveNoReply (); //float ret = demo.Hello ("hi from test client", 21); float ret = 200; while (ret > 5) { ret = demo.Hello ("hi from test client", (int)ret); Console.WriteLine ("Returned float: " + ret); System.Threading.Thread.Sleep (1000); } } else { string path; bool abstr; AddressEntry entry = AddressEntry.Parse (addr); path = entry.Properties["path"]; UnixSocket server = new UnixSocket (); byte[] p = Encoding.Default.GetBytes (path); byte[] sa = new byte[2 + p.Length + 1]; //we use BitConverter to stay endian-safe byte[] afData = BitConverter.GetBytes (UnixSocket.AF_UNIX); sa[0] = afData[0]; sa[1] = afData[1]; for (int i = 0 ; i != p.Length ; i++) sa[2 + i] = p[i]; sa[2 + p.Length] = 0; //null suffix for domain socket addresses, see unix(7) server.Bind (sa); //server.Listen (1); server.Listen (5); while (true) { Console.WriteLine ("Waiting for client on " + addr); UnixSocket client = server.Accept (); Console.WriteLine ("Client accepted"); //client.Blocking = true; //PeerCred pc = new PeerCred (client); //Console.WriteLine ("PeerCred: pid={0}, uid={1}, gid={2}", pc.ProcessID, pc.UserID, pc.GroupID); UnixNativeTransport transport = new UnixNativeTransport (); transport.Stream = new UnixStream (client.Handle); conn = new Connection (transport); //ConnectionHandler.Handle (conn); //in reality a thread per connection is of course too expensive ConnectionHandler hnd = new ConnectionHandler (conn); new Thread (new ThreadStart (hnd.Handle)).Start (); Console.WriteLine (); } } }
public static void Main(string[] args) { string addr = "tcp:host=localhost,port=12345"; //string addr = "win:path=dbus-session"; bool shouldFork = false; for (int i = 0; i != args.Length; i++) { string arg = args[i]; //Console.Error.WriteLine ("arg: " + arg); /* * if (!arg.StartsWith ("--")) { * addr = arg; * continue; * } */ if (arg.StartsWith("--print-")) { string[] parts = arg.Split('='); int fd = 1; if (parts.Length > 1) { fd = Int32.Parse(parts[1]); } else if (args.Length > i + 1) { string poss = args[i + 1]; if (Int32.TryParse(poss, out fd)) { i++; } } TextWriter tw; if (fd == 1) { tw = Console.Out; } else if (fd == 2) { tw = Console.Error; } else { Stream fs = new UnixStream(fd); tw = new StreamWriter(fs, Encoding.ASCII); tw.NewLine = "\n"; } if (parts[0] == "--print-address") { tw.WriteLine(addr); } //else if (parts[0] == "--print-pid") { // int pid = System.Diagnostics.Process.GetCurrentProcess ().Id; ; // tw.WriteLine (pid); //} else { continue; } //throw new Exception (); tw.Flush(); continue; } switch (arg) { case "--version": //Console.WriteLine ("D-Bus Message Bus Daemon " + Introspector.GetProductDescription ()); Console.WriteLine("D-Bus Message Bus Daemon " + "0.1"); return; case "--system": break; case "--session": break; case "--fork": shouldFork = true; break; case "--introspect": { Introspector intro = new Introspector(); intro.root_path = ObjectPath.Root; intro.WriteStart(); intro.WriteType(typeof(org.freedesktop.DBus.IBus)); intro.WriteEnd(); Console.WriteLine(intro.Xml); } return; default: break; } } /* * if (args.Length >= 1) { * addr = args[0]; * } */ int childPid; if (shouldFork) { childPid = (int)UnixSocket.fork(); //if (childPid != 0) // return; } else { childPid = System.Diagnostics.Process.GetCurrentProcess().Id; } if (childPid != 0) { for (int i = 0; i != args.Length; i++) { string arg = args[i]; //Console.Error.WriteLine ("arg: " + arg); /* * if (!arg.StartsWith ("--")) { * addr = arg; * continue; * } */ if (arg.StartsWith("--print-")) { string[] parts = arg.Split('='); int fd = 1; if (parts.Length > 1) { fd = Int32.Parse(parts[1]); } else if (args.Length > i + 1) { string poss = args[i + 1]; if (Int32.TryParse(poss, out fd)) { i++; } } TextWriter tw; if (fd == 1) { tw = Console.Out; } else if (fd == 2) { tw = Console.Error; } else { Stream fs = new UnixStream(fd); tw = new StreamWriter(fs, Encoding.ASCII); tw.NewLine = "\n"; } //if (parts[0] == "--print-address") // tw.WriteLine (addr); if (parts[0] == "--print-pid") { int pid = childPid; tw.WriteLine(pid); } tw.Flush(); continue; } } } if (shouldFork && childPid != 0) { return; //Environment.Exit (1); } //if (shouldFork && childPid == 0) { if (shouldFork) { /* * Console.In.Dispose (); * Console.Out.Dispose (); * Console.Error.Dispose (); */ int O_RDWR = 2; int devnull = UnixSocket.open("/dev/null", O_RDWR); UnixSocket.dup2(devnull, 0); UnixSocket.dup2(devnull, 1); UnixSocket.dup2(devnull, 2); //UnixSocket.close (0); //UnixSocket.close (1); //UnixSocket.close (2); if (UnixSocket.setsid() == (IntPtr)(-1)) { throw new Exception(); } } RunServer(addr); //Console.Error.WriteLine ("Usage: dbus-daemon [address]"); }
public static bool TryCreateUnixSocket(string path, out Socket socket, string perm = null) { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("path must not be empty", "path"); socket = null; try { string realPath; if (path.StartsWith ("\\0", StringComparison.Ordinal) && path.IndexOf ("\\0", 1, StringComparison.Ordinal) < 0) realPath = '\0' + path.Substring (2); else realPath = path; if (perm == null) { socket = new UnixSocket (realPath); Logger.Write (LogLevel.Debug, "Listening on file {0} with default permissions", realPath); } else { ushort uperm; if (!UInt16.TryParse (perm, out uperm)) { Logger.Write (LogLevel.Error, "Error parsing permissions \"{0}\". Use octal.", perm); return false; } uperm = Convert.ToUInt16 (uperm.ToString (), 8); socket = new UnixSocket (realPath, uperm); Logger.Write (LogLevel.Debug, "Listening on file {0} with permissions {1}", realPath, Convert.ToString (uperm, 8)); } } catch (System.Net.Sockets.SocketException e) { Logger.Write (LogLevel.Error, "Error creating the socket: {0}", e.Message); return false; } return true; }
internal UnixSocket OpenAbstractUnix (string path) { byte[] sa = GetSockAddrAbstract (path); UnixSocket client = new UnixSocket (); client.Connect (sa); return client; }