Ejemplo n.º 1
0
 public static bool PollOut(this ZSocket socket, ZPollItem item, ZMessage outgoing, out ZError error, TimeSpan?timeout = null)
 {
     if (outgoing == null)
     {
         throw new ArgumentNullException("outgoing");
     }
     return(Poll(socket, item, ZPoll.Out, ref outgoing, out error, timeout));
 }
Ejemplo n.º 2
0
        public ZMessage Duplicate()
        {
            var message = new ZMessage();

            foreach (ZFrame frame in this)
            {
                message.Add(frame.Duplicate());
            }
            return(message);
        }
        static bool ReceiveMsg(ZSocket sock, ref ZMessage message, out string address, out ZError error)
        {
            error = ZError.None;
            // address = IPAddress.None;
            address = string.Empty;

            // STREAM: read frames: identity, body

            // read the ip4 address from (ZFrame)frame.GetOption("Peer-Address")

            int receiveCount = 2;

            do
            {
                var frame = ZFrame.CreateEmpty();

                while (-1 == zmq.msg_recv(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More)))
                {
                    error = ZError.GetLastErr();

                    if (error == ZError.EINTR)
                    {
                        error = default(ZError);
                        continue;
                    }

                    frame.Dispose();
                    return(false);
                }

                if (message == null)
                {
                    message = new ZMessage();
                }
                message.Add(frame);

                if (receiveCount == 2)
                {
                    if (default(string) == (address = frame.GetOption("Peer-Address", out error)))
                    {
                        // just ignore
                        error   = default(ZError);
                        address = string.Empty;
                    }
                }
            } while (--receiveCount > 0);

            return(true);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 检查下标是否有数据
        /// </summary>
        /// <param name="index"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool CheckOut(int index, out ZMessage message)
        {
            zmq_pollitem_posix_t *native = ((zmq_pollitem_posix_t *)Ptr.Ptr) + index;

            if (native->ReadyEvents == 0)
            {
                message = null;
                return(false);
            }
            if (!((ZPollEvent)native->ReadyEvents).HasFlag(ZPollEvent.Out))
            {
                message = null;
                return(false);
            }
            return(Sockets[index].Recv(out message, 1));
        }
        /// <summary>
        /// Forwards requests from the frontend socket to the backend socket.
        /// </summary>
        protected override bool FrontendHandler(ZSocket sock, out ZMessage message, out ZError error)
        {
            error   = default(ZError);
            message = null;

            // receiving scope
            // STREAM: get 2 frames, identity and body
            ZMessage incoming = null;
            // IPAddress address = null;
            string address;

            if (!ReceiveMsg(sock, ref incoming, out address, out error))
            {
                return(false);
            }

            // sending scope
            // DEALER: forward
            using (incoming)
            {
                if (incoming[1].Length == 0)
                {
                    return(true);                    // Ignore the Empty one
                }

                // Prepend empty delimiter between Identity frame and Data frame
                incoming.Insert(1, new ZFrame());

                // Prepend Peer-Address
                incoming.Insert(2, new ZFrame(address));

                try
                {
                    if (!BackendSocket.Send(incoming, /* ZSocketFlags.DontWait, */ out error))
                    {
                        return(false);
                    }
                }
                finally {
                    incoming.Dismiss();
                }
            }

            return(true);
        }
