From 318d55fd10c351454169aa00db352b785e53d294 Mon Sep 17 00:00:00 2001 From: Pieter Hintjens Date: Wed, 18 Apr 2012 13:14:07 -0500 Subject: [PATCH] Fixed issue LIBZMQ-358 --- src/device.cpp | 74 ++++++++++++++++---------------------------------- 1 file changed, 24 insertions(+), 50 deletions(-) diff --git a/src/device.cpp b/src/device.cpp index d3e73e40..4d4ab797 100644 --- a/src/device.cpp +++ b/src/device.cpp @@ -32,89 +32,63 @@ int zmq::device (class socket_base_t *insocket_, { msg_t msg; int rc = msg.init (); - - if (rc != 0) { + if (rc != 0) return -1; - } - int64_t more; + // The algorithm below assumes ratio of request and replies processed + // under full load to be 1:1. + + int more; size_t moresz; - - zmq_pollitem_t items [2]; - items [0].socket = insocket_; - items [0].fd = 0; - items [0].events = ZMQ_POLLIN; - items [0].revents = 0; - items [1].socket = outsocket_; - items [1].fd = 0; - items [1].events = ZMQ_POLLIN; - items [1].revents = 0; - + zmq_pollitem_t items [] = { + { insocket_, 0, ZMQ_POLLIN, 0 }, + { outsocket_, 0, ZMQ_POLLIN, 0 } + }; while (true) { - // Wait while there are either requests or replies to process. rc = zmq_poll (&items [0], 2, -1); - if (unlikely (rc < 0)) { + if (unlikely (rc < 0)) return -1; - } - - // The algorithm below asumes ratio of request and replies processed - // under full load to be 1:1. Although processing requests replies - // first is tempting it is suspectible to DoS attacks (overloading - // the system with unsolicited replies). // Process a request. if (items [0].revents & ZMQ_POLLIN) { while (true) { - rc = insocket_->recv (&msg, 0); - if (unlikely (rc < 0)) { + if (unlikely (rc < 0)) return -1; - } - + moresz = sizeof (more); rc = insocket_->getsockopt (ZMQ_RCVMORE, &more, &moresz); - if (unlikely (rc < 0)) { + if (unlikely (rc < 0)) return -1; - } - - rc = outsocket_->send (&msg, more ? ZMQ_SNDMORE : 0); - if (unlikely (rc < 0)) { + + rc = outsocket_->send (&msg, more? ZMQ_SNDMORE: 0); + if (unlikely (rc < 0)) return -1; - } - - if (!more) + if (more == 0) break; } } - // Process a reply. if (items [1].revents & ZMQ_POLLIN) { while (true) { - rc = outsocket_->recv (&msg, 0); - if (unlikely (rc < 0)) { + if (unlikely (rc < 0)) return -1; - } - + moresz = sizeof (more); rc = outsocket_->getsockopt (ZMQ_RCVMORE, &more, &moresz); - if (unlikely (rc < 0)) { + if (unlikely (rc < 0)) return -1; - } - - rc = insocket_->send (&msg, more ? ZMQ_SNDMORE : 0); - if (unlikely (rc < 0)) { + + rc = insocket_->send (&msg, more? ZMQ_SNDMORE: 0); + if (unlikely (rc < 0)) return -1; - } - - if (!more) + if (more == 0) break; } } } - return 0; } -