Ejemplo n.º 6
0
        internal static bool OnSendMessage(ZSocket socket, ZPollItem item, ZMessage message)
        {
            if (((ZPoll)item.ReadyEvents & ZPoll.Out) == ZPoll.Out)
            {
                ZError sendWorkerE;
                if (item.SendMessage == null)
                {
                    // throw?
                }
                else if (item.SendMessage(socket, message, out sendWorkerE))
                {
                    // what to do?

                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 7
0
            /// <summary>
            /// Send a ZAP reply to the handler socket
            /// </summary>
            /// <param name="status_code"></param>
            /// <param name="status_text"></param>
            /// <param name="metadata"></param>
            /// <returns></returns>
            public int RequestReply(string status_code, string status_text, byte[] metadata)
            {
                if (Verbose)
                {
                    ZAuth.Info(string.Format("zauth: - ZAP reply status_code={0} status_text={1}", status_code, status_text));
                }

                ZMessage msg = new ZMessage();

                msg.Add(new ZFrame("1.0"));
                msg.Add(new ZFrame(Sequence));
                msg.Add(new ZFrame(status_code));
                msg.Add(new ZFrame(status_text));
                msg.Add(new ZFrame(UserId != null ? UserId : ""));
                // rc = zmsg_addmem(msg, metadata, metasize);
                msg.Add(new ZFrame(metadata));
                handler.SendMessage(msg);
                return(0);
            }
Ejemplo n.º 8
0
        internal static bool OnReceiveMessage(ZSocket socket, ZPollItem item, out ZMessage message)
        {
            message = null;

            if (((ZPoll)item.ReadyEvents & ZPoll.In) == ZPoll.In)
            {
                ZError recvWorkerE;
                if (item.ReceiveMessage == null)
                {
                    // throw?
                }
                else if (item.ReceiveMessage(socket, out message, out recvWorkerE))
                {
                    // what to do?

                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// Forwards replies from the backend socket to the frontend socket.
        /// </summary>
        protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error)
        {
            error   = default(ZError);
            message = null;

            // receiving scope
            // DEALER: normal movemsg
            ZMessage incoming = null;

            if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error))
            {
                return(false);
            }

            using (incoming)
            {
                // STREAM: write frames: identity, body, identity, empty
                // Read identity
                int ic            = (int)incoming[0].Length;
                var identityBytes = new byte[ic];
                incoming[0].Read(identityBytes, 0, ic);

                // Remove DEALER's delimiter
                incoming.RemoveAt(1);

                // Append Identity frame
                var identity0 = new ZFrame(identityBytes);
                incoming.Add(identity0);

                // Append STREAM's empty delimiter frame
                incoming.Add(new ZFrame());

                if (!SendMsg(FrontendSocket, incoming, out error))
                {
                    return(false);
                }
            }

            return(true);
        }
        static bool SendMsg(ZSocket sock, ZMessage msg, out ZError error)
        {
            error = ZError.None;

            try
            {
                foreach (ZFrame frame in msg)
                {
                    while (-1 == zmq.msg_send(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More)))
                    {
                        error = ZError.GetLastErr();

                        if (error == ZError.EINTR)
                        {
                            error = default(ZError);
                            continue;
                        }

                        /* if (error == ZError.EAGAIN)
                         * {
                         *      error = default(ZError);
                         *      Thread.Sleep(1);
                         *
                         *      continue;
                         * } */

                        return(false);
                    }
                }
            }
            finally
            {
                msg.Dismiss();
            }

            return(true);
        }
Ejemplo n.º 11
0
        internal static bool PollManyResult(IEnumerable <ZSocket> sockets, IEnumerable <ZPollItem> items, ZPoll pollEvents, ref ZMessage[] messages)
        {
            int count      = items.Count();
            int readyCount = 0;

            bool send    = messages != null && ((pollEvents & ZPoll.Out) == ZPoll.Out);
            bool receive = ((pollEvents & ZPoll.In) == ZPoll.In);

            ZMessage[] incoming = null;
            if (receive)
            {
                incoming = new ZMessage[count];
            }

            for (int i = 0; i < count; ++i)
            {
                ZSocket   socket  = sockets.ElementAt(i);
                ZPollItem item    = items.ElementAt(i);
                ZMessage  message = send ? messages[i] : null;

                if (ZPollItems.PollSingleResult(socket, item, pollEvents, ref message))
                {
                    ++readyCount;
                }
                if (receive)
                {
                    incoming[i] = message;
                }
            }

            if (receive)
            {
                messages = incoming;
            }
            return(readyCount > 0);
        }
Ejemplo n.º 12
0
 public static bool PollIn(this ZSocket socket, ZPollItem item, out ZMessage incoming, out ZError error, TimeSpan?timeout = null)
 {
     incoming = null;
     return(Poll(socket, item, ZPoll.In, ref incoming, out error, timeout));
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Not implemented for the <see cref="StreamerDevice"/>.
 /// </summary>
 protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 14
0
 public static bool DefaultSendMessage(ZSocket socket, ZMessage message, out ZError error)
 {
     return(socket.Send(message, out error));
 }
Ejemplo n.º 15
0
        private void Authenticate(ZMessage zMessage)
        {
            ZAP request = new ZAP(sockets[HANDLER], zMessage, verbose);
            //  Is address explicitly whitelisted or blacklisted?
            bool allowed = false;
            bool denied  = false;

            if (whitelist.Count > 0)
            {
                if (whitelist.Contains(request.Address))
                {
                    allowed = true;
                    if (verbose)
                    {
                        Info("zauth: - passed (whitelist) address=" + request.Address);
                    }
                }
                else
                {
                    denied = true;
                    if (verbose)
                    {
                        Info("zauth: - denied (whitelist) address=" + request.Address);
                    }
                }
            }

            if (blacklist.Count > 0)
            {
                if (blacklist.Contains(request.Address))
                {
                    denied = true;
                    if (verbose)
                    {
                        Info("zauth: - denied (blacklist) address=" + request.Address);
                    }
                }
                else
                {
                    allowed = true;
                    if (verbose)
                    {
                        Info("zauth: -  passed (not in blacklist) address=" + request.Address);
                    }
                }
            }

            //  Curve certificate metadata
            List <byte> metabuf        = new List <byte>(512);
            int         metadataLength = 0;

            //  Mechanism-specific checks
            if (!denied)
            {
                if (request.Mechanism.ToUpper() == "NULL" && !allowed)
                {
                    //  For NULL, we allow if the address wasn't blacklisted
                    if (verbose)
                    {
                        Info("zauth: - allowed (NULL)");
                    }
                    allowed = true;
                }
                else
                if (request.Mechanism == "PLAIN")
                {
                    //  For PLAIN, even a whitelisted address must authenticate
                    allowed = AuthenticatePlain(request);
                }
                else
                if (request.Mechanism == "CURVE")
                {
                    //  For CURVE, even a whitelisted address must authenticate
                    allowed = AuthenticateCurve(request, metabuf, out metadataLength);
                }
                else
                if (request.Mechanism == "GSSAPI")
                {
                    //  For GSSAPI, even a whitelisted address must authenticate
                    allowed = AuthenticateGssapi(request);
                }
            }

            if (allowed)
            {
                //size_t metasize = metadata - metabuf;
                //s_zap_request_reply(request, "200", "OK", metabuf, metasize);
                request.RequestReply("200", "OK", metabuf.GetRange(0, metadataLength).ToArray());
            }
            else

            {
                //s_zap_request_reply(request, "400", "No access", (unsigned char *) "", 0);
                request.RequestReply("400", "No access", new byte[0]);
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Forwards requests from the frontend socket to the backend socket.
 /// </summary>
 protected override bool FrontendHandler(ZSocket args, out ZMessage message, out ZError error)
 {
     return(FrontendSocket.Forward(BackendSocket, out message, out error));
 }
Ejemplo n.º 17
0
        internal static bool PollSingleResult(ZSocket socket, ZPollItem item, ZPoll pollEvents, ref ZMessage message)
        {
            bool shouldReceive = item.ReceiveMessage != null && ((pollEvents & ZPoll.In) == ZPoll.In);
            bool shouldSend    = item.SendMessage != null && ((pollEvents & ZPoll.Out) == ZPoll.Out);

            if (pollEvents == ZPoll.In)
            {
                if (!shouldReceive)
                {
                    throw new InvalidOperationException("No ReceiveMessage delegate set for Poll.In");
                }

                if (OnReceiveMessage(socket, item, out message))
                {
                    if (!shouldSend)
                    {
                        return(true);
                    }

                    if (OnSendMessage(socket, item, message))
                    {
                        return(true);
                    }
                }
            }
            else if (pollEvents == ZPoll.Out)
            {
                if (!shouldSend)
                {
                    throw new InvalidOperationException("No SendMessage delegate set for Poll.Out");
                }

                if (OnSendMessage(socket, item, message))
                {
                    if (!shouldReceive)
                    {
                        return(true);
                    }

                    if (OnReceiveMessage(socket, item, out message))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 18
0
 public static bool Poll(this ZSocket socket, ZPollItem item, ZPoll pollEvents, ref ZMessage message, out ZError error, TimeSpan?timeout = null)
 {
     if (PollSingle(socket, item, pollEvents, out error, timeout))
     {
         if (PollSingleResult(socket, item, pollEvents, ref message))
         {
             return(true);
         }
         error = ZError.EAGAIN;
     }
     return(false);
 }
Ejemplo n.º 19
0
 public static bool DefaultReceiveMessage(ZSocket socket, out ZMessage message, out ZError error)
 {
     message = null;
     return(socket.ReceiveMessage(ref message, out error));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Invoked when a message has been received by the frontend socket.
 /// </summary>
 /// <param name="args">A <see cref="SocketEventArgs"/> object containing the poll event args.</param>
 protected abstract bool FrontendHandler(ZSocket socket, out ZMessage message, out ZError error);
Ejemplo n.º 21
0
 /// <summary>
 /// Invoked when a message has been received by the backend socket.
 /// </summary>
 /// <param name="args">A <see cref="SocketEventArgs"/> object containing the poll event args.</param>
 protected abstract bool BackendHandler(ZSocket args, out ZMessage message, out ZError error);
Ejemplo n.º 22
0
        private int HandlePipe(ZMessage request)
        {
            if (request.Count == 0)
            {
                return(-1);                  //  Interrupted
            }
            ZFrame commandFrame = request.Pop();
            string command      = commandFrame.ReadLine();

            if (verbose)
            {
                Info("zauth: API command=" + command);
            }

            if (command == "ALLOW")
            {
                while (request.Count > 0)
                {
                    ZFrame frame   = request.Pop();
                    string address = frame.ReadLine();
                    if (verbose)
                    {
                        Info("zauth: - whitelisting ipaddress=" + address);
                    }

                    if (!whitelist.Contains(address))
                    {
                        whitelist.Add(address);
                    }
                }
                //
                sockets[PIPE].SendFrame(new ZFrame(0));
            }
            else
            if (command == "DENY")
            {
                while (request.Count > 0)
                {
                    ZFrame frame   = request.Pop();
                    string address = frame.ReadLine();
                    if (verbose)
                    {
                        Info("zauth: - blacklisting ipaddress=" + address);
                    }

                    if (!blacklist.Contains(address))
                    {
                        blacklist.Add(address);
                    }
                    if (whitelist.Contains(address))
                    {
                        whitelist.Remove(address);
                    }
                }
                sockets[PIPE].SendFrame(new ZFrame(0));
            }
            else
            if (command == "PLAIN")
            {
                //  Get password file and load into zhash table
                //  If the file doesn't exist we'll get an empty table
                ZFrame frame    = request.Pop();
                string filename = frame.ReadLine();
                if (Load(out passwords, filename) != 0 && verbose)
                {
                    Info("zauth: could not load file=" + filename);
                }
                sockets[PIPE].SendFrame(new ZFrame(0));
            }
            else
            if (command == "CURVE")
            {
                //  If location is CURVE_ALLOW_ANY, allow all clients. Otherwise
                //  treat location as a directory that holds the certificates.
                ZFrame frame    = request.Pop();
                string location = frame.ReadLine();
                if (location == CURVE_ALLOW_ANY)
                {
                    allowAny = true;
                }
                else
                {
                    certStore = new ZCertStore(location);
                    allowAny  = false;
                }
                sockets[PIPE].SendFrame(new ZFrame(0));
            }
            else
            if (command == "GSSAPI")
            {
                //  GSSAPI authentication is not yet implemented here
                sockets[PIPE].SendFrame(new ZFrame(0));
            }
            else
            if (command == "VERBOSE")
            {
                verbose = true;
                sockets[PIPE].SendFrame(new ZFrame(0));
            }
            else
            if (command == "$TERM")
            {
                Terminated = true;
            }
            else
            {
                Error("zauth: - invalid command: " + command);
            }
            return(0);
        }
Ejemplo n.º 23
0
            /// <summary>
            /// Receive a valid ZAP request from the handler socket
            /// </summary>
            /// <param name="handler"></param>
            /// <param name="request"></param>
            /// <param name="verbose"></param>
            public ZAP(ZSocket handler, ZMessage request, bool verbose)
            {
                //  Store handler socket so we can send a reply easily
                this.handler = handler;
                Verbose      = verbose;

                if (request.Count == 0)
                {
                    return;
                }

                //  Get all standard frames off the handler socket
                Version   = request.Pop().ReadLine();
                Sequence  = request.Pop().ReadLine();
                Domain    = request.Pop().ReadLine();
                Address   = request.Pop().ReadLine();
                Identity  = request.Pop().ReadLine();
                Mechanism = request.Pop().ReadLine();

                Mechanism = string.IsNullOrEmpty(Mechanism) ? "" : Mechanism;
                Version   = string.IsNullOrEmpty(Version) ? "" : Version;
                Sequence  = string.IsNullOrEmpty(Sequence) ? "" : Sequence;
                Domain    = string.IsNullOrEmpty(Domain) ? "" : Domain;
                Address   = string.IsNullOrEmpty(Address) ? "" : Address;
                Identity  = string.IsNullOrEmpty(Identity) ? "" : Identity;


                //  If the version is wrong, we're linked with a bogus libzmq, so die
                if (Version != "1.0")
                {
                    return;
                }

                //  Get mechanism-specific frames
                if (Mechanism == "PLAIN")
                {
                    Username = request.Pop().ReadLine();
                    Password = request.Pop().ReadLine();
                    Username = string.IsNullOrEmpty(Username) ? "" : Username;
                    Password = string.IsNullOrEmpty(Password) ? "" : Password;
                }
                else
                if (Mechanism == "CURVE")
                {
                    ZFrame frame = request.Pop();

                    if (frame.Length != 32)
                    {
                        return;
                    }
                    ZCert cert = new ZCert(frame.Read(), new byte[32]);
                    ClientTxt = cert.PublicTxt;
                }
                else
                if (Mechanism == "GSSAPI")
                {
                    Principal = request.Pop().ReadLine();
                }

                if (Verbose)
                {
                    ZAuth.Info(string.Format("zauth: ZAP request mechanism={0} ipaddress={1}", Mechanism, Address));
                }
            }