code
stringlengths
0
56.1M
repo_name
stringclasses
515 values
path
stringlengths
2
147
language
stringclasses
447 values
license
stringclasses
7 values
size
int64
0
56.8M
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <stdlib.h> #include <string.h> SETUP_TEARDOWN_TESTCONTEXT // SHALL receive incoming messages from its peers using a fair-queuing // strategy. void test_fair_queue_in (const char *bind_address_) { char connect_address[MAX_SOCKET_STRING]; void *receiver = test_context_socket (ZMQ_ROUTER); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (receiver, bind_address_)); size_t len = MAX_SOCKET_STRING; TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (receiver, ZMQ_LAST_ENDPOINT, connect_address, &len)); const unsigned char services = 5; void *senders[services]; for (unsigned char peer = 0; peer < services; ++peer) { senders[peer] = test_context_socket (ZMQ_DEALER); char *str = strdup ("A"); str[0] += peer; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (senders[peer], ZMQ_ROUTING_ID, str, 2)); free (str); TEST_ASSERT_SUCCESS_ERRNO ( zmq_connect (senders[peer], connect_address)); } msleep (SETTLE_TIME); zmq_msg_t msg; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&msg)); s_send_seq (senders[0], "M", SEQ_END); s_recv_seq (receiver, "A", "M", SEQ_END); s_send_seq (senders[0], "M", SEQ_END); s_recv_seq (receiver, "A", "M", SEQ_END); int sum = 0; // send N requests for (unsigned char peer = 0; peer < services; ++peer) { s_send_seq (senders[peer], "M", SEQ_END); sum += 'A' + peer; } TEST_ASSERT_EQUAL_INT (services * 'A' + services * (services - 1) / 2, sum); // handle N requests for (unsigned char peer = 0; peer < services; ++peer) { TEST_ASSERT_EQUAL_INT ( 2, TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, receiver, 0))); const char *id = static_cast<const char *> (zmq_msg_data (&msg)); sum -= id[0]; s_recv_seq (receiver, "M", SEQ_END); } TEST_ASSERT_EQUAL_INT (0, sum); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); test_context_socket_close_zero_linger (receiver); for (size_t peer = 0; peer < services; ++peer) test_context_socket_close_zero_linger (senders[peer]); // Wait for disconnects. msleep (SETTLE_TIME); } // SHALL create a double queue when a peer connects to it. If this peer // disconnects, the ROUTER socket SHALL destroy its double queue and SHALL // discard any messages it contains. void test_destroy_queue_on_disconnect (const char *bind_address_) { void *a = test_context_socket (ZMQ_ROUTER); int enabled = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (a, ZMQ_ROUTER_MANDATORY, &enabled, sizeof (enabled))); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (a, bind_address_)); size_t len = MAX_SOCKET_STRING; char connect_address[MAX_SOCKET_STRING]; TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (a, ZMQ_LAST_ENDPOINT, connect_address, &len)); void *b = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (b, ZMQ_ROUTING_ID, "B", 2)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (b, connect_address)); // Wait for connection. msleep (SETTLE_TIME); // Send a message in both directions s_send_seq (a, "B", "ABC", SEQ_END); s_send_seq (b, "DEF", SEQ_END); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (b, connect_address)); // Disconnect may take time and need command processing. zmq_pollitem_t poller[2] = {{a, 0, 0, 0}, {b, 0, 0, 0}}; TEST_ASSERT_SUCCESS_ERRNO (zmq_poll (poller, 2, 100)); TEST_ASSERT_SUCCESS_ERRNO (zmq_poll (poller, 2, 100)); // No messages should be available, sending should fail. zmq_msg_t msg; zmq_msg_init (&msg); TEST_ASSERT_FAILURE_ERRNO ( EHOSTUNREACH, zmq_send (a, "B", 2, ZMQ_SNDMORE | ZMQ_DONTWAIT)); TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_msg_recv (&msg, a, ZMQ_DONTWAIT)); // After a reconnect of B, the messages should still be gone TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (b, connect_address)); TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_msg_recv (&msg, a, ZMQ_DONTWAIT)); TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_msg_recv (&msg, b, ZMQ_DONTWAIT)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); test_context_socket_close_zero_linger (a); test_context_socket_close_zero_linger (b); // Wait for disconnects. msleep (SETTLE_TIME); } #define TEST_SUITE(name, bind_address) \ void test_fair_queue_in_##name () \ { \ test_fair_queue_in (bind_address); \ } \ void test_destroy_queue_on_disconnect_##name () \ { \ test_destroy_queue_on_disconnect (bind_address); \ } TEST_SUITE (inproc, "inproc://a") TEST_SUITE (tcp, "tcp://127.0.0.1:*") int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_fair_queue_in_tcp); RUN_TEST (test_fair_queue_in_inproc); // TODO commented out until libzmq implements this properly // RUN_TEST (test_destroy_queue_on_disconnect_tcp); // RUN_TEST (test_destroy_queue_on_disconnect_inproc); return UNITY_END (); }
sophomore_public/libzmq
tests/test_spec_router.cpp
C++
gpl-3.0
5,514
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> SETUP_TEARDOWN_TESTCONTEXT #define MSG_SIZE 20 #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #endif void test_srcfd () { char my_endpoint[MAX_SOCKET_STRING]; // Create the infrastructure void *rep = test_context_socket (ZMQ_REP); void *req = test_context_socket (ZMQ_REQ); bind_loopback_ipv4 (rep, my_endpoint, sizeof (my_endpoint)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (req, my_endpoint)); char tmp[MSG_SIZE]; memset (tmp, 0, MSG_SIZE); zmq_send (req, tmp, MSG_SIZE, 0); zmq_msg_t msg; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&msg)); zmq_recvmsg (rep, &msg, 0); TEST_ASSERT_EQUAL_UINT (MSG_SIZE, zmq_msg_size (&msg)); // get the messages source file descriptor int src_fd = zmq_msg_get (&msg, ZMQ_SRCFD); TEST_ASSERT_GREATER_OR_EQUAL (0, src_fd); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); // get the remote endpoint struct sockaddr_storage ss; #ifdef ZMQ_HAVE_HPUX int addrlen = sizeof ss; #else socklen_t addrlen = sizeof ss; #endif TEST_ASSERT_SUCCESS_RAW_ERRNO ( getpeername (src_fd, (struct sockaddr *) &ss, &addrlen)); char host[NI_MAXHOST]; TEST_ASSERT_SUCCESS_RAW_ERRNO (getnameinfo ((struct sockaddr *) &ss, addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST)); // assert it is localhost which connected TEST_ASSERT_EQUAL_STRING ("127.0.0.1", host); test_context_socket_close (rep); test_context_socket_close (req); // sleep a bit for the socket to be freed msleep (SETTLE_TIME); // getting name from closed socket will fail #ifdef ZMQ_HAVE_WINDOWS const int expected_errno = WSAENOTSOCK; #else const int expected_errno = EBADF; #endif TEST_ASSERT_FAILURE_RAW_ERRNO ( expected_errno, getpeername (src_fd, (struct sockaddr *) &ss, &addrlen)); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_srcfd); return UNITY_END (); }
sophomore_public/libzmq
tests/test_srcfd.cpp
C++
gpl-3.0
2,250
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> SETUP_TEARDOWN_TESTCONTEXT // ZMTP protocol greeting structure typedef uint8_t byte; typedef struct { byte signature[10]; // 0xFF 8*0x00 0x7F byte version[2]; // 0x03 0x01 for ZMTP/3.1 byte mechanism[20]; // "NULL" byte as_server; byte filler[31]; } zmtp_greeting_t; #define ZMTP_DEALER 5 // Socket type constants // This is a greeting matching what 0MQ will send us; note the // 8-byte size is set to 1 for backwards compatibility static zmtp_greeting_t greeting = { {0xFF, 0, 0, 0, 0, 0, 0, 0, 1, 0x7F}, {3, 1}, {'N', 'U', 'L', 'L'}, 0, {0}}; static void test_stream_to_dealer () { int rc; char my_endpoint[MAX_SOCKET_STRING]; // We'll be using this socket in raw mode void *stream = test_context_socket (ZMQ_STREAM); int zero = 0; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (stream, ZMQ_LINGER, &zero, sizeof (zero))); int enabled = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (stream, ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled))); bind_loopback_ipv4 (stream, my_endpoint, sizeof my_endpoint); // We'll be using this socket as the other peer void *dealer = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (dealer, ZMQ_LINGER, &zero, sizeof (zero))); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (dealer, my_endpoint)); // Send a message on the dealer socket send_string_expect_success (dealer, "Hello", 0); // Connecting sends a zero message // First frame is routing id zmq_msg_t routing_id; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&routing_id)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&routing_id, stream, 0)); TEST_ASSERT_TRUE (zmq_msg_more (&routing_id)); // Verify the existence of Peer-Address metadata char const *peer_address = zmq_msg_gets (&routing_id, "Peer-Address"); TEST_ASSERT_NOT_NULL (peer_address); TEST_ASSERT_EQUAL_STRING ("127.0.0.1", peer_address); // Second frame is zero byte buffer[255]; TEST_ASSERT_EQUAL_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (stream, buffer, 255, 0))); // Verify the existence of Peer-Address metadata peer_address = zmq_msg_gets (&routing_id, "Peer-Address"); TEST_ASSERT_NOT_NULL (peer_address); TEST_ASSERT_EQUAL_STRING ("127.0.0.1", peer_address); // Real data follows // First frame is routing id TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&routing_id, stream, 0)); TEST_ASSERT_TRUE (zmq_msg_more (&routing_id)); // Verify the existence of Peer-Address metadata peer_address = zmq_msg_gets (&routing_id, "Peer-Address"); TEST_ASSERT_NOT_NULL (peer_address); TEST_ASSERT_EQUAL_STRING ("127.0.0.1", peer_address); // Second frame is greeting signature recv_array_expect_success (stream, greeting.signature, 0); // Send our own protocol greeting TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_send (&routing_id, stream, ZMQ_SNDMORE)); TEST_ASSERT_EQUAL_INT ( sizeof (greeting), TEST_ASSERT_SUCCESS_ERRNO ( zmq_send (stream, &greeting, sizeof (greeting), 0))); // Now we expect the data from the DEALER socket // We want the rest of greeting along with the Ready command int bytes_read = 0; while (bytes_read < 97) { // First frame is the routing id of the connection (each time) TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&routing_id, stream, 0))); TEST_ASSERT_TRUE (zmq_msg_more (&routing_id)); // Second frame contains the next chunk of data TEST_ASSERT_SUCCESS_ERRNO ( rc = zmq_recv (stream, buffer + bytes_read, 255 - bytes_read, 0)); bytes_read += rc; } // First two bytes are major and minor version numbers. TEST_ASSERT_EQUAL_INT (3, buffer[0]); // ZMTP/3.1 TEST_ASSERT_EQUAL_INT (1, buffer[1]); // Mechanism is "NULL" TEST_ASSERT_EQUAL_INT8_ARRAY (buffer + 2, "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20); TEST_ASSERT_EQUAL_INT8_ARRAY (buffer + 54, "\4\51\5READY", 8); TEST_ASSERT_EQUAL_INT8_ARRAY (buffer + 62, "\13Socket-Type\0\0\0\6DEALER", 22); TEST_ASSERT_EQUAL_INT8_ARRAY (buffer + 84, "\10Identity\0\0\0\0", 13); // Announce we are ready memcpy (buffer, "\4\51\5READY", 8); memcpy (buffer + 8, "\13Socket-Type\0\0\0\6ROUTER", 22); memcpy (buffer + 30, "\10Identity\0\0\0\0", 13); // Send Ready command TEST_ASSERT_GREATER_THAN_INT (0, TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_send ( &routing_id, stream, ZMQ_SNDMORE))); TEST_ASSERT_EQUAL_INT ( 43, TEST_ASSERT_SUCCESS_ERRNO (zmq_send (stream, buffer, 43, 0))); // Now we expect the data from the DEALER socket // First frame is, again, the routing id of the connection TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&routing_id, stream, 0))); TEST_ASSERT_TRUE (zmq_msg_more (&routing_id)); // Third frame contains Hello message from DEALER TEST_ASSERT_EQUAL_INT (7, TEST_ASSERT_SUCCESS_ERRNO ( zmq_recv (stream, buffer, sizeof buffer, 0))); // Then we have a 5-byte message "Hello" TEST_ASSERT_EQUAL_INT (0, buffer[0]); // Flags = 0 TEST_ASSERT_EQUAL_INT (5, buffer[1]); // Size = 5 TEST_ASSERT_EQUAL_INT8_ARRAY (buffer + 2, "Hello", 5); // Send "World" back to DEALER TEST_ASSERT_GREATER_THAN_INT (0, TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_send ( &routing_id, stream, ZMQ_SNDMORE))); byte world[] = {0, 5, 'W', 'o', 'r', 'l', 'd'}; TEST_ASSERT_EQUAL_INT ( sizeof (world), TEST_ASSERT_SUCCESS_ERRNO (zmq_send (stream, world, sizeof (world), 0))); // Expect response on DEALER socket recv_string_expect_success (dealer, "World", 0); // Test large messages over STREAM socket #define size 64000 uint8_t msgout[size]; memset (msgout, 0xAB, size); zmq_send (dealer, msgout, size, 0); uint8_t msgin[9 + size]; memset (msgin, 0, 9 + size); bytes_read = 0; while (bytes_read < 9 + size) { // Get routing id frame TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (stream, buffer, 256, 0))); // Get next chunk TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (rc = zmq_recv (stream, msgin + bytes_read, 9 + size - bytes_read, 0))); bytes_read += rc; } for (int byte_nbr = 0; byte_nbr < size; byte_nbr++) { TEST_ASSERT_EQUAL_UINT8 (0xAB, msgin[9 + byte_nbr]); } test_context_socket_close (dealer); test_context_socket_close (stream); } static void test_stream_to_stream () { char my_endpoint[MAX_SOCKET_STRING]; // Set-up our context and sockets void *server = test_context_socket (ZMQ_STREAM); int enabled = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server, ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled))); bind_loopback_ipv4 (server, my_endpoint, sizeof my_endpoint); void *client = test_context_socket (ZMQ_STREAM); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (client, ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled))); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (client, my_endpoint)); uint8_t id[256]; uint8_t buffer[256]; // Connecting sends a zero message // Server: First frame is routing id, second frame is zero TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (server, id, 256, 0))); TEST_ASSERT_EQUAL_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (server, buffer, 256, 0))); // Client: First frame is routing id, second frame is zero TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (client, id, 256, 0))); TEST_ASSERT_EQUAL_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (client, buffer, 256, 0))); // Sent HTTP request on client socket // Get server routing id size_t id_size = sizeof id; TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (client, ZMQ_ROUTING_ID, id, &id_size)); // First frame is server routing id TEST_ASSERT_EQUAL_INT ((int) id_size, TEST_ASSERT_SUCCESS_ERRNO (zmq_send ( client, id, id_size, ZMQ_SNDMORE))); // Second frame is HTTP GET request TEST_ASSERT_EQUAL_INT ( 7, TEST_ASSERT_SUCCESS_ERRNO (zmq_send (client, "GET /\n\n", 7, 0))); // Get HTTP request; ID frame and then request TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (server, id, 256, 0))); TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (server, buffer, 256, 0)); TEST_ASSERT_EQUAL_INT8_ARRAY (buffer, "GET /\n\n", 7); // Send reply back to client char http_response[] = "HTTP/1.0 200 OK\r\n" "Content-Type: text/plain\r\n" "\r\n" "Hello, World!"; TEST_ASSERT_SUCCESS_ERRNO (zmq_send (server, id, id_size, ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_send (server, http_response, sizeof (http_response), ZMQ_SNDMORE)); // Send zero to close connection to client TEST_ASSERT_SUCCESS_ERRNO (zmq_send (server, id, id_size, ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO (zmq_send (server, NULL, 0, ZMQ_SNDMORE)); // Get reply at client and check that it's complete TEST_ASSERT_GREATER_THAN_INT ( 0, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (client, id, 256, 0))); TEST_ASSERT_EQUAL_INT ( sizeof http_response, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (client, buffer, 256, 0))); TEST_ASSERT_EQUAL_INT8_ARRAY (buffer, http_response, sizeof (http_response)); // // Get disconnection notification // FIXME: why does this block? Bug in STREAM disconnect notification? // id_size = zmq_recv (client, id, 256, 0); // assert (id_size > 0); // rc = zmq_recv (client, buffer, 256, 0); // assert (rc == 0); test_context_socket_close (server); test_context_socket_close (client); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_stream_to_dealer); RUN_TEST (test_stream_to_stream); return UNITY_END (); }
sophomore_public/libzmq
tests/test_stream.cpp
C++
gpl-3.0
10,578
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> SETUP_TEARDOWN_TESTCONTEXT static const int SERVER = 0; static const int CLIENT = 1; struct test_message_t { int turn; const char *text; }; // NOTE: messages are sent without null terminator. const test_message_t dialog[] = { {CLIENT, "i can haz cheez burger?"}, {SERVER, "y u no disonnect?"}, {CLIENT, ""}, }; const int steps = sizeof (dialog) / sizeof (dialog[0]); bool has_more (void *socket_) { int more = 0; size_t more_size = sizeof (more); int rc = zmq_getsockopt (socket_, ZMQ_RCVMORE, &more, &more_size); if (rc != 0) return false; return more != 0; } void test_stream_disconnect () { size_t len = MAX_SOCKET_STRING; char bind_endpoint[MAX_SOCKET_STRING]; char connect_endpoint[MAX_SOCKET_STRING]; void *sockets[2]; sockets[SERVER] = test_context_socket (ZMQ_STREAM); int enabled = 1; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( sockets[SERVER], ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled))); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sockets[SERVER], "tcp://0.0.0.0:*")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sockets[SERVER], ZMQ_LAST_ENDPOINT, bind_endpoint, &len)); // Apparently Windows can't connect to 0.0.0.0. A better fix would be welcome. #ifdef ZMQ_HAVE_WINDOWS snprintf (connect_endpoint, MAX_SOCKET_STRING * sizeof (char), "tcp://127.0.0.1:%s", strrchr (bind_endpoint, ':') + 1); #else strcpy (connect_endpoint, bind_endpoint); #endif sockets[CLIENT] = test_context_socket (ZMQ_STREAM); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( sockets[CLIENT], ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled))); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sockets[CLIENT], connect_endpoint)); // wait for connect notification // Server: Grab the 1st frame (peer routing id). zmq_msg_t peer_frame; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&peer_frame, sockets[SERVER], 0)); TEST_ASSERT_GREATER_THAN_INT (0, zmq_msg_size (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&peer_frame)); TEST_ASSERT_TRUE (has_more (sockets[SERVER])); // Server: Grab the 2nd frame (actual payload). zmq_msg_t data_frame; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&data_frame, sockets[SERVER], 0)); TEST_ASSERT_EQUAL_INT (0, zmq_msg_size (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&data_frame)); // Client: Grab the 1st frame (peer routing id). TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&peer_frame, sockets[CLIENT], 0)); TEST_ASSERT_GREATER_THAN_INT (0, zmq_msg_size (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&peer_frame)); TEST_ASSERT_TRUE (has_more (sockets[CLIENT])); // Client: Grab the 2nd frame (actual payload). TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&data_frame, sockets[CLIENT], 0)); TEST_ASSERT_EQUAL_INT (0, zmq_msg_size (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&data_frame)); // Send initial message. char blob_data[256]; size_t blob_size = sizeof (blob_data); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sockets[CLIENT], ZMQ_ROUTING_ID, blob_data, &blob_size)); TEST_ASSERT_GREATER_THAN (0, blob_size); zmq_msg_t msg; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init_size (&msg, blob_size)); memcpy (zmq_msg_data (&msg), blob_data, blob_size); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_send (&msg, sockets[dialog[0].turn], ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_init_size (&msg, strlen (dialog[0].text))); memcpy (zmq_msg_data (&msg), dialog[0].text, strlen (dialog[0].text)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_send (&msg, sockets[dialog[0].turn], ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); // TODO: make sure this loop doesn't loop forever if something is wrong // with the test (or the implementation). int step = 0; while (step < steps) { // Wait until something happens. zmq_pollitem_t items[] = { {sockets[SERVER], 0, ZMQ_POLLIN, 0}, {sockets[CLIENT], 0, ZMQ_POLLIN, 0}, }; TEST_ASSERT_SUCCESS_ERRNO (zmq_poll (items, 2, 100)); // Check for data received by the server. if (items[SERVER].revents & ZMQ_POLLIN) { TEST_ASSERT_EQUAL_INT (CLIENT, dialog[step].turn); // Grab the 1st frame (peer routing id). zmq_msg_t peer_frame; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_recv (&peer_frame, sockets[SERVER], 0)); TEST_ASSERT_GREATER_THAN_INT (0, zmq_msg_size (&peer_frame)); TEST_ASSERT_TRUE (has_more (sockets[SERVER])); // Grab the 2nd frame (actual payload). zmq_msg_t data_frame; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_recv (&data_frame, sockets[SERVER], 0)); // Make sure payload matches what we expect. const char *const data = static_cast<const char *> (zmq_msg_data (&data_frame)); const size_t size = zmq_msg_size (&data_frame); // 0-length frame is a disconnection notification. The server // should receive it as the last step in the dialogue. if (size == 0) { ++step; TEST_ASSERT_EQUAL_INT (steps, step); } else { TEST_ASSERT_EQUAL_INT (strlen (dialog[step].text), size); TEST_ASSERT_EQUAL_STRING_LEN (dialog[step].text, data, size); ++step; TEST_ASSERT_LESS_THAN_INT (steps, step); // Prepare the response. TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_init_size (&data_frame, strlen (dialog[step].text))); memcpy (zmq_msg_data (&data_frame), dialog[step].text, zmq_msg_size (&data_frame)); // Send the response. TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_send (&peer_frame, sockets[SERVER], ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_send (&data_frame, sockets[SERVER], ZMQ_SNDMORE)); } // Release resources. TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&data_frame)); } // Check for data received by the client. if (items[CLIENT].revents & ZMQ_POLLIN) { TEST_ASSERT_EQUAL_INT (SERVER, dialog[step].turn); // Grab the 1st frame (peer routing id). zmq_msg_t peer_frame; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_recv (&peer_frame, sockets[CLIENT], 0)); TEST_ASSERT_GREATER_THAN_INT (0, zmq_msg_size (&peer_frame)); TEST_ASSERT_TRUE (has_more (sockets[CLIENT])); // Grab the 2nd frame (actual payload). zmq_msg_t data_frame; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_recv (&data_frame, sockets[CLIENT], 0)); TEST_ASSERT_GREATER_THAN_INT (0, zmq_msg_size (&data_frame)); // Make sure payload matches what we expect. const char *const data = static_cast<const char *> (zmq_msg_data (&data_frame)); const size_t size = zmq_msg_size (&data_frame); TEST_ASSERT_EQUAL_INT (strlen (dialog[step].text), size); TEST_ASSERT_EQUAL_STRING_LEN (dialog[step].text, data, size); ++step; // Prepare the response (next line in the dialog). TEST_ASSERT_LESS_THAN_INT (steps, step); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&data_frame)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_init_size (&data_frame, strlen (dialog[step].text))); memcpy (zmq_msg_data (&data_frame), dialog[step].text, zmq_msg_size (&data_frame)); // Send the response. TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_send (&peer_frame, sockets[CLIENT], ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_send (&data_frame, sockets[CLIENT], ZMQ_SNDMORE)); // Release resources. TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&peer_frame)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&data_frame)); } } TEST_ASSERT_EQUAL_INT (steps, step); test_context_socket_close (sockets[CLIENT]); test_context_socket_close (sockets[SERVER]); } int main (int, char **) { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_stream_disconnect); return UNITY_END (); }
sophomore_public/libzmq
tests/test_stream_disconnect.cpp
C++
gpl-3.0
9,419
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test_stream_empty () { char my_endpoint[MAX_SOCKET_STRING]; void *stream = test_context_socket (ZMQ_STREAM); void *dealer = test_context_socket (ZMQ_DEALER); bind_loopback_ipv4 (stream, my_endpoint, sizeof my_endpoint); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (dealer, my_endpoint)); send_string_expect_success (dealer, "", 0); zmq_msg_t ident, empty; zmq_msg_init (&ident); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&ident, stream, 0)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_msg_init_data (&empty, (void *) "", 0, NULL, NULL)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_send (&ident, stream, ZMQ_SNDMORE)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&ident)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_send (&empty, stream, 0)); // This close used to fail with Bad Address TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&empty)); test_context_socket_close_zero_linger (dealer); test_context_socket_close_zero_linger (stream); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_stream_empty); return UNITY_END (); }
sophomore_public/libzmq
tests/test_stream_empty.cpp
C++
gpl-3.0
1,239
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> SETUP_TEARDOWN_TESTCONTEXT void test_stream_exceeds_buffer () { const int msgsize = 8193; char sndbuf[msgsize] = "\xde\xad\xbe\xef"; unsigned char rcvbuf[msgsize]; char my_endpoint[MAX_SOCKET_STRING]; int server_sock = bind_socket_resolve_port ("127.0.0.1", "0", my_endpoint); void *zsock = test_context_socket (ZMQ_STREAM); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (zsock, my_endpoint)); int client_sock = TEST_ASSERT_SUCCESS_RAW_ERRNO (accept (server_sock, NULL, NULL)); TEST_ASSERT_SUCCESS_RAW_ERRNO (close (server_sock)); TEST_ASSERT_EQUAL_INT (msgsize, send (client_sock, sndbuf, msgsize, 0)); zmq_msg_t msg; zmq_msg_init (&msg); int rcvbytes = 0; while (rcvbytes == 0) // skip connection notification, if any { TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, zsock, 0)); // peerid TEST_ASSERT_TRUE (zmq_msg_more (&msg)); rcvbytes = TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, zsock, 0)); TEST_ASSERT_FALSE (zmq_msg_more (&msg)); } // for this test, we only collect the first chunk // since the corruption already occurs in the first chunk memcpy (rcvbuf, zmq_msg_data (&msg), zmq_msg_size (&msg)); zmq_msg_close (&msg); test_context_socket_close (zsock); close (client_sock); TEST_ASSERT_GREATER_OR_EQUAL (4, rcvbytes); // notice that only the 1st byte gets corrupted TEST_ASSERT_EQUAL_UINT (0xef, rcvbuf[3]); TEST_ASSERT_EQUAL_UINT (0xbe, rcvbuf[2]); TEST_ASSERT_EQUAL_UINT (0xad, rcvbuf[1]); TEST_ASSERT_EQUAL_UINT (0xde, rcvbuf[0]); } int main () { UNITY_BEGIN (); RUN_TEST (test_stream_exceeds_buffer); return UNITY_END (); }
sophomore_public/libzmq
tests/test_stream_exceeds_buffer.cpp
C++
gpl-3.0
1,827
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_monitoring.hpp" #include "testutil_unity.hpp" #include <stdlib.h> #include <string.h> SETUP_TEARDOWN_TESTCONTEXT static void test_stream_handshake_timeout_accept () { char my_endpoint[MAX_SOCKET_STRING]; // We use this socket in raw mode, to make a connection and send nothing void *stream = test_context_socket (ZMQ_STREAM); int zero = 0; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (stream, ZMQ_LINGER, &zero, sizeof (zero))); // We'll be using this socket to test TCP stream handshake timeout void *dealer = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (dealer, ZMQ_LINGER, &zero, sizeof (zero))); int val, tenth = 100; size_t vsize = sizeof (val); // check for the expected default handshake timeout value - 30 sec TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize)); TEST_ASSERT_EQUAL (sizeof (val), vsize); TEST_ASSERT_EQUAL_INT (30000, val); // make handshake timeout faster - 1/10 sec TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (dealer, ZMQ_HANDSHAKE_IVL, &tenth, sizeof (tenth))); vsize = sizeof (val); // make sure zmq_setsockopt changed the value TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize)); TEST_ASSERT_EQUAL (sizeof (val), vsize); TEST_ASSERT_EQUAL_INT (tenth, val); // Create and connect a socket for collecting monitor events on dealer void *dealer_mon = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_socket_monitor ( dealer, "inproc://monitor-dealer", ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED | ZMQ_EVENT_ACCEPTED)); // Connect to the inproc endpoint so we'll get events TEST_ASSERT_SUCCESS_ERRNO ( zmq_connect (dealer_mon, "inproc://monitor-dealer")); // bind dealer socket to accept connection from non-sending stream socket bind_loopback_ipv4 (dealer, my_endpoint, sizeof my_endpoint); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (stream, my_endpoint)); // we should get ZMQ_EVENT_ACCEPTED and then ZMQ_EVENT_DISCONNECTED int event = get_monitor_event (dealer_mon, NULL, NULL); TEST_ASSERT_EQUAL_INT (ZMQ_EVENT_ACCEPTED, event); event = get_monitor_event (dealer_mon, NULL, NULL); TEST_ASSERT_EQUAL_INT (ZMQ_EVENT_DISCONNECTED, event); test_context_socket_close (dealer); test_context_socket_close (dealer_mon); test_context_socket_close (stream); } static void test_stream_handshake_timeout_connect () { char my_endpoint[MAX_SOCKET_STRING]; // We use this socket in raw mode, to accept a connection and send nothing void *stream = test_context_socket (ZMQ_STREAM); int zero = 0; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (stream, ZMQ_LINGER, &zero, sizeof (zero))); bind_loopback_ipv4 (stream, my_endpoint, sizeof my_endpoint); // We'll be using this socket to test TCP stream handshake timeout void *dealer = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (dealer, ZMQ_LINGER, &zero, sizeof (zero))); int val, tenth = 100; size_t vsize = sizeof (val); // check for the expected default handshake timeout value - 30 sec TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize)); TEST_ASSERT_EQUAL (sizeof (val), vsize); TEST_ASSERT_EQUAL_INT (30000, val); // make handshake timeout faster - 1/10 sec TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (dealer, ZMQ_HANDSHAKE_IVL, &tenth, sizeof (tenth))); vsize = sizeof (val); // make sure zmq_setsockopt changed the value TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize)); TEST_ASSERT_EQUAL (sizeof (val), vsize); TEST_ASSERT_EQUAL_INT (tenth, val); // Create and connect a socket for collecting monitor events on dealer void *dealer_mon = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_socket_monitor ( dealer, "inproc://monitor-dealer", ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED | ZMQ_EVENT_ACCEPTED)); // Connect to the inproc endpoint so we'll get events TEST_ASSERT_SUCCESS_ERRNO ( zmq_connect (dealer_mon, "inproc://monitor-dealer")); // connect dealer socket to non-sending stream socket TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (dealer, my_endpoint)); // we should get ZMQ_EVENT_CONNECTED and then ZMQ_EVENT_DISCONNECTED int event = get_monitor_event (dealer_mon, NULL, NULL); TEST_ASSERT_EQUAL_INT (ZMQ_EVENT_CONNECTED, event); event = get_monitor_event (dealer_mon, NULL, NULL); TEST_ASSERT_EQUAL_INT (ZMQ_EVENT_DISCONNECTED, event); test_context_socket_close (dealer); test_context_socket_close (dealer_mon); test_context_socket_close (stream); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_stream_handshake_timeout_accept); RUN_TEST (test_stream_handshake_timeout_connect); return UNITY_END (); }
sophomore_public/libzmq
tests/test_stream_timeout.cpp
C++
gpl-3.0
5,166
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test () { char endpoint1[MAX_SOCKET_STRING]; char endpoint2[MAX_SOCKET_STRING]; // First, create an intermediate device void *xpub = test_context_socket (ZMQ_XPUB); bind_loopback_ipv4 (xpub, endpoint1, sizeof (endpoint1)); void *xsub = test_context_socket (ZMQ_XSUB); bind_loopback_ipv4 (xsub, endpoint2, sizeof (endpoint2)); // Create a publisher void *pub = test_context_socket (ZMQ_PUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pub, endpoint2)); // Create a subscriber void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, endpoint1)); // Subscribe for all messages. TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, "", 0)); // Pass the subscription upstream through the device char buff[32]; int size; TEST_ASSERT_SUCCESS_ERRNO (size = zmq_recv (xpub, buff, sizeof (buff), 0)); TEST_ASSERT_SUCCESS_ERRNO (zmq_send (xsub, buff, size, 0)); // Wait a bit till the subscription gets to the publisher msleep (SETTLE_TIME); // Send an empty message send_string_expect_success (pub, "", 0); // Pass the message downstream through the device TEST_ASSERT_SUCCESS_ERRNO (size = zmq_recv (xsub, buff, sizeof (buff), 0)); TEST_ASSERT_SUCCESS_ERRNO (zmq_send (xpub, buff, size, 0)); // Receive the message in the subscriber recv_string_expect_success (sub, "", 0); // Clean up. test_context_socket_close (xpub); test_context_socket_close (xsub); test_context_socket_close (pub); test_context_socket_close (sub); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test); return UNITY_END (); }
sophomore_public/libzmq
tests/test_sub_forward.cpp
C++
gpl-3.0
1,853
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test () { // First, create an intermediate device. void *xpub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (xpub, "tipc://{5560,0,0}")); void *xsub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (xsub, "tipc://{5561,0,0}")); // Create a publisher. void *pub = test_context_socket (ZMQ_PUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pub, "tipc://{5561,0}@0.0.0")); // Create a subscriber. void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "tipc://{5560,0}@0.0.0")); // TODO the remainder of this method is duplicated with test_sub_forward // Subscribe for all messages. TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, "", 0)); // Pass the subscription upstream through the device char buff[32]; int size; TEST_ASSERT_SUCCESS_ERRNO (size = zmq_recv (xpub, buff, sizeof (buff), 0)); TEST_ASSERT_SUCCESS_ERRNO (zmq_send (xsub, buff, size, 0)); // Wait a bit till the subscription gets to the publisher msleep (SETTLE_TIME); // Send an empty message send_string_expect_success (pub, "", 0); // Pass the message downstream through the device TEST_ASSERT_SUCCESS_ERRNO (size = zmq_recv (xsub, buff, sizeof (buff), 0)); TEST_ASSERT_SUCCESS_ERRNO (zmq_send (xpub, buff, size, 0)); // Receive the message in the subscriber recv_string_expect_success (sub, "", 0); // Clean up. test_context_socket_close (xpub); test_context_socket_close (xsub); test_context_socket_close (pub); test_context_socket_close (sub); } int main () { if (!is_tipc_available ()) { printf ("TIPC environment unavailable, skipping test\n"); return 77; } UNITY_BEGIN (); RUN_TEST (test); return UNITY_END (); }
sophomore_public/libzmq
tests/test_sub_forward_tipc.cpp
C++
gpl-3.0
1,991
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #if defined(ZMQ_HAVE_WINDOWS) #include <winsock2.h> #include <stdexcept> #else #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #endif SETUP_TEARDOWN_TESTCONTEXT // Solaris has a default of 256 max files per process #ifdef ZMQ_HAVE_SOLARIS #define MAX_SOCKETS 200 #else #define MAX_SOCKETS 1000 #endif #if defined(ZMQ_HAVE_WINDOWS) void initialise_network (void) { WSADATA info; if (WSAStartup (MAKEWORD (2, 0), &info) != 0) throw std::runtime_error ("Could not start WSA"); } #else void initialise_network (void) { } #endif void test_localhost () { // Check that we have local networking via ZeroMQ void *dealer = test_context_socket (ZMQ_DEALER); if (zmq_bind (dealer, "tcp://127.0.0.1:*") == -1) { TEST_FAIL_MESSAGE ( "E: Cannot find 127.0.0.1 -- your system does not have local\n" "E: networking. Please fix this before running libzmq checks.\n"); } test_context_socket_close (dealer); } void test_max_sockets () { // Check that we can create 1,000 sockets fd_t handle[MAX_SOCKETS]; int count; for (count = 0; count < MAX_SOCKETS; count++) { handle[count] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (handle[count] == retired_fd) { printf ("W: Only able to create %d sockets on this box\n", count); const char msg[] = "I: Tune your system to increase maximum allowed file handles\n" #if !defined(ZMQ_HAVE_WINDOWS) "I: Run 'ulimit -n 1200' in bash\n" #endif ; TEST_FAIL_MESSAGE (msg); } } // Release the socket handles for (count = 0; count < MAX_SOCKETS; count++) { close (handle[count]); } } // This test case stresses the system to shake out known configuration // problems. We're direct system calls when necessary. Some code may // need wrapping to be properly portable. int main (void) { initialise_network (); UNITY_BEGIN (); RUN_TEST (test_localhost); RUN_TEST (test_max_sockets); return UNITY_END (); }
sophomore_public/libzmq
tests/test_system.cpp
C++
gpl-3.0
2,180
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <cstring> SETUP_TEARDOWN_TESTCONTEXT void test_reconnect_ivl_against_pair_socket (const char *my_endpoint_, void *sb_) { void *sc = test_context_socket (ZMQ_PAIR); int interval = -1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sc, ZMQ_RECONNECT_IVL, &interval, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, my_endpoint_)); bounce (sb_, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb_, my_endpoint_)); expect_bounce_fail (sb_, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb_, my_endpoint_)); expect_bounce_fail (sb_, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, my_endpoint_)); bounce (sb_, sc); test_context_socket_close (sc); } void test_reconnect_ivl_tcp (bind_function_t bind_function_) { char my_endpoint[MAX_SOCKET_STRING]; void *sb = test_context_socket (ZMQ_PAIR); bind_function_ (sb, my_endpoint, sizeof my_endpoint); test_reconnect_ivl_against_pair_socket (my_endpoint, sb); test_context_socket_close (sb); } void test_bad_filter_string (const char *const filter_) { void *socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_setsockopt (socket, ZMQ_TCP_ACCEPT_FILTER, filter_, strlen (filter_))); test_context_socket_close (socket); } #define TEST_BAD_FILTER_STRING(case, filter) \ void test_bad_filter_string_##case (){test_bad_filter_string (filter);} TEST_BAD_FILTER_STRING (foo, "foo") TEST_BAD_FILTER_STRING (zeros_foo, "0.0.0.0foo") TEST_BAD_FILTER_STRING (zeros_foo_mask, "0.0.0.0/foo") TEST_BAD_FILTER_STRING (zeros_empty_mask, "0.0.0.0/") TEST_BAD_FILTER_STRING (zeros_negative_mask, "0.0.0.0/-1") TEST_BAD_FILTER_STRING (zeros_too_large_mask, "0.0.0.0/33") void test_clear () { void *bind_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (bind_socket, ZMQ_TCP_ACCEPT_FILTER, NULL, 0)); #if 0 // XXX Shouldn't this work as well? const char empty_filter[] = ""; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( socket, ZMQ_TCP_ACCEPT_FILTER, empty_filter, strlen (empty_filter))); #endif char endpoint[MAX_SOCKET_STRING]; bind_loopback_ipv4 (bind_socket, endpoint, sizeof (endpoint)); void *connect_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (connect_socket, endpoint)); bounce (bind_socket, connect_socket); test_context_socket_close (connect_socket); test_context_socket_close (bind_socket); } const char non_matching_filter[] = "127.0.0.255/32"; void test_set_non_matching_and_clear () { void *bind_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (bind_socket, ZMQ_TCP_ACCEPT_FILTER, non_matching_filter, strlen (non_matching_filter))); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (bind_socket, ZMQ_TCP_ACCEPT_FILTER, NULL, 0)); char endpoint[MAX_SOCKET_STRING]; bind_loopback_ipv4 (bind_socket, endpoint, sizeof (endpoint)); void *connect_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (connect_socket, endpoint)); bounce (bind_socket, connect_socket); test_context_socket_close (connect_socket); test_context_socket_close (bind_socket); } void test_set_matching (const char *const filter_) { void *bind_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( bind_socket, ZMQ_TCP_ACCEPT_FILTER, filter_, strlen (filter_))); char endpoint[MAX_SOCKET_STRING]; bind_loopback_ipv4 (bind_socket, endpoint, sizeof (endpoint)); void *connect_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (connect_socket, endpoint)); bounce (bind_socket, connect_socket); test_context_socket_close (connect_socket); test_context_socket_close (bind_socket); } void test_set_matching_1 () { test_set_matching ("127.0.0.1/32"); } void test_set_matching_2 () { test_set_matching ("0.0.0.0/0"); } void test_set_non_matching () { void *bind_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (bind_socket, ZMQ_TCP_ACCEPT_FILTER, non_matching_filter, strlen (non_matching_filter))); char endpoint[MAX_SOCKET_STRING]; bind_loopback_ipv4 (bind_socket, endpoint, sizeof (endpoint)); void *connect_socket = test_context_socket (ZMQ_PAIR); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (connect_socket, endpoint)); expect_bounce_fail (bind_socket, connect_socket); test_context_socket_close_zero_linger (connect_socket); test_context_socket_close_zero_linger (bind_socket); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_bad_filter_string_foo); RUN_TEST (test_bad_filter_string_zeros_foo); RUN_TEST (test_bad_filter_string_zeros_foo_mask); RUN_TEST (test_bad_filter_string_zeros_empty_mask); RUN_TEST (test_bad_filter_string_zeros_negative_mask); RUN_TEST (test_bad_filter_string_zeros_too_large_mask); RUN_TEST (test_clear); RUN_TEST (test_set_non_matching_and_clear); RUN_TEST (test_set_matching_1); RUN_TEST (test_set_matching_2); RUN_TEST (test_set_non_matching); return UNITY_END (); }
sophomore_public/libzmq
tests/test_tcp_accept_filter.cpp
C++
gpl-3.0
5,579
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT /* Use the worst case filename size for the buffer (+1 for trailing NUL), this * is larger than MAX_SOCKET_STRING, which is not large enough for IPC */ #define BUF_SIZE (FILENAME_MAX + 1) const char *ep_wc_tcp = "tcp://127.0.0.1:*"; #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS const char *ep_wc_ipc = "ipc://*"; #endif #if defined ZMQ_HAVE_VMCI const char *ep_wc_vmci = "vmci://*:*"; #endif void test_send_after_unbind_fails () { char my_endpoint[BUF_SIZE]; // Create infrastructure. void *push = test_context_socket (ZMQ_PUSH); bind_loopback_ipv4 (push, my_endpoint, BUF_SIZE); void *pull = test_context_socket (ZMQ_PULL); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pull, my_endpoint)); // Pass one message through to ensure the connection is established send_string_expect_success (push, "ABC", 0); recv_string_expect_success (pull, "ABC", 0); // Unbind the listening endpoint TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (push, my_endpoint)); // Allow unbind to settle msleep (SETTLE_TIME); // Check that sending would block (there's no outbound connection) TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_send (push, "ABC", 3, ZMQ_DONTWAIT)); // Clean up test_context_socket_close (pull); test_context_socket_close (push); } void test_send_after_disconnect_fails () { // Create infrastructure void *pull = test_context_socket (ZMQ_PULL); char my_endpoint[BUF_SIZE]; bind_loopback_ipv4 (pull, my_endpoint, BUF_SIZE); void *push = test_context_socket (ZMQ_PUSH); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (push, my_endpoint)); // Pass one message through to ensure the connection is established. send_string_expect_success (push, "ABC", 0); recv_string_expect_success (pull, "ABC", 0); // Disconnect the bound endpoint TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (push, my_endpoint)); // Allow disconnect to settle msleep (SETTLE_TIME); // Check that sending would block (there's no inbound connections). TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_send (push, "ABC", 3, ZMQ_DONTWAIT)); // Clean up test_context_socket_close (pull); test_context_socket_close (push); } void test_unbind_via_last_endpoint () { // Create infrastructure (wild-card binding) void *push = test_context_socket (ZMQ_PUSH); char my_endpoint[BUF_SIZE]; bind_loopback_ipv4 (push, my_endpoint, BUF_SIZE); void *pull = test_context_socket (ZMQ_PULL); #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pull, ep_wc_ipc)); #endif #if defined ZMQ_HAVE_VMCI void *req = test_context_socket (ZMQ_REQ); int rc = zmq_bind (req, ep_wc_vmci); if (rc < 0 && errno == EAFNOSUPPORT) TEST_IGNORE_MESSAGE ("VMCI not supported"); TEST_ASSERT_SUCCESS_ERRNO (rc); #endif // Unbind sockets binded by wild-card address TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (push, my_endpoint)); size_t buf_size = 0; (void) buf_size; #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS buf_size = sizeof (my_endpoint); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (pull, ZMQ_LAST_ENDPOINT, my_endpoint, &buf_size)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (pull, my_endpoint)); #endif #if defined ZMQ_HAVE_VMCI buf_size = sizeof (my_endpoint); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (req, ZMQ_LAST_ENDPOINT, my_endpoint, &buf_size)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (req, my_endpoint)); #endif // Clean up test_context_socket_close (pull); test_context_socket_close (push); } void test_wildcard_unbind_fails () { // Create infrastructure (wild-card binding) void *push = test_context_socket (ZMQ_PUSH); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (push, ep_wc_tcp)); void *pull = test_context_socket (ZMQ_PULL); #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pull, ep_wc_ipc)); #endif #if defined ZMQ_HAVE_VMCI void *req = test_context_socket (ZMQ_REQ); int rc = zmq_bind (req, ep_wc_vmci); if (rc < 0 && errno == EAFNOSUPPORT) TEST_IGNORE_MESSAGE ("VMCI not supported"); TEST_ASSERT_SUCCESS_ERRNO (rc); #endif // Sockets binded by wild-card address can't be unbinded by wild-card address TEST_ASSERT_FAILURE_ERRNO (ENOENT, zmq_unbind (push, ep_wc_tcp)); #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS TEST_ASSERT_FAILURE_ERRNO (ENOENT, zmq_unbind (pull, ep_wc_ipc)); #endif #if defined ZMQ_HAVE_VMCI TEST_ASSERT_FAILURE_ERRNO (ENOENT, zmq_unbind (req, ep_wc_vmci)); #endif // Clean up test_context_socket_close (pull); test_context_socket_close (push); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_send_after_unbind_fails); RUN_TEST (test_send_after_disconnect_fails); RUN_TEST (test_unbind_via_last_endpoint); RUN_TEST (test_wildcard_unbind_fails); return UNITY_END (); }
sophomore_public/libzmq
tests/test_term_endpoint.cpp
C++
gpl-3.0
5,161
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT const char ep[] = "tipc://{5560,0,0}"; const char name[] = "tipc://{5560,0}@0.0.0"; void test_term_endpoint_unbind_tipc () { if (!is_tipc_available ()) { TEST_IGNORE_MESSAGE ("TIPC environment unavailable, skipping test\n"); } // Create infrastructure. void *push = test_context_socket (ZMQ_PUSH); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (push, ep)); void *pull = test_context_socket (ZMQ_PULL); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pull, name)); // Pass one message through to ensure the connection is established. send_string_expect_success (push, "ABC", 0); recv_string_expect_success (pull, "ABC", 0); // Unbind the lisnening endpoint TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (push, ep)); // Let events some time msleep (SETTLE_TIME); // Check that sending would block (there's no outbound connection). TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_send (push, "ABC", 3, ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pull); test_context_socket_close (push); } void test_term_endpoint_disconnect_tipc () { if (!is_tipc_available ()) { TEST_IGNORE_MESSAGE ("TIPC environment unavailable, skipping test\n"); } // Create infrastructure. void *push = test_context_socket (ZMQ_PUSH); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (push, name)); void *pull = test_context_socket (ZMQ_PULL); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pull, ep)); // Pass one message through to ensure the connection is established. send_string_expect_success (push, "ABC", 0); recv_string_expect_success (pull, "ABC", 0); // Disconnect the bound endpoint TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (push, name)); msleep (SETTLE_TIME); // Check that sending would block (there's no inbound connections). TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_send (push, "ABC", 3, ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pull); test_context_socket_close (push); } int main (void) { UNITY_BEGIN (); RUN_TEST (test_term_endpoint_unbind_tipc); RUN_TEST (test_term_endpoint_disconnect_tipc); return UNITY_END (); }
sophomore_public/libzmq
tests/test_term_endpoint_tipc.cpp
C++
gpl-3.0
2,301
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT // Client threads loop on send/recv until told to exit void client_thread (void *client_) { for (int count = 0; count < 15000; count++) { send_string_expect_success (client_, "0", 0); } send_string_expect_success (client_, "1", 0); } void test_thread_safe () { char my_endpoint[MAX_SOCKET_STRING]; void *server = test_context_socket (ZMQ_SERVER); bind_loopback_ipv4 (server, my_endpoint, sizeof my_endpoint); void *client = test_context_socket (ZMQ_CLIENT); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (client, my_endpoint)); void *t1 = zmq_threadstart (client_thread, client); void *t2 = zmq_threadstart (client_thread, client); char data; int threads_completed = 0; while (threads_completed < 2) { TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (server, &data, 1, 0)); if (data == '1') threads_completed++; // Thread ended } zmq_threadclose (t1); zmq_threadclose (t2); test_context_socket_close (server); test_context_socket_close (client); } void test_getsockopt_thread_safe (void *const socket_) { int thread_safe; size_t size = sizeof (int); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (socket_, ZMQ_THREAD_SAFE, &thread_safe, &size)); TEST_ASSERT_EQUAL_INT (1, thread_safe); } void test_client_getsockopt_thread_safe () { void *client = test_context_socket (ZMQ_CLIENT); test_getsockopt_thread_safe (client); test_context_socket_close (client); } void test_server_getsockopt_thread_safe () { void *server = test_context_socket (ZMQ_SERVER); test_getsockopt_thread_safe (server); test_context_socket_close (server); } int main (void) { setup_test_environment (); // TODO this file could be merged with test_client_server UNITY_BEGIN (); RUN_TEST (test_client_getsockopt_thread_safe); RUN_TEST (test_server_getsockopt_thread_safe); RUN_TEST (test_thread_safe); return UNITY_END (); }
sophomore_public/libzmq
tests/test_thread_safe.cpp
C++
gpl-3.0
2,091
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test_timeo () { void *frontend = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (frontend, "inproc://timeout_test")); // Receive on disconnected socket returns immediately char buffer[32]; TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (frontend, buffer, 32, ZMQ_DONTWAIT)); // Check whether receive timeout is honored const int timeout = 250; const int jitter = 50; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (frontend, ZMQ_RCVTIMEO, &timeout, sizeof (int))); void *stopwatch = zmq_stopwatch_start (); TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (frontend, buffer, 32, 0)); unsigned int elapsed = zmq_stopwatch_stop (stopwatch) / 1000; TEST_ASSERT_GREATER_THAN_INT (timeout - jitter, elapsed); if (elapsed >= timeout + jitter) { // we cannot assert this on a non-RT system fprintf (stderr, "zmq_recv took quite long, with a timeout of %i ms, it took " "actually %i ms\n", timeout, elapsed); } // Check that normal message flow works as expected void *backend = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (backend, "inproc://timeout_test")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (backend, ZMQ_SNDTIMEO, &timeout, sizeof (int))); send_string_expect_success (backend, "Hello", 0); recv_string_expect_success (frontend, "Hello", 0); // Clean-up test_context_socket_close (backend); test_context_socket_close (frontend); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_timeo); return UNITY_END (); }
sophomore_public/libzmq
tests/test_timeo.cpp
C++
gpl-3.0
1,841
/* SPDX-License-Identifier: MPL-2.0 */ #define __STDC_LIMIT_MACROS // to define SIZE_MAX with older compilers #include "testutil.hpp" #include "testutil_unity.hpp" void setUp () { } void tearDown () { } void handler (int timer_id_, void *arg_) { (void) timer_id_; // Stop 'unused' compiler warnings *(static_cast<bool *> (arg_)) = true; } int sleep_and_execute (void *timers_) { int timeout = zmq_timers_timeout (timers_); // Sleep methods are inaccurate, so we sleep in a loop until time arrived while (timeout > 0) { msleep (timeout); timeout = zmq_timers_timeout (timers_); } return zmq_timers_execute (timers_); } void test_null_timer_pointers () { void *timers = NULL; TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_destroy (&timers)); // TODO this currently triggers an access violation #if 0 TEST_ASSERT_FAILURE_ERRNO(EFAULT, zmq_timers_destroy (NULL)); #endif const size_t dummy_interval = 100; const int dummy_timer_id = 1; TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_add (timers, dummy_interval, &handler, NULL)); TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_add (&timers, dummy_interval, &handler, NULL)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_cancel (timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_cancel (&timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_set_interval (timers, dummy_timer_id, dummy_interval)); TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_set_interval (&timers, dummy_timer_id, dummy_interval)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_reset (timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_reset (&timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_timeout (timers)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_timeout (&timers)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_execute (timers)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_execute (&timers)); } void test_corner_cases () { void *timers = zmq_timers_new (); TEST_ASSERT_NOT_NULL (timers); const size_t dummy_interval = SIZE_MAX; const int dummy_timer_id = 1; // attempt to cancel non-existent timer TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_cancel (timers, dummy_timer_id)); // attempt to set interval of non-existent timer TEST_ASSERT_FAILURE_ERRNO ( EINVAL, zmq_timers_set_interval (timers, dummy_timer_id, dummy_interval)); // attempt to reset non-existent timer TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_reset (timers, dummy_timer_id)); // attempt to add NULL handler TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_add (timers, dummy_interval, NULL, NULL)); const int timer_id = TEST_ASSERT_SUCCESS_ERRNO ( zmq_timers_add (timers, dummy_interval, handler, NULL)); // attempt to cancel timer twice // TODO should this case really be an error? canceling twice could be allowed TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_cancel (timers, timer_id)); TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_cancel (timers, timer_id)); // timeout without any timers active TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_timeout (timers)); // cleanup TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_destroy (&timers)); } void test_timers () { void *timers = zmq_timers_new (); TEST_ASSERT_NOT_NULL (timers); bool timer_invoked = false; const unsigned long full_timeout = 100; void *const stopwatch = zmq_stopwatch_start (); const int timer_id = TEST_ASSERT_SUCCESS_ERRNO ( zmq_timers_add (timers, full_timeout, handler, &timer_invoked)); // Timer should not have been invoked yet TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_intermediate (stopwatch) < full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Wait half the time and check again long timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers)); msleep (timeout / 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_intermediate (stopwatch) < full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Wait until the end TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers)); TEST_ASSERT_TRUE (timer_invoked); timer_invoked = false; // Wait half the time and check again timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers)); msleep (timeout / 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_intermediate (stopwatch) < 2 * full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Reset timer and wait half of the time left TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_reset (timers, timer_id)); msleep (timeout / 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_stop (stopwatch) < 2 * full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Wait until the end TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers)); TEST_ASSERT_TRUE (timer_invoked); timer_invoked = false; // reschedule TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_set_interval (timers, timer_id, 50)); TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers)); TEST_ASSERT_TRUE (timer_invoked); timer_invoked = false; // cancel timer timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers)); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_cancel (timers, timer_id)); msleep (timeout * 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); TEST_ASSERT_FALSE (timer_invoked); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_destroy (&timers)); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_timers); RUN_TEST (test_null_timer_pointers); RUN_TEST (test_corner_cases); return UNITY_END (); }
sophomore_public/libzmq
tests/test_timers.cpp
C++
gpl-3.0
6,194
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> SETUP_TEARDOWN_TESTCONTEXT void test_address_wildcard_ipv4 () { /* Address wildcard, IPv6 disabled */ void *sb = test_context_socket (ZMQ_REP); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://*:*")); char bind_endpoint[256]; char connect_endpoint[256]; size_t endpoint_len = sizeof (bind_endpoint); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, bind_endpoint, &endpoint_len)); // Apparently Windows can't connect to 0.0.0.0. A better fix would be welcome. #ifdef ZMQ_HAVE_WINDOWS snprintf (connect_endpoint, 256 * sizeof (char), "tcp://127.0.0.1:%s", strrchr (bind_endpoint, ':') + 1); #else strcpy (connect_endpoint, bind_endpoint); #endif TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_endpoint)); bounce (sb, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (sc, connect_endpoint)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb, bind_endpoint)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_address_wildcard_ipv6 () { int ipv6 = is_ipv6_available (); /* Address wildcard, IPv6 enabled */ void *sb = test_context_socket (ZMQ_REP); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sb, ZMQ_IPV6, &ipv6, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sc, ZMQ_IPV6, &ipv6, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://*:*")); char bind_endpoint[256]; char connect_endpoint[256]; size_t endpoint_len = sizeof (bind_endpoint); memset (bind_endpoint, 0, endpoint_len); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, bind_endpoint, &endpoint_len)); #ifdef ZMQ_HAVE_WINDOWS if (ipv6) snprintf (connect_endpoint, 256 * sizeof (char), "tcp://[::1]:%s", strrchr (bind_endpoint, ':') + 1); else snprintf (connect_endpoint, 256 * sizeof (char), "tcp://127.0.0.1:%s", strrchr (bind_endpoint, ':') + 1); #else strcpy (connect_endpoint, bind_endpoint); #endif TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_endpoint)); bounce (sb, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (sc, connect_endpoint)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb, bind_endpoint)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_port_wildcard_ipv4_address () { /* Port wildcard, IPv4 address, IPv6 disabled */ void *sb = test_context_socket (ZMQ_REP); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://127.0.0.1:*")); char endpoint[256]; size_t endpoint_len = sizeof (endpoint); memset (endpoint, 0, endpoint_len); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &endpoint_len)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, endpoint)); bounce (sb, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (sc, endpoint)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb, endpoint)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_port_wildcard_ipv4_address_ipv6 () { /* Port wildcard, IPv4 address, IPv6 enabled */ void *sb = test_context_socket (ZMQ_REP); void *sc = test_context_socket (ZMQ_REQ); const int ipv6 = is_ipv6_available (); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sb, ZMQ_IPV6, &ipv6, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sc, ZMQ_IPV6, &ipv6, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://127.0.0.1:*")); char endpoint[256]; size_t endpoint_len = sizeof (endpoint); memset (endpoint, 0, endpoint_len); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &endpoint_len)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, endpoint)); bounce (sb, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (sc, endpoint)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb, endpoint)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_port_wildcard_ipv6_address () { const int ipv6 = is_ipv6_available (); if (!ipv6) TEST_IGNORE_MESSAGE ("ipv6 is not available"); /* Port wildcard, IPv6 address, IPv6 enabled */ void *sb = test_context_socket (ZMQ_REP); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sb, ZMQ_IPV6, &ipv6, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sc, ZMQ_IPV6, &ipv6, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://[::1]:*")); char endpoint[256]; size_t endpoint_len = sizeof (endpoint); memset (endpoint, 0, endpoint_len); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &endpoint_len)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, endpoint)); bounce (sb, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (sc, endpoint)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb, endpoint)); test_context_socket_close (sc); test_context_socket_close (sb); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_address_wildcard_ipv4); RUN_TEST (test_address_wildcard_ipv6); RUN_TEST (test_port_wildcard_ipv4_address); RUN_TEST (test_port_wildcard_ipv4_address_ipv6); RUN_TEST (test_port_wildcard_ipv6_address); return UNITY_END (); }
sophomore_public/libzmq
tests/test_unbind_wildcard.cpp
C++
gpl-3.0
5,686
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <stdlib.h> #include <string.h> #include <unistd.h> SETUP_TEARDOWN_TESTCONTEXT #if !defined(ZMQ_HAVE_WINDOWS) void pre_allocate_sock_tcp (void *socket_, char *my_endpoint_) { fd_t s = bind_socket_resolve_port ("127.0.0.1", "0", my_endpoint_); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (socket_, ZMQ_USE_FD, &s, sizeof (s))); } typedef void (*pre_allocate_sock_fun_t) (void *, char *); void setup_socket_pair (pre_allocate_sock_fun_t pre_allocate_sock_fun_, int bind_socket_type_, int connect_socket_type_, void **out_sb_, void **out_sc_) { *out_sb_ = test_context_socket (bind_socket_type_); char my_endpoint[MAX_SOCKET_STRING]; pre_allocate_sock_fun_ (*out_sb_, my_endpoint); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (*out_sb_, my_endpoint)); *out_sc_ = test_context_socket (connect_socket_type_); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (*out_sc_, my_endpoint)); } void test_socket_pair (pre_allocate_sock_fun_t pre_allocate_sock_fun_, int bind_socket_type_, int connect_socket_type_) { void *sb, *sc; setup_socket_pair (pre_allocate_sock_fun_, bind_socket_type_, connect_socket_type_, &sb, &sc); bounce (sb, sc); test_context_socket_close (sc); test_context_socket_close (sb); } void test_req_rep (pre_allocate_sock_fun_t pre_allocate_sock_fun_) { test_socket_pair (pre_allocate_sock_fun_, ZMQ_REP, ZMQ_REQ); } void test_pair (pre_allocate_sock_fun_t pre_allocate_sock_fun_) { test_socket_pair (pre_allocate_sock_fun_, ZMQ_PAIR, ZMQ_PAIR); } void test_client_server (pre_allocate_sock_fun_t pre_allocate_sock_fun_) { #if defined(ZMQ_SERVER) && defined(ZMQ_CLIENT) void *sb, *sc; setup_socket_pair (pre_allocate_sock_fun_, ZMQ_SERVER, ZMQ_CLIENT, &sb, &sc); zmq_msg_t msg; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init_size (&msg, 1)); char *data = static_cast<char *> (zmq_msg_data (&msg)); data[0] = 1; int rc = zmq_msg_send (&msg, sc, ZMQ_SNDMORE); // TODO which error code is expected? TEST_ASSERT_EQUAL_INT (-1, rc); rc = zmq_msg_send (&msg, sc, 0); TEST_ASSERT_EQUAL_INT (1, rc); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&msg)); rc = zmq_msg_recv (&msg, sb, 0); TEST_ASSERT_EQUAL_INT (1, rc); uint32_t routing_id = zmq_msg_routing_id (&msg); TEST_ASSERT_NOT_EQUAL (0, routing_id); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init_size (&msg, 1)); data = static_cast<char *> (zmq_msg_data (&msg)); data[0] = 2; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_set_routing_id (&msg, routing_id)); rc = zmq_msg_send (&msg, sb, ZMQ_SNDMORE); // TODO which error code is expected? TEST_ASSERT_EQUAL_INT (-1, rc); rc = zmq_msg_send (&msg, sb, 0); TEST_ASSERT_EQUAL_INT (1, rc); rc = zmq_msg_recv (&msg, sc, 0); TEST_ASSERT_EQUAL_INT (1, rc); routing_id = zmq_msg_routing_id (&msg); TEST_ASSERT_EQUAL_INT (0, routing_id); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); test_context_socket_close (sc); test_context_socket_close (sb); #endif } void test_req_rep_tcp () { test_req_rep (pre_allocate_sock_tcp); } void test_pair_tcp () { test_pair (pre_allocate_sock_tcp); } void test_client_server_tcp () { #if defined(ZMQ_SERVER) && defined(ZMQ_CLIENT) test_client_server (pre_allocate_sock_tcp); #endif } char ipc_endpoint[MAX_SOCKET_STRING] = ""; void pre_allocate_sock_ipc (void *sb_, char *my_endpoint_) { fd_t s = bind_socket_resolve_port ("", "", my_endpoint_, AF_UNIX, 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sb_, ZMQ_USE_FD, &s, sizeof (s))); strcpy (ipc_endpoint, strchr (my_endpoint_, '/') + 2); } void test_req_rep_ipc () { test_req_rep (pre_allocate_sock_ipc); TEST_ASSERT_SUCCESS_ERRNO (unlink (ipc_endpoint)); } void test_pair_ipc () { test_pair (pre_allocate_sock_ipc); TEST_ASSERT_SUCCESS_ERRNO (unlink (ipc_endpoint)); } void test_client_server_ipc () { #if defined(ZMQ_SERVER) && defined(ZMQ_CLIENT) test_client_server (pre_allocate_sock_ipc); TEST_ASSERT_SUCCESS_ERRNO (unlink (ipc_endpoint)); #endif } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_req_rep_tcp); RUN_TEST (test_pair_tcp); RUN_TEST (test_client_server_tcp); RUN_TEST (test_req_rep_ipc); RUN_TEST (test_pair_ipc); RUN_TEST (test_client_server_ipc); return UNITY_END (); } #else int main () { return 0; } #endif
sophomore_public/libzmq
tests/test_use_fd.cpp
C++
gpl-3.0
4,775
/* SPDX-License-Identifier: MPL-2.0 */ #include <string.h> #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test_roundtrip () { char bind_address[MAX_SOCKET_STRING]; char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_REP); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://*:*/roundtrip")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, bind_address, &addr_length)); // Windows can't connect to 0.0.0.0 snprintf (connect_address, MAX_SOCKET_STRING * sizeof (char), "ws://127.0.0.1%s", strrchr (bind_address, ':')); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); bounce (sb, sc); TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (sc, connect_address)); TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (sb, bind_address)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_roundtrip_without_path () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://127.0.0.1:*")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); bounce (sb, sc); test_context_socket_close (sc); test_context_socket_close (sb); } void test_heartbeat () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://127.0.0.1:*/heartbeat")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *sc = test_context_socket (ZMQ_REQ); // Setting heartbeat settings int ivl = 10; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sc, ZMQ_HEARTBEAT_IVL, &ivl, sizeof (ivl))); // Disable reconnect, to make sure the ping-pong actually work ivl = -1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sc, ZMQ_RECONNECT_IVL, &ivl, sizeof (ivl))); // Connect to server TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); // Make sure some ping and pong going through msleep (100); bounce (sb, sc); test_context_socket_close (sc); test_context_socket_close (sb); } void test_short_message () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://127.0.0.1:*/short")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); zmq_msg_t msg; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init_size (&msg, 255)); for (unsigned char i = 0; i < 255; ++i) ((unsigned char *) zmq_msg_data (&msg))[i] = i; int rc = zmq_msg_send (&msg, sc, 0); TEST_ASSERT_EQUAL_INT (255, rc); rc = zmq_msg_recv (&msg, sb, 0); TEST_ASSERT_EQUAL_INT (255, rc); for (unsigned char i = 0; i < 255; ++i) TEST_ASSERT_EQUAL_INT (i, ((unsigned char *) zmq_msg_data (&msg))[i]); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_large_message () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://127.0.0.1:*/large")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *sc = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); zmq_msg_t msg; TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init_size (&msg, 65536)); for (int i = 0; i < 65536; ++i) ((unsigned char *) zmq_msg_data (&msg))[i] = i % 255; int rc = zmq_msg_send (&msg, sc, 0); TEST_ASSERT_EQUAL_INT (65536, rc); rc = zmq_msg_recv (&msg, sb, 0); TEST_ASSERT_EQUAL_INT (65536, rc); for (int i = 0; i < 65536; ++i) TEST_ASSERT_EQUAL_INT (i % 255, ((unsigned char *) zmq_msg_data (&msg))[i]); TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg)); test_context_socket_close (sc); test_context_socket_close (sb); } void test_curve () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); char client_public[41]; char client_secret[41]; char server_public[41]; char server_secret[41]; TEST_ASSERT_SUCCESS_ERRNO ( zmq_curve_keypair (server_public, server_secret)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_curve_keypair (client_public, client_secret)); void *server = test_context_socket (ZMQ_REP); int as_server = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server, ZMQ_CURVE_SERVER, &as_server, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server, ZMQ_CURVE_SECRETKEY, server_secret, 41)); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (server, "ws://127.0.0.1:*/roundtrip")); TEST_ASSERT_SUCCESS_ERRNO (zmq_getsockopt (server, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *client = test_context_socket (ZMQ_REQ); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (client, ZMQ_CURVE_SERVERKEY, server_public, 41)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (client, ZMQ_CURVE_PUBLICKEY, client_public, 41)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (client, ZMQ_CURVE_SECRETKEY, client_secret, 41)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (client, connect_address)); bounce (server, client); test_context_socket_close (client); test_context_socket_close (server); } void test_mask_shared_msg () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://127.0.0.1:*/mask-shared")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *sc = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); zmq_msg_t msg; zmq_msg_init_size ( &msg, 255); // Message have to be long enough so it won't fit inside msg unsigned char *data = (unsigned char *) zmq_msg_data (&msg); for (int i = 0; i < 255; i++) data[i] = i; // Taking a copy to make the msg shared zmq_msg_t copy; zmq_msg_init (&copy); zmq_msg_copy (&copy, &msg); // Sending the shared msg int rc = zmq_msg_send (&msg, sc, 0); TEST_ASSERT_EQUAL_INT (255, rc); // Recv the msg and check that it was masked correctly rc = zmq_msg_recv (&msg, sb, 0); TEST_ASSERT_EQUAL_INT (255, rc); data = (unsigned char *) zmq_msg_data (&msg); for (int i = 0; i < 255; i++) TEST_ASSERT_EQUAL_INT (i, data[i]); // Testing that copy was not masked data = (unsigned char *) zmq_msg_data (&copy); for (int i = 0; i < 255; i++) TEST_ASSERT_EQUAL_INT (i, data[i]); // Constant msg cannot be masked as well, as it is constant rc = zmq_send_const (sc, "HELLO", 5, 0); TEST_ASSERT_EQUAL_INT (5, rc); recv_string_expect_success (sb, "HELLO", 0); zmq_msg_close (&copy); zmq_msg_close (&msg); test_context_socket_close (sc); test_context_socket_close (sb); } void test_pub_sub () { char connect_address[MAX_SOCKET_STRING]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "ws://127.0.0.1:*")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); void *sc = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sc, ZMQ_SUBSCRIBE, "A", 1)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sc, ZMQ_SUBSCRIBE, "B", 1)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); recv_string_expect_success (sb, "\1A", 0); recv_string_expect_success (sb, "\1B", 0); send_string_expect_success (sb, "A", 0); send_string_expect_success (sb, "B", 0); recv_string_expect_success (sc, "A", 0); recv_string_expect_success (sc, "B", 0); test_context_socket_close (sc); test_context_socket_close (sb); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_roundtrip_without_path); RUN_TEST (test_roundtrip); RUN_TEST (test_short_message); RUN_TEST (test_large_message); RUN_TEST (test_heartbeat); RUN_TEST (test_mask_shared_msg); RUN_TEST (test_pub_sub); if (zmq_has ("curve")) RUN_TEST (test_curve); return UNITY_END (); }
sophomore_public/libzmq
tests/test_ws_transport.cpp
C++
gpl-3.0
9,320
/* SPDX-License-Identifier: MPL-2.0 */ #include <string.h> #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT #ifdef ZMQ_WSS_CERT_PEM const char *key = "-----BEGIN PRIVATE KEY-----\n" "MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDnzizmqK1e0iRR\n" "lY75z9q3TWVBzFYX00Rl18GT2liW6AYzOB/qa55EhjTf4snhC2FaUoosu4MYRdvo\n" "8qBOpFvnQDScJ6o06LyrWyL15kkBYEsTkjmDEXe/TxUVE2IBb991m1F91SIEjK5m\n" "NRH2aRjrN5mL9f8+Crrv96Y4sxGCDkqwOarViFbDYFxdYa7WrvZImpknrmM5KPyg\n" "PtU9gqnlIgAU9bPTGUJGdQeQ+AWKOgw6unV8IiKEX8jyHBoKiAqTspRCCV9yDOKx\n" "eVUGgkcAMpeSv8HVboNbfof8DI+eT8EtYNsWW4dINgiYYEGZIhy74X2dKria6hCc\n" "AYdS+/90nf0RAyymniDtgTGrMIXFmjlYpLngqfAo+zzl21dGh3VnRUFbTak8CH4g\n" "wYIefJFerwJP1im5jAiULWHaiOOk2r5fHdxbBLebqcaWBRSGGNE9cj4bj/qYuHAf\n" "VrNW5+CN3j0h5ss/f8lOoDbbrb6GtSJfI16fuQZd2hW84u38EuVd1/mzbVMv7Bip\n" "yzjbEAcOgn0Mk89zZewooz8Sxr2e1R47/5CCHJodUFqc5hmcnOqRd7YmpM68bS7V\n" "KbnOY3w9Llw6tkXMitmtUs7IiKZ1ViXA3UzMSumvEJKMqOnfNEUH9pkqYe2lVbay\n" "1HSk/hz7AkprVPMlqlF12x/794fg9wIDAQABAoICAHI10UWsYg9P9nkD+Tf4Q0kB\n" "JxyuMtT2UMLk9QmGERP5KeTeiEsVzxrwDOkqclEhLEw2UsILeWHiOaGiuX1F2cos\n" "hj9SA7ih2yOKecUyO1IkQZlY+GEtoBRwQHDr5ePTXQQzDIm1E1eugNb22uzPh2mN\n" "MWgWQjYtT0GggRN6luu/YulE4Hjo/eaxeZDA6kX4WnwXP9KfR2AIY8AIdUQjNtYg\n" "VG3/SSR/U3onexzgNsqOIyxkZjJNFzilgPpZAjOiJ6Px3r5So+Yrlx3eLBhS4+yj\n" "AK9bL4ObOblAtHtpLPHRVdqn2ApB+nuHs+BvvKJYflPLm/pt7BrXrGtRDX3Dj27T\n" "sXPZTBsPmFr8vqlbgIYNCiY3uQonsAO95o0Y0Dx6oVFlzL1ajP49KmUye+p/wEHc\n" "1XfYD8DxfU+ECEZk1/DvmKIPc4cZr2U1i9RBVRiKFd4NFIGYylLihuYhB9FZEyWQ\n" "p0TwM3DFs7PwIQNPE6mGKtjgdgBGkY4AGfCxQzdp1mM+I2700OIx0EHAbxm5JMQm\n" "NQKtBWliiz7+DLK/NWrDVS8N8tdkZVpHUK6ahvJbYG8oDqX0me6Bmk+0SaQJujis\n" "fOPFRNGanr0X97+fqMJnDeOfXAcYurXBm81IkGilUF+2a0wWhS7PGhOT4dcLKRU8\n" "tcmIZRJDWWyv2uQGg2yhAoIBAQD5sM7SX/ZuQ44HHmjQP59//vxCoZYqcPtf+52z\n" "kCpRnbbzFh/uTLRBvQ5NjZp7XOpZ/3y05JnarYChjCuVjG5+SJO7UQ0pl5N7LL0r\n" "3YGSRkfBGE05AiccyitonQssnJ4GVGfkt+1l9kVn4aMN9YkgoWc68vFzHY9CfIjS\n" "3d7QM89vGJBmBCpLG9WC0R24VNH6mfnM0MANwFlYFk9a2cKWueNjMidtHaNgry7A\n" "lWKn7jEUizkb5kNiVoFC+9qYx16unR1U2K4eRJoOhOLNWPaPuGX219iMvQ+CHs2T\n" "ZA72qj0d29t2wS8RmFXAIRNDuc7MkPh3iTF4jdRt57/pU1WPAoIBAQDtqavyOx/h\n" "kilyGjALfca68iQscWuVmWCVzFFfeGvFN4IXSxgM38xmtSEhAILVf7ozv/QNJsxv\n" "9l1xGkY+FaoFTSxglMw0iO4fZwNp2GuEy57jFzJuJyzE4FiueNb5dzoZnGnXxJIS\n" "bnprZgR42aaYAU0PzPwrqyc3PXv2J4tn6O8Mt53JO4bN+/XomD4oQBOhM0iLuS7t\n" "xTUQnsaHr1QglSIGQf4XOmXTO0+dE5uhFXkKP0Frq4MtoJUdEiWNzOdzwzxAZJTL\n" "v8dPOQud9yxKxwRg2rroasKgyRgE6GHqKSRhggiMwVOFzeMxPLJ2oeWmpRZXiMoH\n" "dkiCnPh7DBoZAoIBAGSuUJcvrrSDdO+V6XmfTfdUn+9WLLDsYdAwK0TOauICEFUw\n" "pKt4Lm8bhnrrEFGSA8VKacSfMRKmR2nclW5188/j//3WDtKolgVi4tyfMrICuMg5\n" "vlmwbokDVEGYoXrZpDa1Ljdhms40YYQjzZXBXgvUSUXR1F4wmyWaBanRYRje61PG\n" "ueMI5uzmSk+3dp5vRUQhdkKKIgbpep00Ucc2a2pPhkrnXFJ5UvmXaeip0+AXAZ9h\n" "DCQd0yoB65lQ6LIWIi2SmNMvk/YMf3o/Rxy6NKF7H1JLcrw9N9WmCgrWm9oGhyJV\n" "Fsdp2krj/B++tn/mmmaORkIdBd+wgOnYOuAghC0CggEBAK6KtLgyieh9Eqk06GIY\n" "HlJ/sOde6Pc2bIO3SW/HHcb6TDVVNjWGSzSHA+yb1np70sFc0RyziOMVWWzOMhY4\n" "jORV2CiaPxq6Eb/IRO6APf6KGIeJKsVRSgTRCvAf2SnfUTEr+WO4ftrAfnHPu6sR\n" "ldL+6ZyYG/7qNOPR6O9P/YbzwFRjqaL3b7ppuCD5ZnTjEkeKRVYwS3HeKmmpYf6W\n" "Wj+PpyxXXQesIMowPfkLRHnaLknDSQWNMcrZq4ltIV1xxe3zzZUxCUJV90eMiqaZ\n" "t9K3NNT47tnwRj4VUemQzRBO5OQjvqm49eFH4vnvLNYJcoKfrbfdwxoV2YzrQWYE\n" "7kkCggEBAKzLviuI6eoaPwgKeR2wrFBbrucnY4yqkVIFzFRpjM6azzMArYVpslZW\n" "DTdmi/2QCd9altVAT20Yvml8YqrFszpINV1DqBIfHtQPEy9oKrhFW92rhuJQo/aX\n" "1yILvzmyzLdpQG6zLm7TD7mEkumiT9F3ObeoVnAOllEwUrNAfDPPclRHGowJs6Ya\n" "wv50Idk62v7gnXny9OyFN3kUq6dtwItYqmalfKKGXhTi49mEWX39SSZSt+a15oKM\n" "21fKHdqiG/AXST7n8IlBGRzyW9TqTnmVC5zj7esmqfRT0eno399hl0LOZgJoa4dx\n" "lMwbKi/uEdrUT3ei3nAxnuQolXgClZk=\n" "-----END PRIVATE KEY-----"; const char *cert = "-----BEGIN CERTIFICATE-----\n" "MIIFkTCCA3mgAwIBAgIUWazS3jRxgV/9TgdybZ9ch7nYsQIwDQYJKoZIhvcNAQEL\n" "BQAwVzELMAkGA1UEBhMCWFgxFTATBgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoGA1UE\n" "CgwTRGVmYXVsdCBDb21wYW55IEx0ZDETMBEGA1UEAwwKemVyb21xLm9yZzAgFw0x\n" "OTExMTAwODMzMThaGA8yMTE5MTAxNzA4MzMxOFowVzELMAkGA1UEBhMCWFgxFTAT\n" "BgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoGA1UECgwTRGVmYXVsdCBDb21wYW55IEx0\n" "ZDETMBEGA1UEAwwKemVyb21xLm9yZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\n" "AgoCggIBAOfOLOaorV7SJFGVjvnP2rdNZUHMVhfTRGXXwZPaWJboBjM4H+prnkSG\n" "NN/iyeELYVpSiiy7gxhF2+jyoE6kW+dANJwnqjTovKtbIvXmSQFgSxOSOYMRd79P\n" "FRUTYgFv33WbUX3VIgSMrmY1EfZpGOs3mYv1/z4Kuu/3pjizEYIOSrA5qtWIVsNg\n" "XF1hrtau9kiamSeuYzko/KA+1T2CqeUiABT1s9MZQkZ1B5D4BYo6DDq6dXwiIoRf\n" "yPIcGgqICpOylEIJX3IM4rF5VQaCRwAyl5K/wdVug1t+h/wMj55PwS1g2xZbh0g2\n" "CJhgQZkiHLvhfZ0quJrqEJwBh1L7/3Sd/REDLKaeIO2BMaswhcWaOVikueCp8Cj7\n" "POXbV0aHdWdFQVtNqTwIfiDBgh58kV6vAk/WKbmMCJQtYdqI46Tavl8d3FsEt5up\n" "xpYFFIYY0T1yPhuP+pi4cB9Ws1bn4I3ePSHmyz9/yU6gNtutvoa1Il8jXp+5Bl3a\n" "Fbzi7fwS5V3X+bNtUy/sGKnLONsQBw6CfQyTz3Nl7CijPxLGvZ7VHjv/kIIcmh1Q\n" "WpzmGZyc6pF3tiakzrxtLtUpuc5jfD0uXDq2RcyK2a1SzsiIpnVWJcDdTMxK6a8Q\n" "koyo6d80RQf2mSph7aVVtrLUdKT+HPsCSmtU8yWqUXXbH/v3h+D3AgMBAAGjUzBR\n" "MB0GA1UdDgQWBBTVHR+4lBIBcr2rEEMdideTAkwDZDAfBgNVHSMEGDAWgBTVHR+4\n" "lBIBcr2rEEMdideTAkwDZDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA\n" "A4ICAQB9M5p9z92UhVXg2baUj9QBN2YFGAeveFRpZ9Y/wktEssTqMKkc+39UtfJS\n" "UclZnzMEhLyTieNqf+8GCgLLI0YSTIJpWwzvQBcXPoo+8IcexANvxR22KZrE51y4\n" "/YfCKh8Q0ZbG8oc5Br8YHwipzGcmWjWtznfMpuaELezv/r381QV1Sbmpw2a0jvwp\n" "uA/bc+4IZ9yvrhC9KkOUnivnCV71U2Wy8zOvrBEJicuGOc+lbWJRKyjbMDi1IybG\n" "VnemtkQEyXFh6f1h8AdaN+Xj7qXX/YKmNk20Siu4qDNo8nozVpOL2DHjoKLa4N2c\n" "ULG3kXScxVxWqCuPVNeypV2TZ9uSVFeKK/VJ5iGvFeifDsqVVo6WC4Pdz0WYes8H\n" "3VqEPSwmNJ1FswLpYpGgCEFnkGRPFFB5dmwr0fuubkgaJPatxrImFac+nukfqZ8N\n" "x/d4t72u1yIs0HnrkAj96ZIUXH5jFGPXbD8eGO0hzw+wbY9KRLXGBBl2B4EAaBdt\n" "Cmp8R8xus3FGDZ5RVftZvTQO2CiTC4yn9Wab/ADDwcXDs6ntHctx4xQpm0tLqMoz\n" "BTH8+ftqyzklar35gJluD84oh1kynEojrPkUvb75NlzxikBSF3pRrOx30Myy7DBx\n" "rhUIqDFxqlYFx9InEzHlvI7cWWdMNqAmSxpz4SXMrd/7PJG+Ag==\n" "-----END CERTIFICATE-----"; void test_roundtrip () { char connect_address[MAX_SOCKET_STRING + sizeof ("/roundtrip") - 1]; size_t addr_length = sizeof (connect_address); void *sb = test_context_socket (ZMQ_REP); zmq_setsockopt (sb, ZMQ_WSS_CERT_PEM, cert, strlen (cert)); zmq_setsockopt (sb, ZMQ_WSS_KEY_PEM, key, strlen (key)); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "wss://*:*/roundtrip")); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, connect_address, &addr_length)); strcat (connect_address, "/roundtrip"); void *sc = test_context_socket (ZMQ_REQ); zmq_setsockopt (sc, ZMQ_WSS_TRUST_PEM, cert, strlen (cert)); zmq_setsockopt (sc, ZMQ_WSS_HOSTNAME, "zeromq.org", strlen ("zeromq.org")); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, connect_address)); bounce (sb, sc); test_context_socket_close (sc); test_context_socket_close (sb); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_roundtrip); return UNITY_END (); } #else int main () { printf ("WSS unavailable, skipping test\n"); return 77; } #endif
sophomore_public/libzmq
tests/test_wss_transport.cpp
C++
gpl-3.0
7,090
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test_basic () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); int manual = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_MANUAL, &manual, 4)); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Subscribe for A const char subscription[] = {1, 'A', 0}; send_string_expect_success (sub, subscription, 0); // Receive subscriptions from subscriber recv_string_expect_success (pub, subscription, 0); // Subscribe socket for B instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "B", 1)); // Sending A message and B Message send_string_expect_success (pub, "A", 0); send_string_expect_success (pub, "B", 0); recv_string_expect_success (sub, "B", ZMQ_DONTWAIT); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } void test_unsubscribe_manual () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // set pub socket options int manual = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_MANUAL, &manual, sizeof (manual))); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Subscribe for A const uint8_t subscription1[] = {1, 'A'}; send_array_expect_success (sub, subscription1, 0); // Subscribe for B const uint8_t subscription2[] = {1, 'B'}; send_array_expect_success (sub, subscription2, 0); char buffer[3]; // Receive subscription "A" from subscriber recv_array_expect_success (pub, subscription1, 0); // Subscribe socket for XA instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XA", 2)); // Receive subscription "B" from subscriber recv_array_expect_success (pub, subscription2, 0); // Subscribe socket for XB instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XB", 2)); // Unsubscribe from A const uint8_t unsubscription1[2] = {0, 'A'}; send_array_expect_success (sub, unsubscription1, 0); // Receive unsubscription "A" from subscriber recv_array_expect_success (pub, unsubscription1, 0); // Unsubscribe socket from XA instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XA", 2)); // Sending messages XA, XB send_string_expect_success (pub, "XA", 0); send_string_expect_success (pub, "XB", 0); // Subscriber should receive XB only recv_string_expect_success (sub, "XB", ZMQ_DONTWAIT); // Close subscriber test_context_socket_close (sub); // Receive unsubscription "B" const char unsubscription2[2] = {0, 'B'}; TEST_ASSERT_EQUAL_INT ( sizeof unsubscription2, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (pub, buffer, sizeof buffer, 0))); TEST_ASSERT_EQUAL_INT8_ARRAY (unsubscription2, buffer, sizeof unsubscription2); // Unsubscribe socket from XB instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XB", 2)); // Clean up. test_context_socket_close (pub); } void test_xpub_proxy_unsubscribe_on_disconnect () { const uint8_t topic_buff[] = {"1"}; const uint8_t payload_buff[] = {"X"}; char my_endpoint_backend[MAX_SOCKET_STRING]; char my_endpoint_frontend[MAX_SOCKET_STRING]; int manual = 1; // proxy frontend void *xsub_proxy = test_context_socket (ZMQ_XSUB); bind_loopback_ipv4 (xsub_proxy, my_endpoint_frontend, sizeof my_endpoint_frontend); // proxy backend void *xpub_proxy = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_XPUB_MANUAL, &manual, 4)); bind_loopback_ipv4 (xpub_proxy, my_endpoint_backend, sizeof my_endpoint_backend); // publisher void *pub = test_context_socket (ZMQ_PUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pub, my_endpoint_frontend)); // first subscriber subscribes void *sub1 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub1, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, topic_buff, 1)); // wait msleep (SETTLE_TIME); // proxy reroutes and confirms subscriptions const uint8_t subscription[2] = {1, *topic_buff}; recv_array_expect_success (xpub_proxy, subscription, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, subscription, 0); // second subscriber subscribes void *sub2 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub2, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, topic_buff, 1)); // wait msleep (SETTLE_TIME); // proxy reroutes recv_array_expect_success (xpub_proxy, subscription, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, subscription, 0); // wait msleep (SETTLE_TIME); // let publisher send a msg send_array_expect_success (pub, topic_buff, ZMQ_SNDMORE); send_array_expect_success (pub, payload_buff, 0); // wait msleep (SETTLE_TIME); // proxy reroutes data messages to subscribers recv_array_expect_success (xsub_proxy, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (xsub_proxy, payload_buff, ZMQ_DONTWAIT); send_array_expect_success (xpub_proxy, topic_buff, ZMQ_SNDMORE); send_array_expect_success (xpub_proxy, payload_buff, 0); // wait msleep (SETTLE_TIME); // each subscriber should now get a message recv_array_expect_success (sub2, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub2, payload_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub1, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub1, payload_buff, ZMQ_DONTWAIT); // Disconnect both subscribers test_context_socket_close (sub1); test_context_socket_close (sub2); // wait msleep (SETTLE_TIME); // unsubscribe messages are passed from proxy to publisher const uint8_t unsubscription[] = {0, *topic_buff}; recv_array_expect_success (xpub_proxy, unsubscription, 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_UNSUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, unsubscription, 0); // should receive another unsubscribe msg recv_array_expect_success (xpub_proxy, unsubscription, 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_UNSUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, unsubscription, 0); // wait msleep (SETTLE_TIME); // let publisher send a msg send_array_expect_success (pub, topic_buff, ZMQ_SNDMORE); send_array_expect_success (pub, payload_buff, 0); // wait msleep (SETTLE_TIME); // nothing should come to the proxy char buffer[1]; TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (xsub_proxy, buffer, sizeof buffer, ZMQ_DONTWAIT)); test_context_socket_close (pub); test_context_socket_close (xpub_proxy); test_context_socket_close (xsub_proxy); } void test_missing_subscriptions () { const char *topic1 = "1"; const char *topic2 = "2"; const char *payload = "X"; char my_endpoint_backend[MAX_SOCKET_STRING]; char my_endpoint_frontend[MAX_SOCKET_STRING]; int manual = 1; // proxy frontend void *xsub_proxy = test_context_socket (ZMQ_XSUB); bind_loopback_ipv4 (xsub_proxy, my_endpoint_frontend, sizeof my_endpoint_frontend); // proxy backend void *xpub_proxy = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_XPUB_MANUAL, &manual, 4)); bind_loopback_ipv4 (xpub_proxy, my_endpoint_backend, sizeof my_endpoint_backend); // publisher void *pub = test_context_socket (ZMQ_PUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pub, my_endpoint_frontend)); // Here's the problem: because subscribers subscribe in quick succession, // the proxy is unable to confirm the first subscription before receiving // the second. This causes the first subscription to get lost. // first subscriber void *sub1 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub1, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, topic1, 1)); // wait msleep (SETTLE_TIME); // proxy now reroutes and confirms subscriptions const uint8_t subscription1[] = {1, static_cast<uint8_t> (topic1[0])}; recv_array_expect_success (xpub_proxy, subscription1, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic1, 1)); send_array_expect_success (xsub_proxy, subscription1, 0); // second subscriber void *sub2 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub2, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, topic2, 1)); // wait msleep (SETTLE_TIME); const uint8_t subscription2[] = {1, static_cast<uint8_t> (topic2[0])}; recv_array_expect_success (xpub_proxy, subscription2, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic2, 1)); send_array_expect_success (xsub_proxy, subscription2, 0); // wait msleep (SETTLE_TIME); // let publisher send 2 msgs, each with its own topic_buff send_string_expect_success (pub, topic1, ZMQ_SNDMORE); send_string_expect_success (pub, payload, 0); send_string_expect_success (pub, topic2, ZMQ_SNDMORE); send_string_expect_success (pub, payload, 0); // wait msleep (SETTLE_TIME); // proxy reroutes data messages to subscribers recv_string_expect_success (xsub_proxy, topic1, ZMQ_DONTWAIT); recv_string_expect_success (xsub_proxy, payload, ZMQ_DONTWAIT); send_string_expect_success (xpub_proxy, topic1, ZMQ_SNDMORE); send_string_expect_success (xpub_proxy, payload, 0); recv_string_expect_success (xsub_proxy, topic2, ZMQ_DONTWAIT); recv_string_expect_success (xsub_proxy, payload, ZMQ_DONTWAIT); send_string_expect_success (xpub_proxy, topic2, ZMQ_SNDMORE); send_string_expect_success (xpub_proxy, payload, 0); // wait msleep (SETTLE_TIME); // each subscriber should now get a message recv_string_expect_success (sub2, topic2, ZMQ_DONTWAIT); recv_string_expect_success (sub2, payload, ZMQ_DONTWAIT); recv_string_expect_success (sub1, topic1, ZMQ_DONTWAIT); recv_string_expect_success (sub1, payload, ZMQ_DONTWAIT); // Clean up test_context_socket_close (sub1); test_context_socket_close (sub2); test_context_socket_close (pub); test_context_socket_close (xpub_proxy); test_context_socket_close (xsub_proxy); } void test_unsubscribe_cleanup () { char my_endpoint[MAX_SOCKET_STRING]; // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); int manual = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_MANUAL, &manual, 4)); bind_loopback_ipv4 (pub, my_endpoint, sizeof my_endpoint); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, my_endpoint)); // Subscribe for A const uint8_t subscription1[2] = {1, 'A'}; send_array_expect_success (sub, subscription1, 0); // Receive subscriptions from subscriber recv_array_expect_success (pub, subscription1, 0); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XA", 2)); // send 2 messages send_string_expect_success (pub, "XA", 0); send_string_expect_success (pub, "XB", 0); // receive the single message recv_string_expect_success (sub, "XA", 0); // should be nothing left in the queue char buffer[2]; TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (sub, buffer, sizeof buffer, ZMQ_DONTWAIT)); // close the socket test_context_socket_close (sub); // closing the socket will result in an unsubscribe event const uint8_t unsubscription[2] = {0, 'A'}; recv_array_expect_success (pub, unsubscription, 0); // this doesn't really do anything // there is no last_pipe set it will just fail silently TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XA", 2)); // reconnect sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, my_endpoint)); // send a subscription for B const uint8_t subscription2[2] = {1, 'B'}; send_array_expect_success (sub, subscription2, 0); // receive the subscription, overwrite it to XB recv_array_expect_success (pub, subscription2, 0); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XB", 2)); // send 2 messages send_string_expect_success (pub, "XA", 0); send_string_expect_success (pub, "XB", 0); // receive the single message recv_string_expect_success (sub, "XB", 0); // should be nothing left in the queue TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (sub, buffer, sizeof buffer, ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } void test_user_message () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Send some data that is neither sub nor unsub const char subscription[] = {2, 'A', 0}; send_string_expect_success (sub, subscription, 0); // Receive subscriptions from subscriber recv_string_expect_success (pub, subscription, 0); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } #ifdef ZMQ_ONLY_FIRST_SUBSCRIBE void test_user_message_multi () { const int only_first_subscribe = 1; // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_ONLY_FIRST_SUBSCRIBE, &only_first_subscribe, sizeof (only_first_subscribe))); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_ONLY_FIRST_SUBSCRIBE, &only_first_subscribe, sizeof (only_first_subscribe))); // Send some data that is neither sub nor unsub const uint8_t msg_common[] = {'A', 'B', 'C'}; // Message starts with 0 but should still treated as user const uint8_t msg_0a[] = {0, 'B', 'C'}; const uint8_t msg_0b[] = {0, 'C', 'D'}; // Message starts with 1 but should still treated as user const uint8_t msg_1a[] = {1, 'B', 'C'}; const uint8_t msg_1b[] = {1, 'C', 'D'}; // Test second message starting with 0 send_array_expect_success (sub, msg_common, ZMQ_SNDMORE); send_array_expect_success (sub, msg_0a, 0); // Receive messages from subscriber recv_array_expect_success (pub, msg_common, 0); recv_array_expect_success (pub, msg_0a, 0); // Test second message starting with 1 send_array_expect_success (sub, msg_common, ZMQ_SNDMORE); send_array_expect_success (sub, msg_1a, 0); // Receive messages from subscriber recv_array_expect_success (pub, msg_common, 0); recv_array_expect_success (pub, msg_1a, 0); // Test first message starting with 1 send_array_expect_success (sub, msg_1a, ZMQ_SNDMORE); send_array_expect_success (sub, msg_1b, 0); recv_array_expect_success (pub, msg_1a, 0); recv_array_expect_success (pub, msg_1b, 0); send_array_expect_success (sub, msg_0a, ZMQ_SNDMORE); send_array_expect_success (sub, msg_0b, 0); recv_array_expect_success (pub, msg_0a, 0); recv_array_expect_success (pub, msg_0b, 0); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } #endif int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_basic); RUN_TEST (test_unsubscribe_manual); RUN_TEST (test_xpub_proxy_unsubscribe_on_disconnect); RUN_TEST (test_missing_subscriptions); RUN_TEST (test_unsubscribe_cleanup); RUN_TEST (test_user_message); #ifdef ZMQ_ONLY_FIRST_SUBSCRIBE RUN_TEST (test_user_message_multi); #endif return UNITY_END (); }
sophomore_public/libzmq
tests/test_xpub_manual.cpp
C++
gpl-3.0
17,445
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test_basic () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); int manual = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_MANUAL_LAST_VALUE, &manual, 4)); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Subscribe for A const char subscription[] = {1, 'A', 0}; send_string_expect_success (sub, subscription, 0); // Receive subscriptions from subscriber recv_string_expect_success (pub, subscription, 0); // Subscribe socket for B instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "B", 1)); // Sending A message and B Message send_string_expect_success (pub, "A", 0); send_string_expect_success (pub, "B", 0); recv_string_expect_success (sub, "B", ZMQ_DONTWAIT); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } void test_unsubscribe_manual () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // set pub socket options int manual = 1; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_XPUB_MANUAL_LAST_VALUE, &manual, sizeof (manual))); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Subscribe for A const uint8_t subscription1[] = {1, 'A'}; send_array_expect_success (sub, subscription1, 0); // Subscribe for B const uint8_t subscription2[] = {1, 'B'}; send_array_expect_success (sub, subscription2, 0); char buffer[3]; // Receive subscription "A" from subscriber recv_array_expect_success (pub, subscription1, 0); // Subscribe socket for XA instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XA", 2)); // Receive subscription "B" from subscriber recv_array_expect_success (pub, subscription2, 0); // Subscribe socket for XB instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XB", 2)); // Unsubscribe from A const uint8_t unsubscription1[2] = {0, 'A'}; send_array_expect_success (sub, unsubscription1, 0); // Receive unsubscription "A" from subscriber recv_array_expect_success (pub, unsubscription1, 0); // Unsubscribe socket from XA instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XA", 2)); // Sending messages XA, XB send_string_expect_success (pub, "XA", 0); send_string_expect_success (pub, "XB", 0); // Subscriber should receive XB only recv_string_expect_success (sub, "XB", ZMQ_DONTWAIT); // Close subscriber test_context_socket_close (sub); // Receive unsubscription "B" const char unsubscription2[2] = {0, 'B'}; TEST_ASSERT_EQUAL_INT ( sizeof unsubscription2, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (pub, buffer, sizeof buffer, 0))); TEST_ASSERT_EQUAL_INT8_ARRAY (unsubscription2, buffer, sizeof unsubscription2); // Unsubscribe socket from XB instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XB", 2)); // Clean up. test_context_socket_close (pub); } void test_xpub_proxy_unsubscribe_on_disconnect () { const uint8_t topic_buff[] = {"1"}; const uint8_t payload_buff[] = {"X"}; char my_endpoint_backend[MAX_SOCKET_STRING]; char my_endpoint_frontend[MAX_SOCKET_STRING]; int manual = 1; // proxy frontend void *xsub_proxy = test_context_socket (ZMQ_XSUB); bind_loopback_ipv4 (xsub_proxy, my_endpoint_frontend, sizeof my_endpoint_frontend); // proxy backend void *xpub_proxy = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_XPUB_MANUAL_LAST_VALUE, &manual, 4)); bind_loopback_ipv4 (xpub_proxy, my_endpoint_backend, sizeof my_endpoint_backend); // publisher void *pub = test_context_socket (ZMQ_PUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pub, my_endpoint_frontend)); // first subscriber subscribes void *sub1 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub1, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, topic_buff, 1)); // wait msleep (SETTLE_TIME); // proxy reroutes and confirms subscriptions const uint8_t subscription[2] = {1, *topic_buff}; recv_array_expect_success (xpub_proxy, subscription, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, subscription, 0); // second subscriber subscribes void *sub2 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub2, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, topic_buff, 1)); // wait msleep (SETTLE_TIME); // proxy reroutes recv_array_expect_success (xpub_proxy, subscription, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, subscription, 0); // wait msleep (SETTLE_TIME); // let publisher send a msg send_array_expect_success (pub, topic_buff, ZMQ_SNDMORE); send_array_expect_success (pub, payload_buff, 0); // wait msleep (SETTLE_TIME); // proxy reroutes data messages to subscribers recv_array_expect_success (xsub_proxy, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (xsub_proxy, payload_buff, ZMQ_DONTWAIT); // send 2 messages send_array_expect_success (xpub_proxy, topic_buff, ZMQ_SNDMORE); send_array_expect_success (xpub_proxy, payload_buff, 0); send_array_expect_success (xpub_proxy, topic_buff, ZMQ_SNDMORE); send_array_expect_success (xpub_proxy, payload_buff, 0); // wait msleep (SETTLE_TIME); // sub2 will get 2 messages because the last subscription is sub2. recv_array_expect_success (sub2, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub2, payload_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub2, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub2, payload_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub1, topic_buff, ZMQ_DONTWAIT); recv_array_expect_success (sub1, payload_buff, ZMQ_DONTWAIT); // Disconnect both subscribers test_context_socket_close (sub1); test_context_socket_close (sub2); // wait msleep (SETTLE_TIME); // unsubscribe messages are passed from proxy to publisher const uint8_t unsubscription[] = {0, *topic_buff}; recv_array_expect_success (xpub_proxy, unsubscription, 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_UNSUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, unsubscription, 0); // should receive another unsubscribe msg recv_array_expect_success (xpub_proxy, unsubscription, 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_UNSUBSCRIBE, topic_buff, 1)); send_array_expect_success (xsub_proxy, unsubscription, 0); // wait msleep (SETTLE_TIME); // let publisher send a msg send_array_expect_success (pub, topic_buff, ZMQ_SNDMORE); send_array_expect_success (pub, payload_buff, 0); // wait msleep (SETTLE_TIME); // nothing should come to the proxy char buffer[1]; TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (xsub_proxy, buffer, sizeof buffer, ZMQ_DONTWAIT)); test_context_socket_close (pub); test_context_socket_close (xpub_proxy); test_context_socket_close (xsub_proxy); } void test_missing_subscriptions () { const char *topic1 = "1"; const char *topic2 = "2"; const char *payload = "X"; char my_endpoint_backend[MAX_SOCKET_STRING]; char my_endpoint_frontend[MAX_SOCKET_STRING]; int manual = 1; // proxy frontend void *xsub_proxy = test_context_socket (ZMQ_XSUB); bind_loopback_ipv4 (xsub_proxy, my_endpoint_frontend, sizeof my_endpoint_frontend); // proxy backend void *xpub_proxy = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_XPUB_MANUAL_LAST_VALUE, &manual, 4)); bind_loopback_ipv4 (xpub_proxy, my_endpoint_backend, sizeof my_endpoint_backend); // publisher void *pub = test_context_socket (ZMQ_PUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (pub, my_endpoint_frontend)); // Here's the problem: because subscribers subscribe in quick succession, // the proxy is unable to confirm the first subscription before receiving // the second. This causes the first subscription to get lost. // first subscriber void *sub1 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub1, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, topic1, 1)); // wait msleep (SETTLE_TIME); // proxy now reroutes and confirms subscriptions const uint8_t subscription1[] = {1, static_cast<uint8_t> (topic1[0])}; recv_array_expect_success (xpub_proxy, subscription1, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic1, 1)); send_array_expect_success (xsub_proxy, subscription1, 0); // second subscriber void *sub2 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub2, my_endpoint_backend)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, topic2, 1)); // wait msleep (SETTLE_TIME); // proxy now reroutes and confirms subscriptions const uint8_t subscription2[] = {1, static_cast<uint8_t> (topic2[0])}; recv_array_expect_success (xpub_proxy, subscription2, ZMQ_DONTWAIT); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic2, 1)); send_array_expect_success (xsub_proxy, subscription2, 0); // wait msleep (SETTLE_TIME); // let publisher send 2 msgs, each with its own topic_buff send_string_expect_success (pub, topic1, ZMQ_SNDMORE); send_string_expect_success (pub, payload, 0); send_string_expect_success (pub, topic2, ZMQ_SNDMORE); send_string_expect_success (pub, payload, 0); // wait msleep (SETTLE_TIME); // proxy reroutes data messages to subscribers recv_string_expect_success (xsub_proxy, topic1, ZMQ_DONTWAIT); recv_string_expect_success (xsub_proxy, payload, ZMQ_DONTWAIT); send_string_expect_success (xpub_proxy, topic1, ZMQ_SNDMORE); send_string_expect_success (xpub_proxy, payload, 0); recv_string_expect_success (xsub_proxy, topic2, ZMQ_DONTWAIT); recv_string_expect_success (xsub_proxy, payload, ZMQ_DONTWAIT); send_string_expect_success (xpub_proxy, topic2, ZMQ_SNDMORE); send_string_expect_success (xpub_proxy, payload, 0); // wait msleep (SETTLE_TIME); // only sub2 should now get a message recv_string_expect_success (sub2, topic2, ZMQ_DONTWAIT); recv_string_expect_success (sub2, payload, ZMQ_DONTWAIT); //recv_string_expect_success (sub1, topic1, ZMQ_DONTWAIT); //recv_string_expect_success (sub1, payload, ZMQ_DONTWAIT); // Clean up test_context_socket_close (sub1); test_context_socket_close (sub2); test_context_socket_close (pub); test_context_socket_close (xpub_proxy); test_context_socket_close (xsub_proxy); } void test_unsubscribe_cleanup () { char my_endpoint[MAX_SOCKET_STRING]; // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); int manual = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_MANUAL_LAST_VALUE, &manual, 4)); bind_loopback_ipv4 (pub, my_endpoint, sizeof my_endpoint); // Create a subscriber void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, my_endpoint)); // Subscribe for A const uint8_t subscription1[2] = {1, 'A'}; send_array_expect_success (sub, subscription1, 0); // Receive subscriptions from subscriber recv_array_expect_success (pub, subscription1, 0); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XA", 2)); // send 2 messages send_string_expect_success (pub, "XA", 0); send_string_expect_success (pub, "XB", 0); // receive the single message recv_string_expect_success (sub, "XA", 0); // should be nothing left in the queue char buffer[2]; TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (sub, buffer, sizeof buffer, ZMQ_DONTWAIT)); // close the socket test_context_socket_close (sub); // closing the socket will result in an unsubscribe event const uint8_t unsubscription[2] = {0, 'A'}; recv_array_expect_success (pub, unsubscription, 0); // this doesn't really do anything // there is no last_pipe set it will just fail silently TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XA", 2)); // reconnect sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, my_endpoint)); // send a subscription for B const uint8_t subscription2[2] = {1, 'B'}; send_array_expect_success (sub, subscription2, 0); // receive the subscription, overwrite it to XB recv_array_expect_success (pub, subscription2, 0); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XB", 2)); // send 2 messages send_string_expect_success (pub, "XA", 0); send_string_expect_success (pub, "XB", 0); // receive the single message recv_string_expect_success (sub, "XB", 0); // should be nothing left in the queue TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (sub, buffer, sizeof buffer, ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } void test_manual_last_value () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); int hwm = 2000; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SNDHWM, &hwm, 4)); // set pub socket options int manual = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_MANUAL_LAST_VALUE, &manual, 4)); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // Create a subscriber void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Create another subscriber void *sub2 = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub2, "inproc://soname")); // Subscribe for "A". TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, "A", 1)); const uint8_t subscription[2] = {1, 'A'}; // we must wait for the subscription to be processed here, otherwise some // or all published messages might be lost recv_array_expect_success (pub, subscription, 0); // manual subscribe message TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "A", 1)); send_string_expect_success (pub, "A", 0); recv_string_expect_success (sub, "A", 0); // Subscribe for "A". TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, "A", 1)); recv_array_expect_success (pub, subscription, 0); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "A", 1)); send_string_expect_success (pub, "A", 0); recv_string_expect_success (sub2, "A", 0); char buffer[255]; // sub won't get a message because the last subscription pipe is sub2. TEST_ASSERT_FAILURE_ERRNO ( EAGAIN, zmq_recv (sub, buffer, sizeof (buffer), ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); test_context_socket_close (sub2); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_basic); RUN_TEST (test_unsubscribe_manual); RUN_TEST (test_xpub_proxy_unsubscribe_on_disconnect); RUN_TEST (test_missing_subscriptions); RUN_TEST (test_unsubscribe_cleanup); RUN_TEST (test_manual_last_value); return UNITY_END (); }
sophomore_public/libzmq
tests/test_xpub_manual_last_value.cpp
C++
gpl-3.0
16,683
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); int hwm = 2000; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SNDHWM, &hwm, 4)); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // set pub socket options int wait = 1; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_XPUB_NODROP, &wait, 4)); // Create a subscriber void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); // Subscribe for all messages. TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, "", 0)); // we must wait for the subscription to be processed here, otherwise some // or all published messages might be lost recv_string_expect_success (pub, "\1", 0); int hwmlimit = hwm - 1; int send_count = 0; // Send an empty message for (int i = 0; i < hwmlimit; i++) { TEST_ASSERT_SUCCESS_ERRNO (zmq_send (pub, NULL, 0, 0)); send_count++; } int recv_count = 0; do { // Receive the message in the subscriber int rc = zmq_recv (sub, NULL, 0, 0); if (rc == -1) { TEST_ASSERT_EQUAL_INT (EAGAIN, errno); break; } TEST_ASSERT_EQUAL_INT (0, rc); recv_count++; if (recv_count == 1) { const int sub_rcvtimeo = 250; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( sub, ZMQ_RCVTIMEO, &sub_rcvtimeo, sizeof (sub_rcvtimeo))); } } while (true); TEST_ASSERT_EQUAL_INT (send_count, recv_count); // Now test real blocking behavior // Set a timeout, default is infinite int timeout = 0; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (pub, ZMQ_SNDTIMEO, &timeout, 4)); send_count = 0; recv_count = 0; hwmlimit = hwm; // Send an empty message until we get an error, which must be EAGAIN while (zmq_send (pub, "", 0, 0) == 0) send_count++; TEST_ASSERT_EQUAL_INT (EAGAIN, errno); if (send_count > 0) { // Receive first message with blocking TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (sub, NULL, 0, 0)); recv_count++; while (zmq_recv (sub, NULL, 0, ZMQ_DONTWAIT) == 0) recv_count++; } TEST_ASSERT_EQUAL_INT (send_count, recv_count); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test); return UNITY_END (); }
sophomore_public/libzmq
tests/test_xpub_nodrop.cpp
C++
gpl-3.0
2,684
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT const char bind_address[] = "tcp://127.0.0.1:*"; char connect_address[MAX_SOCKET_STRING]; // 245 chars + 10 chars for subscribe command = 255 chars const char short_topic[] = "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP" "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP" "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP" "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDE"; // 246 chars + 10 chars for subscribe command = 256 chars const char long_topic[] = "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP" "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP" "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP" "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEF"; template <size_t SIZE> void test_subscribe_cancel (void *xpub, void *sub, const char (&topic)[SIZE]) { // Ignore '\0' terminating the topic string. const size_t topic_len = SIZE - 1; // Subscribe for topic TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic, topic_len)); // Allow receiving more than the expected number of bytes char buffer[topic_len + 5]; // Receive subscription int rc = TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (xpub, buffer, sizeof (buffer), 0)); TEST_ASSERT_EQUAL_INT (topic_len + 1, rc); TEST_ASSERT_EQUAL_UINT8 (1, buffer[0]); TEST_ASSERT_EQUAL_UINT8_ARRAY (topic, buffer + 1, topic_len); // Unsubscribe from topic TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic, topic_len)); // Receive unsubscription rc = TEST_ASSERT_SUCCESS_ERRNO (zmq_recv (xpub, buffer, sizeof (buffer), 0)); TEST_ASSERT_EQUAL_INT (topic_len + 1, rc); TEST_ASSERT_EQUAL_UINT8 (0, buffer[0]); TEST_ASSERT_EQUAL_UINT8_ARRAY (topic, buffer + 1, topic_len); } void test_xpub_subscribe_long_topic () { void *xpub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (xpub, bind_address)); size_t len = MAX_SOCKET_STRING; TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (xpub, ZMQ_LAST_ENDPOINT, connect_address, &len)); void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, connect_address)); test_subscribe_cancel (xpub, sub, short_topic); test_subscribe_cancel (xpub, sub, long_topic); // Clean up. test_context_socket_close (xpub); test_context_socket_close (sub); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_xpub_subscribe_long_topic); return UNITY_END (); }
sophomore_public/libzmq
tests/test_xpub_topic.cpp
C++
gpl-3.0
2,763
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT const uint8_t unsubscribe_a_msg[] = {0, 'A'}; const uint8_t subscribe_a_msg[] = {1, 'A'}; const uint8_t subscribe_b_msg[] = {1, 'B'}; const char test_endpoint[] = "inproc://soname"; const char topic_a[] = "A"; const char topic_b[] = "B"; void test_xpub_verbose_one_sub () { void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, test_endpoint)); void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, test_endpoint)); // Subscribe for A TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_a, 1)); // Receive subscriptions from subscriber recv_array_expect_success (pub, subscribe_a_msg, 0); // Subscribe socket for B instead TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_b, 1)); // Receive subscriptions from subscriber recv_array_expect_success (pub, subscribe_b_msg, 0); // Subscribe again for A again TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_a, 1)); // This time it is duplicated, so it will be filtered out TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); int verbose = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_VERBOSE, &verbose, sizeof (int))); // Subscribe socket for A again TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_a, 1)); // This time with VERBOSE the duplicated sub will be received recv_array_expect_success (pub, subscribe_a_msg, 0); // Sending A message and B Message send_string_expect_success (pub, topic_a, 0); send_string_expect_success (pub, topic_b, 0); recv_string_expect_success (sub, topic_a, 0); recv_string_expect_success (sub, topic_b, 0); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } void create_xpub_with_2_subs (void **pub_, void **sub0_, void **sub1_) { *pub_ = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (*pub_, test_endpoint)); *sub0_ = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (*sub0_, test_endpoint)); *sub1_ = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (*sub1_, test_endpoint)); } void create_duplicate_subscription (void *pub_, void *sub0_, void *sub1_) { // Subscribe for A TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub0_, ZMQ_SUBSCRIBE, topic_a, 1)); // Receive subscriptions from subscriber recv_array_expect_success (pub_, subscribe_a_msg, 0); // Subscribe again for A on the other socket TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1_, ZMQ_SUBSCRIBE, topic_a, 1)); // This time it is duplicated, so it will be filtered out by XPUB TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub_, NULL, 0, ZMQ_DONTWAIT)); } void test_xpub_verbose_two_subs () { void *pub, *sub0, *sub1; create_xpub_with_2_subs (&pub, &sub0, &sub1); create_duplicate_subscription (pub, sub0, sub1); // Subscribe socket for B instead TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub0, ZMQ_SUBSCRIBE, topic_b, 1)); // Receive subscriptions from subscriber recv_array_expect_success (pub, subscribe_b_msg, 0); int verbose = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_VERBOSE, &verbose, sizeof (int))); // Subscribe socket for A again TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, topic_a, 1)); // This time with VERBOSE the duplicated sub will be received recv_array_expect_success (pub, subscribe_a_msg, 0); // Sending A message and B Message send_string_expect_success (pub, topic_a, 0); send_string_expect_success (pub, topic_b, 0); recv_string_expect_success (sub0, topic_a, 0); recv_string_expect_success (sub1, topic_a, 0); recv_string_expect_success (sub0, topic_b, 0); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub0); test_context_socket_close (sub1); } void test_xpub_verboser_one_sub () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, test_endpoint)); // Create a subscriber void *sub = test_context_socket (ZMQ_SUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, test_endpoint)); // Unsubscribe for A, does not exist yet TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Does not exist, so it will be filtered out by XSUB TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // Subscribe for A TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_a, 1)); // Receive subscriptions from subscriber recv_array_expect_success (pub, subscribe_a_msg, 0); // Subscribe again for A again, XSUB will increase refcount TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_a, 1)); // This time it is duplicated, so it will be filtered out by XPUB TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // Unsubscribe for A, this time it exists in XPUB TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic_a, 1)); // XSUB refcounts and will not actually send unsub to PUB until the number // of unsubs match the earlier subs TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Receive unsubscriptions from subscriber recv_array_expect_success (pub, unsubscribe_a_msg, 0); // XSUB only sends the last and final unsub, so XPUB will only receive 1 TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // Unsubscribe for A, does not exist anymore TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Does not exist, so it will be filtered out by XSUB TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); int verbose = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_VERBOSER, &verbose, sizeof (int))); // Subscribe socket for A again TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, topic_a, 1)); // Receive subscriptions from subscriber, did not exist anymore recv_array_expect_success (pub, subscribe_a_msg, 0); // Sending A message to make sure everything still works send_string_expect_success (pub, topic_a, 0); recv_string_expect_success (sub, topic_a, 0); // Unsubscribe for A, this time it exists TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Receive unsubscriptions from subscriber recv_array_expect_success (pub, unsubscribe_a_msg, 0); // Unsubscribe for A again, it does not exist anymore so XSUB will filter TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub, ZMQ_UNSUBSCRIBE, topic_a, 1)); // XSUB only sends unsub if it matched it in its trie, IOW: it will only // send it if it existed in the first place even with XPUB_VERBBOSER TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } void test_xpub_verboser_two_subs () { void *pub, *sub0, *sub1; create_xpub_with_2_subs (&pub, &sub0, &sub1); create_duplicate_subscription (pub, sub0, sub1); // Unsubscribe for A, this time it exists in XPUB TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub0, ZMQ_UNSUBSCRIBE, topic_a, 1)); // sub1 is still subscribed, so no notification TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // Unsubscribe the second socket to trigger the notification TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Receive unsubscriptions since all sockets are gone recv_array_expect_success (pub, unsubscribe_a_msg, 0); // Make really sure there is only one notification TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); int verbose = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_VERBOSER, &verbose, sizeof (int))); // Subscribe socket for A again TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub0, ZMQ_SUBSCRIBE, topic_a, 1)); // Subscribe socket for A again TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, topic_a, 1)); // Receive subscriptions from subscriber, did not exist anymore recv_array_expect_success (pub, subscribe_a_msg, 0); // VERBOSER is set, so subs from both sockets are received recv_array_expect_success (pub, subscribe_a_msg, 0); // Sending A message to make sure everything still works send_string_expect_success (pub, topic_a, 0); recv_string_expect_success (sub0, topic_a, 0); recv_string_expect_success (sub1, topic_a, 0); // Unsubscribe for A TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Receive unsubscriptions from first subscriber due to VERBOSER recv_array_expect_success (pub, unsubscribe_a_msg, 0); // Unsubscribe for A again from the other socket TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub0, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Receive unsubscriptions from first subscriber due to VERBOSER recv_array_expect_success (pub, unsubscribe_a_msg, 0); // Unsubscribe again to make sure it gets filtered now TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (sub1, ZMQ_UNSUBSCRIBE, topic_a, 1)); // Unmatched, so XSUB filters even with VERBOSER TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub0); test_context_socket_close (sub1); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_xpub_verbose_one_sub); RUN_TEST (test_xpub_verbose_two_subs); RUN_TEST (test_xpub_verboser_one_sub); RUN_TEST (test_xpub_verboser_two_subs); return UNITY_END (); }
sophomore_public/libzmq
tests/test_xpub_verbose.cpp
C++
gpl-3.0
10,420
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT void test () { // Create a publisher void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, "inproc://soname")); // set pub socket options TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_WELCOME_MSG, "W", 1)); // Create a subscriber void *sub = test_context_socket (ZMQ_SUB); // Subscribe to the welcome message TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (sub, ZMQ_SUBSCRIBE, "W", 1)); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, "inproc://soname")); const uint8_t buffer[2] = {1, 'W'}; // Receive the welcome subscription recv_array_expect_success (pub, buffer, 0); // Receive the welcome message recv_string_expect_success (sub, "W", 0); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test); return UNITY_END (); }
sophomore_public/libzmq
tests/test_xpub_welcome_msg.cpp
C++
gpl-3.0
1,090
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" SETUP_TEARDOWN_TESTCONTEXT const uint8_t unsubscribe_a_msg[] = {0, 'A'}; const uint8_t subscribe_a_msg[] = {1, 'A'}; const char test_endpoint[] = "inproc://soname"; void test_xsub_verbose_unsubscribe () { void *pub = test_context_socket (ZMQ_XPUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (pub, test_endpoint)); void *sub = test_context_socket (ZMQ_XSUB); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sub, test_endpoint)); // set option ZMQ_XPUB_VERBOSER to get all messages int xbup_verboser = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (pub, ZMQ_XPUB_VERBOSER, &xbup_verboser, sizeof (int))); // unsubscribe from topic A, does not exist yet send_array_expect_success (sub, unsubscribe_a_msg, 0); // does not exist, so it will be filtered out by XSUB TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // subscribe to topic A send_array_expect_success (sub, subscribe_a_msg, 0); // receive subscription from subscriber recv_array_expect_success (pub, subscribe_a_msg, 0); // subscribe again to topic A send_array_expect_success (sub, subscribe_a_msg, 0); // receive subscription from subscriber recv_array_expect_success (pub, subscribe_a_msg, 0); // unsubscribe from topic A send_array_expect_success (sub, unsubscribe_a_msg, 0); // The first unsubscribe will be filtered out TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (pub, NULL, 0, ZMQ_DONTWAIT)); // unsubscribe again from topic A send_array_expect_success (sub, unsubscribe_a_msg, 0); // receive unsubscription from subscriber recv_array_expect_success (pub, unsubscribe_a_msg, 0); // set option ZMQ_XSUB_VERBOSE_UNSUBSCRIBE to get duplicate unsubscribes int xsub_verbose = 1; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( sub, ZMQ_XSUB_VERBOSE_UNSUBSCRIBE, &xsub_verbose, sizeof (int))); // unsubscribe from topic A, does not exist yet send_array_expect_success (sub, unsubscribe_a_msg, 0); // does not exist, but with ZMQ_XSUB_VERBOSE_UNSUBSCRIBE set it will be forwarded anyway recv_array_expect_success (pub, unsubscribe_a_msg, 0); // subscribe to topic A send_array_expect_success (sub, subscribe_a_msg, 0); // receive subscription from subscriber recv_array_expect_success (pub, subscribe_a_msg, 0); // subscribe again to topic A send_array_expect_success (sub, subscribe_a_msg, 0); // receive subscription from subscriber recv_array_expect_success (pub, subscribe_a_msg, 0); // unsubscribe from topic A send_array_expect_success (sub, unsubscribe_a_msg, 0); // receive unsubscription from subscriber recv_array_expect_success (pub, unsubscribe_a_msg, 0); // unsubscribe again from topic A send_array_expect_success (sub, unsubscribe_a_msg, 0); // receive unsubscription from subscriber recv_array_expect_success (pub, unsubscribe_a_msg, 0); // Clean up. test_context_socket_close (pub); test_context_socket_close (sub); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_xsub_verbose_unsubscribe); return UNITY_END (); }
sophomore_public/libzmq
tests/test_xsub_verbose.cpp
C++
gpl-3.0
3,290
/* SPDX-License-Identifier: MPL-2.0 */ #ifdef ZMQ_USE_FUZZING_ENGINE #include <fuzzer/FuzzedDataProvider.h> #endif #include <string> #include <stdlib.h> #include "testutil.hpp" #include "testutil_unity.hpp" extern "C" int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { uint8_t *secret_key; if (size < 5) return 0; // As per API definition, input must be divisible by 5, so truncate it if it's not size -= size % 5; // As per API definition, the destination must be at least 0.8 times the input data TEST_ASSERT_NOT_NULL (secret_key = (uint8_t *) malloc (size * 4 / 5)); std::string z85_secret_key (reinterpret_cast<const char *> (data), size); zmq_z85_decode (secret_key, z85_secret_key.c_str ()); free (secret_key); return 0; } #ifndef ZMQ_USE_FUZZING_ENGINE void test_z85_decode_fuzzer () { uint8_t **data; size_t *len, num_cases = 0; if (fuzzer_corpus_encode ( "tests/libzmq-fuzz-corpora/test_z85_decode_fuzzer_seed_corpus", &data, &len, &num_cases) != 0) exit (77); while (num_cases-- > 0) { TEST_ASSERT_SUCCESS_ERRNO ( LLVMFuzzerTestOneInput (data[num_cases], len[num_cases])); free (data[num_cases]); } free (data); free (len); } int main (int argc, char **argv) { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_z85_decode_fuzzer); return UNITY_END (); } #endif
sophomore_public/libzmq
tests/test_z85_decode_fuzzer.cpp
C++
gpl-3.0
1,461
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <netdb.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #endif SETUP_TEARDOWN_TESTCONTEXT void test_poll_fd () { int recv_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); TEST_ASSERT_NOT_EQUAL (-1, recv_socket); int flag = 1; TEST_ASSERT_SUCCESS_ERRNO ( setsockopt (recv_socket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int))); struct sockaddr_in saddr = bind_bsd_socket (recv_socket); void *sb = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://127.0.0.1:*")); zmq_pollitem_t pollitems[] = { {sb, 0, ZMQ_POLLIN, 0}, {NULL, recv_socket, ZMQ_POLLIN, 0}, }; int send_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); TEST_ASSERT_NOT_EQUAL (-1, send_socket); char buf[10]; memset (buf, 1, 10); TEST_ASSERT_SUCCESS_ERRNO (sendto ( send_socket, buf, 10, 0, (struct sockaddr *) &saddr, sizeof (saddr))); TEST_ASSERT_EQUAL (1, zmq_poll (pollitems, 2, 1)); TEST_ASSERT_BITS_LOW (ZMQ_POLLIN, pollitems[0].revents); TEST_ASSERT_BITS_HIGH (ZMQ_POLLIN, pollitems[1].revents); test_context_socket_close (sb); close (send_socket); close (recv_socket); } int main () { UNITY_BEGIN (); RUN_TEST (test_poll_fd); return UNITY_END (); }
sophomore_public/libzmq
tests/test_zmq_poll_fd.cpp
C++
gpl-3.0
1,397
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> #ifndef _WIN32 #include <netdb.h> #include <unistd.h> #endif SETUP_TEARDOWN_TESTCONTEXT void test_ppoll_fd () { #ifdef ZMQ_HAVE_PPOLL int recv_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); TEST_ASSERT_NOT_EQUAL (-1, recv_socket); int flag = 1; TEST_ASSERT_SUCCESS_ERRNO ( setsockopt (recv_socket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int))); struct sockaddr_in saddr = bind_bsd_socket (recv_socket); void *sb = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tcp://127.0.0.1:*")); zmq_pollitem_t pollitems[] = { {sb, 0, ZMQ_POLLIN, 0}, {NULL, recv_socket, ZMQ_POLLIN, 0}, }; int send_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); TEST_ASSERT_NOT_EQUAL (-1, send_socket); char buf[10]; memset (buf, 1, 10); TEST_ASSERT_SUCCESS_ERRNO (sendto ( send_socket, buf, 10, 0, (struct sockaddr *) &saddr, sizeof (saddr))); TEST_ASSERT_EQUAL (1, zmq_ppoll (pollitems, 2, 1, NULL)); TEST_ASSERT_BITS_LOW (ZMQ_POLLIN, pollitems[0].revents); TEST_ASSERT_BITS_HIGH (ZMQ_POLLIN, pollitems[1].revents); test_context_socket_close (sb); close (send_socket); close (recv_socket); #else TEST_IGNORE_MESSAGE ("libzmq without zmq_ppoll, ignoring test"); #endif // ZMQ_HAVE_PPOLL } int main () { UNITY_BEGIN (); RUN_TEST (test_ppoll_fd); return UNITY_END (); }
sophomore_public/libzmq
tests/test_zmq_ppoll_fd.cpp
C++
gpl-3.0
1,528
/* SPDX-License-Identifier: MPL-2.0 */ // author: E. G. Patrick Bos, Netherlands eScience Center, 2021 #include "testutil.hpp" #include "testutil_unity.hpp" #include <string.h> // memset // types.h and wait.h for waitpid: #include <sys/types.h> #include <sys/wait.h> static bool sigterm_received = false; void handle_sigterm (int /*signum*/) { sigterm_received = true; } void recv_string_expect_success_or_eagain (void *socket_, const char *str_, int flags_) { const size_t len = str_ ? strlen (str_) : 0; char buffer[255]; TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (sizeof (buffer), len, "recv_string_expect_success cannot be " "used for strings longer than 255 " "characters"); const int rc = zmq_recv (socket_, buffer, sizeof (buffer), flags_); if (rc < 0) { if (errno == EAGAIN) { printf ("got EAGAIN\n"); return; } else { TEST_ASSERT_SUCCESS_ERRNO (rc); } } else { TEST_ASSERT_EQUAL_INT ((int) len, rc); if (str_) TEST_ASSERT_EQUAL_STRING_LEN (str_, buffer, len); } } void test_ppoll_signals () { #ifdef ZMQ_HAVE_PPOLL size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; pid_t child_pid; /* Get a random TCP port first */ setup_test_context (); void *sb = test_context_socket (ZMQ_REP); bind_loopback (sb, 0, my_endpoint, len); test_context_socket_close (sb); teardown_test_context (); do { child_pid = fork (); } while (child_pid == -1); // retry if fork fails if (child_pid > 0) { // parent setup_test_context (); void *socket = test_context_socket (ZMQ_REQ); // to make sure we don't hang when the child has already exited at the end, we set a receive timeout of five seconds int recv_timeout = 5000; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( socket, ZMQ_RCVTIMEO, &recv_timeout, sizeof (recv_timeout))); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (socket, my_endpoint)); // bind is on the master process to avoid zombie children to hold on to binds // first send a test message to check whether the signal mask is setup in the child process send_string_expect_success (socket, "breaker breaker", 0); recv_string_expect_success (socket, "one-niner", 0); // then send the signal kill (child_pid, SIGTERM); // for good measure, and to make sure everything went as expected, close off with another handshake, which will trigger the second poll call on the other side send_string_expect_success (socket, "breaker breaker", 0); // in case the 1 second sleep was not enough on the child side, we are also fine with an EAGAIN here recv_string_expect_success_or_eagain (socket, "one-niner", 0); // finish test_context_socket_close (socket); teardown_test_context (); // wait for child int status = 0; pid_t pid; do { pid = waitpid (child_pid, &status, 0); } while (-1 == pid && EINTR == errno); // retry on interrupted system call if (0 != status) { if (WIFEXITED (status)) { printf ("exited, status=%d\n", WEXITSTATUS (status)); } else if (WIFSIGNALED (status)) { printf ("killed by signal %d\n", WTERMSIG (status)); } else if (WIFSTOPPED (status)) { printf ("stopped by signal %d\n", WSTOPSIG (status)); } else if (WIFCONTINUED (status)) { printf ("continued\n"); } } if (-1 == pid) { printf ("waitpid returned -1, with errno %s\n", strerror (errno)); } } else { // child setup_test_context (); // set up signal mask and install handler for SIGTERM sigset_t sigmask, sigmask_without_sigterm; sigemptyset (&sigmask); sigaddset (&sigmask, SIGTERM); sigprocmask (SIG_BLOCK, &sigmask, &sigmask_without_sigterm); struct sigaction sa; memset (&sa, '\0', sizeof (sa)); sa.sa_handler = handle_sigterm; TEST_ASSERT_SUCCESS_ERRNO (sigaction (SIGTERM, &sa, NULL)); void *socket = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (socket, my_endpoint)); zmq_pollitem_t pollitems[] = { {socket, 0, ZMQ_POLLIN, 0}, }; // first receive test message and send back handshake recv_string_expect_success (socket, "breaker breaker", 0); send_string_expect_success (socket, "one-niner", 0); // now start ppolling, which should exit with EINTR because of the SIGTERM TEST_ASSERT_FAILURE_ERRNO ( EINTR, zmq_ppoll (pollitems, 1, -1, &sigmask_without_sigterm)); TEST_ASSERT_TRUE (sigterm_received); // poll again for the final handshake TEST_ASSERT_SUCCESS_ERRNO ( zmq_ppoll (pollitems, 1, -1, &sigmask_without_sigterm)); TEST_ASSERT_BITS_HIGH (ZMQ_POLLIN, pollitems[0].revents); // receive and send back handshake recv_string_expect_success (socket, "breaker breaker", 0); send_string_expect_success (socket, "one-niner", 0); // finish // wait before closing socket, so that parent has time to receive sleep (1); test_context_socket_close (socket); teardown_test_context (); _Exit (0); } #else TEST_IGNORE_MESSAGE ("libzmq without zmq_ppoll, ignoring test"); #endif // ZMQ_HAVE_PPOLL } // We note that using zmq_poll instead of zmq_ppoll in the test above, while // also not using the sigmask, will fail most of the time, because it is // impossible to predict during which call the signal will be handled. Of // course, every call could be surrounded with an EINTR check and a subsequent // check of sigterm_received's value, but even then a race condition can occur, // see the explanation given here: https://250bpm.com/blog:12/ int main () { UNITY_BEGIN (); RUN_TEST (test_ppoll_signals); return UNITY_END (); }
sophomore_public/libzmq
tests/test_zmq_ppoll_signals.cpp
C++
gpl-3.0
6,333
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil.hpp" #include "testutil_unity.hpp" #include <stdarg.h> #include <string.h> #if defined _WIN32 #include "../src/windows.hpp" #if defined ZMQ_HAVE_WINDOWS #if defined ZMQ_HAVE_IPC #include <direct.h> #include <afunix.h> #endif #include <crtdbg.h> #pragma warning(disable : 4996) // iphlpapi is needed for if_nametoindex (not on Windows XP) #if _WIN32_WINNT > _WIN32_WINNT_WINXP #pragma comment(lib, "iphlpapi") #endif #endif #else #include <pthread.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> #include <grp.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include <netdb.h> #include <sys/un.h> #include <dirent.h> #if defined(ZMQ_HAVE_AIX) #include <sys/types.h> #include <sys/socketvar.h> #endif #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif const char *SEQ_END = (const char *) 1; const char bounce_content[] = "12345678ABCDEFGH12345678abcdefgh"; static void send_bounce_msg (void *socket_) { send_string_expect_success (socket_, bounce_content, ZMQ_SNDMORE); send_string_expect_success (socket_, bounce_content, 0); } static void recv_bounce_msg (void *socket_) { recv_string_expect_success (socket_, bounce_content, 0); int rcvmore; size_t sz = sizeof (rcvmore); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (socket_, ZMQ_RCVMORE, &rcvmore, &sz)); TEST_ASSERT_TRUE (rcvmore); recv_string_expect_success (socket_, bounce_content, 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (socket_, ZMQ_RCVMORE, &rcvmore, &sz)); TEST_ASSERT_FALSE (rcvmore); } void bounce (void *server_, void *client_) { // Send message from client to server send_bounce_msg (client_); // Receive message at server side and // check that message is still the same recv_bounce_msg (server_); // Send two parts back to client send_bounce_msg (server_); // Receive the two parts at the client side recv_bounce_msg (client_); } static void send_bounce_msg_may_fail (void *socket_) { int timeout = 250; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (socket_, ZMQ_SNDTIMEO, &timeout, sizeof (int))); int rc = zmq_send (socket_, bounce_content, 32, ZMQ_SNDMORE); TEST_ASSERT_TRUE ((rc == 32) || ((rc == -1) && (errno == EAGAIN))); rc = zmq_send (socket_, bounce_content, 32, 0); TEST_ASSERT_TRUE ((rc == 32) || ((rc == -1) && (errno == EAGAIN))); } static void recv_bounce_msg_fail (void *socket_) { int timeout = 250; char buffer[32]; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (socket_, ZMQ_RCVTIMEO, &timeout, sizeof (int))); TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_recv (socket_, buffer, 32, 0)); } void expect_bounce_fail (void *server_, void *client_) { // Send message from client to server send_bounce_msg_may_fail (client_); // Receive message at server side (should not succeed) recv_bounce_msg_fail (server_); // Send message from server to client to test other direction // If connection failed, send may block, without a timeout send_bounce_msg_may_fail (server_); // Receive message at client side (should not succeed) recv_bounce_msg_fail (client_); } char *s_recv (void *socket_) { char buffer[256]; int size = zmq_recv (socket_, buffer, 255, 0); if (size == -1) return NULL; if (size > 255) size = 255; buffer[size] = 0; return strdup (buffer); } void s_send_seq (void *socket_, ...) { va_list ap; va_start (ap, socket_); const char *data = va_arg (ap, const char *); while (true) { const char *prev = data; data = va_arg (ap, const char *); bool end = data == SEQ_END; if (!prev) { TEST_ASSERT_SUCCESS_ERRNO ( zmq_send (socket_, 0, 0, end ? 0 : ZMQ_SNDMORE)); } else { TEST_ASSERT_SUCCESS_ERRNO (zmq_send ( socket_, prev, strlen (prev) + 1, end ? 0 : ZMQ_SNDMORE)); } if (end) break; } va_end (ap); } void s_recv_seq (void *socket_, ...) { zmq_msg_t msg; zmq_msg_init (&msg); int more; size_t more_size = sizeof (more); va_list ap; va_start (ap, socket_); const char *data = va_arg (ap, const char *); while (true) { TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, socket_, 0)); if (!data) TEST_ASSERT_EQUAL_INT (0, zmq_msg_size (&msg)); else TEST_ASSERT_EQUAL_STRING (data, (const char *) zmq_msg_data (&msg)); data = va_arg (ap, const char *); bool end = data == SEQ_END; TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (socket_, ZMQ_RCVMORE, &more, &more_size)); TEST_ASSERT_TRUE (!more == end); if (end) break; } va_end (ap); zmq_msg_close (&msg); } void close_zero_linger (void *socket_) { int linger = 0; int rc = zmq_setsockopt (socket_, ZMQ_LINGER, &linger, sizeof (linger)); TEST_ASSERT_TRUE (rc == 0 || errno == ETERM); TEST_ASSERT_SUCCESS_ERRNO (zmq_close (socket_)); } void setup_test_environment (int timeout_seconds_) { #if defined _WIN32 #if defined _MSC_VER _set_abort_behavior (0, _WRITE_ABORT_MSG); _CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile (_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif #else #if defined ZMQ_HAVE_CYGWIN // abort test after 121 seconds alarm (121); #else #if !defined ZMQ_DISABLE_TEST_TIMEOUT // abort test after timeout_seconds_ seconds alarm (timeout_seconds_); #endif #endif #endif #if defined __MVS__ // z/OS UNIX System Services: Ignore SIGPIPE during test runs, as a // workaround for no SO_NOGSIGPIPE socket option. signal (SIGPIPE, SIG_IGN); #endif } void msleep (int milliseconds_) { #ifdef ZMQ_HAVE_WINDOWS Sleep (milliseconds_); #else usleep (static_cast<useconds_t> (milliseconds_) * 1000); #endif } int is_ipv6_available () { #if defined(ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) return 0; #else int rc, ipv6 = 1; struct sockaddr_in6 test_addr; memset (&test_addr, 0, sizeof (test_addr)); test_addr.sin6_family = AF_INET6; inet_pton (AF_INET6, "::1", &(test_addr.sin6_addr)); fd_t fd = socket (AF_INET6, SOCK_STREAM, IPPROTO_IP); if (fd == retired_fd) ipv6 = 0; else { #ifdef ZMQ_HAVE_WINDOWS setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (const char *) &ipv6, sizeof (int)); rc = setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *) &ipv6, sizeof (int)); if (rc == SOCKET_ERROR) ipv6 = 0; else { rc = bind (fd, (struct sockaddr *) &test_addr, sizeof (test_addr)); if (rc == SOCKET_ERROR) ipv6 = 0; } #else setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &ipv6, sizeof (int)); rc = setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6, sizeof (int)); if (rc != 0) ipv6 = 0; else { rc = bind (fd, reinterpret_cast<struct sockaddr *> (&test_addr), sizeof (test_addr)); if (rc != 0) ipv6 = 0; } #endif close (fd); } return ipv6; #endif // _WIN32_WINNT < 0x0600 } int is_tipc_available () { #ifndef ZMQ_HAVE_TIPC return 0; #else int tipc = 0; void *ctx = zmq_init (1); TEST_ASSERT_NOT_NULL (ctx); void *rep = zmq_socket (ctx, ZMQ_REP); TEST_ASSERT_NOT_NULL (rep); tipc = zmq_bind (rep, "tipc://{5560,0,0}"); zmq_close (rep); zmq_ctx_term (ctx); return tipc == 0; #endif // ZMQ_HAVE_TIPC } int test_inet_pton (int af_, const char *src_, void *dst_) { #if defined(ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) if (af_ == AF_INET) { struct in_addr *ip4addr = (struct in_addr *) dst_; ip4addr->s_addr = inet_addr (src_); // INADDR_NONE is -1 which is also a valid representation for IP // 255.255.255.255 if (ip4addr->s_addr == INADDR_NONE && strcmp (src_, "255.255.255.255") != 0) { return 0; } // Success return 1; } else { // Not supported. return 0; } #else return inet_pton (af_, src_, dst_); #endif } sockaddr_in bind_bsd_socket (int socket_) { struct sockaddr_in saddr; memset (&saddr, 0, sizeof (saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; #if !defined(_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600) saddr.sin_port = 0; #else saddr.sin_port = htons (PORT_6); #endif TEST_ASSERT_SUCCESS_RAW_ERRNO ( bind (socket_, (struct sockaddr *) &saddr, sizeof (saddr))); #if !defined(_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600) socklen_t saddr_len = sizeof (saddr); TEST_ASSERT_SUCCESS_RAW_ERRNO ( getsockname (socket_, (struct sockaddr *) &saddr, &saddr_len)); #endif return saddr; } fd_t connect_socket (const char *endpoint_, const int af_, const int protocol_) { struct sockaddr_storage addr; // OSX is very opinionated and wants the size to match the AF family type socklen_t addr_len; const fd_t s_pre = socket (af_, SOCK_STREAM, protocol_ == IPPROTO_UDP ? IPPROTO_UDP : protocol_ == IPPROTO_TCP ? IPPROTO_TCP : 0); #ifdef ZMQ_HAVE_WINDOWS TEST_ASSERT_NOT_EQUAL (INVALID_SOCKET, s_pre); #else TEST_ASSERT_NOT_EQUAL (-1, s_pre); #endif if (af_ == AF_INET || af_ == AF_INET6) { const char *port = strrchr (endpoint_, ':') + 1; char address[MAX_SOCKET_STRING]; // getaddrinfo does not like [x:y::z] if (*strchr (endpoint_, '/') + 2 == '[') { strcpy (address, strchr (endpoint_, '[') + 1); address[strlen (address) - strlen (port) - 2] = '\0'; } else { strcpy (address, strchr (endpoint_, '/') + 2); address[strlen (address) - strlen (port) - 1] = '\0'; } struct addrinfo *in, hint; memset (&hint, 0, sizeof (struct addrinfo)); hint.ai_flags = AI_NUMERICSERV; hint.ai_family = af_; hint.ai_socktype = protocol_ == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; hint.ai_protocol = protocol_ == IPPROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP; TEST_ASSERT_SUCCESS_RAW_ZERO_ERRNO ( getaddrinfo (address, port, &hint, &in)); TEST_ASSERT_NOT_NULL (in); memcpy (&addr, in->ai_addr, in->ai_addrlen); addr_len = (socklen_t) in->ai_addrlen; freeaddrinfo (in); } else { #if defined(ZMQ_HAVE_IPC) // Cannot cast addr as gcc 4.4 will fail with strict aliasing errors (*(struct sockaddr_un *) &addr).sun_family = AF_UNIX; strcpy ((*(struct sockaddr_un *) &addr).sun_path, endpoint_); addr_len = sizeof (struct sockaddr_un); #else return retired_fd; #endif } TEST_ASSERT_SUCCESS_RAW_ERRNO ( connect (s_pre, (struct sockaddr *) &addr, addr_len)); return s_pre; } fd_t bind_socket_resolve_port (const char *address_, const char *port_, char *my_endpoint_, const int af_, const int protocol_) { struct sockaddr_storage addr; // OSX is very opinionated and wants the size to match the AF family type socklen_t addr_len; const fd_t s_pre = socket (af_, SOCK_STREAM, protocol_ == IPPROTO_UDP ? IPPROTO_UDP : protocol_ == IPPROTO_TCP ? IPPROTO_TCP : 0); #ifdef ZMQ_HAVE_WINDOWS TEST_ASSERT_NOT_EQUAL (INVALID_SOCKET, s_pre); #else TEST_ASSERT_NOT_EQUAL (-1, s_pre); #endif if (af_ == AF_INET || af_ == AF_INET6) { #ifdef ZMQ_HAVE_WINDOWS const char flag = '\1'; #elif defined ZMQ_HAVE_VXWORKS char flag = '\1'; #else int flag = 1; #endif struct addrinfo *in, hint; memset (&hint, 0, sizeof (struct addrinfo)); hint.ai_flags = AI_NUMERICSERV; hint.ai_family = af_; hint.ai_socktype = protocol_ == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; hint.ai_protocol = protocol_ == IPPROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP; TEST_ASSERT_SUCCESS_RAW_ERRNO ( setsockopt (s_pre, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int))); TEST_ASSERT_SUCCESS_RAW_ZERO_ERRNO ( getaddrinfo (address_, port_, &hint, &in)); TEST_ASSERT_NOT_NULL (in); memcpy (&addr, in->ai_addr, in->ai_addrlen); addr_len = (socklen_t) in->ai_addrlen; freeaddrinfo (in); } else { #if defined(ZMQ_HAVE_IPC) // Cannot cast addr as gcc 4.4 will fail with strict aliasing errors (*(struct sockaddr_un *) &addr).sun_family = AF_UNIX; addr_len = sizeof (struct sockaddr_un); #if defined ZMQ_HAVE_WINDOWS char buffer[MAX_PATH] = ""; TEST_ASSERT_SUCCESS_RAW_ERRNO (tmpnam_s (buffer)); TEST_ASSERT_SUCCESS_RAW_ERRNO (_mkdir (buffer)); strcat (buffer, "/ipc"); #else char buffer[PATH_MAX] = ""; strcpy (buffer, "tmpXXXXXX"); #ifdef HAVE_MKDTEMP TEST_ASSERT_TRUE (mkdtemp (buffer)); strcat (buffer, "/socket"); #else int fd = mkstemp (buffer); TEST_ASSERT_TRUE (fd != -1); close (fd); #endif #endif strcpy ((*(struct sockaddr_un *) &addr).sun_path, buffer); memcpy (my_endpoint_, "ipc://", 7); strcat (my_endpoint_, buffer); // TODO check return value of unlink unlink (buffer); #else return retired_fd; #endif } TEST_ASSERT_SUCCESS_RAW_ERRNO ( bind (s_pre, (struct sockaddr *) &addr, addr_len)); TEST_ASSERT_SUCCESS_RAW_ERRNO (listen (s_pre, SOMAXCONN)); if (af_ == AF_INET || af_ == AF_INET6) { addr_len = sizeof (struct sockaddr_storage); TEST_ASSERT_SUCCESS_RAW_ERRNO ( getsockname (s_pre, (struct sockaddr *) &addr, &addr_len)); snprintf ( my_endpoint_, 6 + strlen (address_) + 7 * sizeof (char), "%s://%s:%u", protocol_ == IPPROTO_TCP ? "tcp" : protocol_ == IPPROTO_UDP ? "udp" : protocol_ == IPPROTO_WSS ? "wss" : "ws", address_, af_ == AF_INET ? ntohs ((*(struct sockaddr_in *) &addr).sin_port) : ntohs ((*(struct sockaddr_in6 *) &addr).sin6_port)); } return s_pre; } bool streq (const char *lhs_, const char *rhs_) { return strcmp (lhs_, rhs_) == 0; } bool strneq (const char *lhs_, const char *rhs_) { return strcmp (lhs_, rhs_) != 0; } #if defined _WIN32 int fuzzer_corpus_encode (const char *dirname, uint8_t ***data, size_t **len, size_t *num_cases) { (void) dirname; (void) data; (void) len; (void) num_cases; return -1; } #else int fuzzer_corpus_encode (const char *dirname, uint8_t ***data, size_t **len, size_t *num_cases) { TEST_ASSERT_NOT_NULL (dirname); TEST_ASSERT_NOT_NULL (data); TEST_ASSERT_NOT_NULL (len); struct dirent *ent; DIR *dir = opendir (dirname); if (!dir) return -1; *len = NULL; *data = NULL; *num_cases = 0; while ((ent = readdir (dir)) != NULL) { if (!strcmp (ent->d_name, ".") || !strcmp (ent->d_name, "..")) continue; char *filename = (char *) malloc (strlen (dirname) + strlen (ent->d_name) + 2); TEST_ASSERT_NOT_NULL (filename); strcpy (filename, dirname); strcat (filename, "/"); strcat (filename, ent->d_name); FILE *f = fopen (filename, "r"); free (filename); if (!f) continue; fseek (f, 0, SEEK_END); size_t file_len = ftell (f); fseek (f, 0, SEEK_SET); if (file_len == 0) { fclose (f); continue; } *len = (size_t *) realloc (*len, (*num_cases + 1) * sizeof (size_t)); TEST_ASSERT_NOT_NULL (*len); *(*len + *num_cases) = file_len; *data = (uint8_t **) realloc (*data, (*num_cases + 1) * sizeof (uint8_t *)); TEST_ASSERT_NOT_NULL (*data); *(*data + *num_cases) = (uint8_t *) malloc (file_len * sizeof (uint8_t)); TEST_ASSERT_NOT_NULL (*(*data + *num_cases)); size_t read_bytes = 0; read_bytes = fread (*(*data + *num_cases), 1, file_len, f); TEST_ASSERT_EQUAL (file_len, read_bytes); (*num_cases)++; fclose (f); } closedir (dir); return 0; } #endif
sophomore_public/libzmq
tests/testutil.cpp
C++
gpl-3.0
17,020
/* SPDX-License-Identifier: MPL-2.0 */ #ifndef __TESTUTIL_HPP_INCLUDED__ #define __TESTUTIL_HPP_INCLUDED__ #if defined ZMQ_CUSTOM_PLATFORM_HPP #include "platform.hpp" #else #include "../src/platform.hpp" #endif #include "../include/zmq.h" #include "../src/stdint.hpp" // For AF_INET and IPPROTO_TCP #if defined _WIN32 #include "../src/windows.hpp" #if defined(__MINGW32__) #include <unistd.h> #endif #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #endif // This defines the settle time used in tests; raise this if we // get test failures on slower systems due to binds/connects not // settled. Tested to work reliably at 1 msec on a fast PC. #define SETTLE_TIME 300 // In msec // Commonly used buffer size for ZMQ_LAST_ENDPOINT // this used to be sizeof ("tcp://[::ffff:127.127.127.127]:65536"), but this // may be too short for ipc wildcard binds, e.g. #define MAX_SOCKET_STRING 256 // We need to test codepaths with non-random bind ports. List them here to // keep them unique, to allow parallel test runs. #define ENDPOINT_0 "tcp://127.0.0.1:5555" #define ENDPOINT_1 "tcp://127.0.0.1:5556" #define ENDPOINT_2 "tcp://127.0.0.1:5557" #define ENDPOINT_3 "tcp://127.0.0.1:5558" #define ENDPOINT_4 "udp://127.0.0.1:5559" #define ENDPOINT_5 "udp://127.0.0.1:5560" #define PORT_6 5561 // For tests that mock ZMTP const uint8_t zmtp_greeting_null[64] = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f, 3, 0, 'N', 'U', 'L', 'L', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const uint8_t zmtp_greeting_curve[64] = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f, 3, 0, 'C', 'U', 'R', 'V', 'E', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const uint8_t zmtp_ready_dealer[43] = { 4, 41, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e', 't', '-', 'T', 'y', 'p', 'e', 0, 0, 0, 6, 'D', 'E', 'A', 'L', 'E', 'R', 8, 'I', 'd', 'e', 'n', 't', 'i', 't', 'y', 0, 0, 0, 0}; const uint8_t zmtp_ready_xpub[28] = { 4, 26, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e', 't', '-', 'T', 'y', 'p', 'e', 0, 0, 0, 4, 'X', 'P', 'U', 'B'}; const uint8_t zmtp_ready_sub[27] = { 4, 25, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e', 't', '-', 'T', 'y', 'p', 'e', 0, 0, 0, 3, 'S', 'U', 'B'}; #undef NDEBUG #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif // duplicated from fd.hpp #ifdef ZMQ_HAVE_WINDOWS #ifndef NOMINMAX #define NOMINMAX // Macros min(a,b) and max(a,b) #endif #include <winsock2.h> #include <ws2tcpip.h> #include <stdexcept> #define close closesocket typedef int socket_size_t; inline const char *as_setsockopt_opt_t (const void *opt) { return static_cast<const char *> (opt); } #else typedef size_t socket_size_t; inline const void *as_setsockopt_opt_t (const void *opt_) { return opt_; } #endif // duplicated from fd.hpp typedef zmq_fd_t fd_t; #ifdef ZMQ_HAVE_WINDOWS #if defined _MSC_VER && _MSC_VER <= 1400 enum { retired_fd = (zmq_fd_t) (~0) }; #else enum #if _MSC_VER >= 1800 : zmq_fd_t #endif { retired_fd = INVALID_SOCKET }; #endif #else enum { retired_fd = -1 }; #endif // In MSVC prior to v14, snprintf is not available // The closest implementation is the _snprintf_s function #if defined _MSC_VER && _MSC_VER < 1900 #define snprintf(buffer_, count_, format_, ...) \ _snprintf_s (buffer_, count_, _TRUNCATE, format_, __VA_ARGS__) #endif #define LIBZMQ_UNUSED(object) (void) object // Bounce a message from client to server and back // For REQ/REP or DEALER/DEALER pairs only void bounce (void *server_, void *client_); // Same as bounce, but expect messages to never arrive // for security or subscriber reasons. void expect_bounce_fail (void *server_, void *client_); // Receive 0MQ string from socket and convert into C string // Caller must free returned string. Returns NULL if the context // is being terminated. char *s_recv (void *socket_); bool streq (const char *lhs, const char *rhs); bool strneq (const char *lhs, const char *rhs); extern const char *SEQ_END; // Sends a message composed of frames that are C strings or null frames. // The list must be terminated by SEQ_END. // Example: s_send_seq (req, "ABC", 0, "DEF", SEQ_END); void s_send_seq (void *socket_, ...); // Receives message a number of frames long and checks that the frames have // the given data which can be either C strings or 0 for a null frame. // The list must be terminated by SEQ_END. // Example: s_recv_seq (rep, "ABC", 0, "DEF", SEQ_END); void s_recv_seq (void *socket_, ...); // Sets a zero linger period on a socket and closes it. void close_zero_linger (void *socket_); // Setups the test environment. Must be called at the beginning of each test // executable. On POSIX systems, it sets an alarm to the specified number of // seconds, after which the test will be killed. Set to 0 to disable this // timeout. void setup_test_environment (int timeout_seconds_ = 60); // Provide portable millisecond sleep // http://www.cplusplus.com/forum/unices/60161/ // http://en.cppreference.com/w/cpp/thread/sleep_for void msleep (int milliseconds_); // check if IPv6 is available (0/false if not, 1/true if it is) // only way to reliably check is to actually open a socket and try to bind it int is_ipv6_available (void); // check if tipc is available (0/false if not, 1/true if it is) // only way to reliably check is to actually open a socket and try to bind it // as it depends on a non-default kernel module to be already loaded int is_tipc_available (void); // Wrapper around 'inet_pton' for systems that don't support it (e.g. Windows // XP) int test_inet_pton (int af_, const char *src_, void *dst_); // Binds an ipv4 BSD socket to an ephemeral port, returns the compiled sockaddr struct sockaddr_in bind_bsd_socket (int socket); // Some custom definitions in addition to IPPROTO_TCP and IPPROTO_UDP #define IPPROTO_WS 10000 #define IPPROTO_WSS 10001 // Connects a BSD socket to the ZMQ endpoint. Works with ipv4/ipv6/unix. fd_t connect_socket (const char *endpoint_, const int af_ = AF_INET, const int protocol_ = IPPROTO_TCP); // Binds a BSD socket to an ephemeral port, returns the file descriptor. // The resulting ZMQ endpoint will be stored in my_endpoint, including the protocol // prefix, so ensure it is writable and of appropriate size. // Works with ipv4/ipv6/unix. With unix sockets address_/port_ can be empty and // my_endpoint_ will contain a random path. fd_t bind_socket_resolve_port (const char *address_, const char *port_, char *my_endpoint_, const int af_ = AF_INET, const int protocol_ = IPPROTO_TCP); int fuzzer_corpus_encode (const char *filename, uint8_t ***data, size_t **len, size_t *num_cases); #endif
sophomore_public/libzmq
tests/testutil.hpp
C++
gpl-3.0
7,196
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil_monitoring.hpp" #include "testutil_unity.hpp" #include <stdlib.h> #include <string.h> static int receive_monitor_address (void *monitor_, char **address_, bool expect_more_) { zmq_msg_t msg; zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor_, 0) == -1) return -1; // Interrupted, presumably TEST_ASSERT_EQUAL (expect_more_, zmq_msg_more (&msg)); if (address_) { const uint8_t *const data = static_cast<const uint8_t *> (zmq_msg_data (&msg)); const size_t size = zmq_msg_size (&msg); *address_ = static_cast<char *> (malloc (size + 1)); memcpy (*address_, data, size); (*address_)[size] = 0; } zmq_msg_close (&msg); return 0; } // Read one event off the monitor socket; return value and address // by reference, if not null, and event number by value. Returns -1 // in case of error. static int get_monitor_event_internal (void *monitor_, int *value_, char **address_, int recv_flag_) { // First frame in message contains event number and value zmq_msg_t msg; zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor_, recv_flag_) == -1) { TEST_ASSERT_FAILURE_ERRNO (EAGAIN, -1); return -1; // timed out or no message available } TEST_ASSERT_TRUE (zmq_msg_more (&msg)); uint8_t *data = static_cast<uint8_t *> (zmq_msg_data (&msg)); uint16_t event = *reinterpret_cast<uint16_t *> (data); if (value_) memcpy (value_, data + 2, sizeof (uint32_t)); // Second frame in message contains event address TEST_ASSERT_SUCCESS_ERRNO ( receive_monitor_address (monitor_, address_, false)); return event; } int get_monitor_event_with_timeout (void *monitor_, int *value_, char **address_, int timeout_) { int res; if (timeout_ == -1) { // process infinite timeout in small steps to allow the user // to see some information on the console int timeout_step = 250; int wait_time = 0; zmq_setsockopt (monitor_, ZMQ_RCVTIMEO, &timeout_step, sizeof (timeout_step)); while ( (res = get_monitor_event_internal (monitor_, value_, address_, 0)) == -1) { wait_time += timeout_step; fprintf (stderr, "Still waiting for monitor event after %i ms\n", wait_time); } } else { zmq_setsockopt (monitor_, ZMQ_RCVTIMEO, &timeout_, sizeof (timeout_)); res = get_monitor_event_internal (monitor_, value_, address_, 0); } int timeout_infinite = -1; zmq_setsockopt (monitor_, ZMQ_RCVTIMEO, &timeout_infinite, sizeof (timeout_infinite)); return res; } int get_monitor_event (void *monitor_, int *value_, char **address_) { return get_monitor_event_with_timeout (monitor_, value_, address_, -1); } void expect_monitor_event (void *monitor_, int expected_event_) { TEST_ASSERT_EQUAL_HEX (expected_event_, get_monitor_event (monitor_, NULL, NULL)); } static void print_unexpected_event (char *buf_, size_t buf_size_, int event_, int err_, int expected_event_, int expected_err_) { snprintf (buf_, buf_size_, "Unexpected event: 0x%x, value = %i/0x%x (expected: 0x%x, value " "= %i/0x%x)\n", event_, err_, err_, expected_event_, expected_err_, expected_err_); } void print_unexpected_event_stderr (int event_, int err_, int expected_event_, int expected_err_) { char buf[256]; print_unexpected_event (buf, sizeof buf, event_, err_, expected_event_, expected_err_); fputs (buf, stderr); } int expect_monitor_event_multiple (void *server_mon_, int expected_event_, int expected_err_, bool optional_) { int count_of_expected_events = 0; int client_closed_connection = 0; int timeout = 250; int wait_time = 0; int event; int err; while ((event = get_monitor_event_with_timeout (server_mon_, &err, NULL, timeout)) != -1 || !count_of_expected_events) { if (event == -1) { if (optional_) break; wait_time += timeout; fprintf (stderr, "Still waiting for first event after %ims (expected event " "%x (value %i/0x%x))\n", wait_time, expected_event_, expected_err_, expected_err_); continue; } // ignore errors with EPIPE/ECONNRESET/ECONNABORTED, which can happen // ECONNRESET can happen on very slow machines, when the engine writes // to the peer and then tries to read the socket before the peer reads // ECONNABORTED happens when a client aborts a connection via RST/timeout if (event == ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL && ((err == EPIPE && expected_err_ != EPIPE) || err == ECONNRESET || err == ECONNABORTED)) { fprintf (stderr, "Ignored event (skipping any further events): %x (err = " "%i == %s)\n", event, err, zmq_strerror (err)); client_closed_connection = 1; break; } if (event != expected_event_ || (-1 != expected_err_ && err != expected_err_)) { char buf[256]; print_unexpected_event (buf, sizeof buf, event, err, expected_event_, expected_err_); TEST_FAIL_MESSAGE (buf); } ++count_of_expected_events; } TEST_ASSERT_TRUE (optional_ || count_of_expected_events > 0 || client_closed_connection); return count_of_expected_events; } static int64_t get_monitor_event_internal_v2 (void *monitor_, uint64_t **value_, char **local_address_, char **remote_address_, int recv_flag_) { // First frame in message contains event number zmq_msg_t msg; zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor_, recv_flag_) == -1) { TEST_ASSERT_FAILURE_ERRNO (EAGAIN, -1); return -1; // timed out or no message available } TEST_ASSERT_TRUE (zmq_msg_more (&msg)); TEST_ASSERT_EQUAL_UINT (sizeof (uint64_t), zmq_msg_size (&msg)); uint64_t event; memcpy (&event, zmq_msg_data (&msg), sizeof (event)); zmq_msg_close (&msg); // Second frame in message contains the number of values zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor_, recv_flag_) == -1) { TEST_ASSERT_FAILURE_ERRNO (EAGAIN, -1); return -1; // timed out or no message available } TEST_ASSERT_TRUE (zmq_msg_more (&msg)); TEST_ASSERT_EQUAL_UINT (sizeof (uint64_t), zmq_msg_size (&msg)); uint64_t value_count; memcpy (&value_count, zmq_msg_data (&msg), sizeof (value_count)); zmq_msg_close (&msg); if (value_) { *value_ = (uint64_t *) malloc ((size_t) value_count * sizeof (uint64_t)); TEST_ASSERT_NOT_NULL (*value_); } for (uint64_t i = 0; i < value_count; ++i) { // Subsequent frames in message contain event values zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor_, recv_flag_) == -1) { TEST_ASSERT_FAILURE_ERRNO (EAGAIN, -1); return -1; // timed out or no message available } TEST_ASSERT_TRUE (zmq_msg_more (&msg)); TEST_ASSERT_EQUAL_UINT (sizeof (uint64_t), zmq_msg_size (&msg)); if (value_ && *value_) memcpy (&(*value_)[i], zmq_msg_data (&msg), sizeof (uint64_t)); zmq_msg_close (&msg); } // Second-to-last frame in message contains local address TEST_ASSERT_SUCCESS_ERRNO ( receive_monitor_address (monitor_, local_address_, true)); // Last frame in message contains remote address TEST_ASSERT_SUCCESS_ERRNO ( receive_monitor_address (monitor_, remote_address_, false)); return event; } static int64_t get_monitor_event_with_timeout_v2 (void *monitor_, uint64_t **value_, char **local_address_, char **remote_address_, int timeout_) { int64_t res; if (timeout_ == -1) { // process infinite timeout in small steps to allow the user // to see some information on the console int timeout_step = 250; int wait_time = 0; zmq_setsockopt (monitor_, ZMQ_RCVTIMEO, &timeout_step, sizeof (timeout_step)); while ((res = get_monitor_event_internal_v2 ( monitor_, value_, local_address_, remote_address_, 0)) == -1) { wait_time += timeout_step; fprintf (stderr, "Still waiting for monitor event after %i ms\n", wait_time); } } else { zmq_setsockopt (monitor_, ZMQ_RCVTIMEO, &timeout_, sizeof (timeout_)); res = get_monitor_event_internal_v2 (monitor_, value_, local_address_, remote_address_, 0); } int timeout_infinite = -1; zmq_setsockopt (monitor_, ZMQ_RCVTIMEO, &timeout_infinite, sizeof (timeout_infinite)); return res; } int64_t get_monitor_event_v2 (void *monitor_, uint64_t **value_, char **local_address_, char **remote_address_) { return get_monitor_event_with_timeout_v2 (monitor_, value_, local_address_, remote_address_, -1); } void expect_monitor_event_v2 (void *monitor_, int64_t expected_event_, const char *expected_local_address_, const char *expected_remote_address_) { char *local_address = NULL; char *remote_address = NULL; int64_t event = get_monitor_event_v2 ( monitor_, NULL, expected_local_address_ ? &local_address : NULL, expected_remote_address_ ? &remote_address : NULL); bool failed = false; char buf[256]; char *pos = buf; if (event != expected_event_) { pos += snprintf (pos, sizeof buf - (pos - buf), "Expected monitor event %llx, but received %llx\n", static_cast<long long> (expected_event_), static_cast<long long> (event)); failed = true; } if (expected_local_address_ && 0 != strcmp (local_address, expected_local_address_)) { pos += snprintf (pos, sizeof buf - (pos - buf), "Expected local address %s, but received %s\n", expected_local_address_, local_address); } if (expected_remote_address_ && 0 != strcmp (remote_address, expected_remote_address_)) { snprintf (pos, sizeof buf - (pos - buf), "Expected remote address %s, but received %s\n", expected_remote_address_, remote_address); } free (local_address); free (remote_address); TEST_ASSERT_FALSE_MESSAGE (failed, buf); } const char *get_zmqEventName (uint64_t event) { switch (event) { case ZMQ_EVENT_CONNECTED: return "CONNECTED"; case ZMQ_EVENT_CONNECT_DELAYED: return "CONNECT_DELAYED"; case ZMQ_EVENT_CONNECT_RETRIED: return "CONNECT_RETRIED"; case ZMQ_EVENT_LISTENING: return "LISTENING"; case ZMQ_EVENT_BIND_FAILED: return "BIND_FAILED"; case ZMQ_EVENT_ACCEPTED: return "ACCEPTED"; case ZMQ_EVENT_ACCEPT_FAILED: return "ACCEPT_FAILED"; case ZMQ_EVENT_CLOSED: return "CLOSED"; case ZMQ_EVENT_CLOSE_FAILED: return "CLOSE_FAILED"; case ZMQ_EVENT_DISCONNECTED: return "DISCONNECTED"; case ZMQ_EVENT_MONITOR_STOPPED: return "MONITOR_STOPPED"; case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL: return "HANDSHAKE_FAILED_NO_DETAIL"; case ZMQ_EVENT_HANDSHAKE_SUCCEEDED: return "HANDSHAKE_SUCCEEDED"; case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL: return "HANDSHAKE_FAILED_PROTOCOL"; case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH: return "HANDSHAKE_FAILED_AUTH"; default: return "UNKNOWN"; } } void print_events (void *socket, int timeout, int limit) { // print events received int value; char *event_address; int event = get_monitor_event_with_timeout (socket, &value, &event_address, timeout); int i = 0; ; while ((event != -1) && (++i < limit)) { const char *eventName = get_zmqEventName (event); printf ("Got event: %s\n", eventName); event = get_monitor_event_with_timeout (socket, &value, &event_address, timeout); } }
sophomore_public/libzmq
tests/testutil_monitoring.cpp
C++
gpl-3.0
13,947
/* SPDX-License-Identifier: MPL-2.0 */ #ifndef __TESTUTIL_MONITORING_HPP_INCLUDED__ #define __TESTUTIL_MONITORING_HPP_INCLUDED__ #include "../include/zmq.h" #include "../src/stdint.hpp" #include <stddef.h> // General, i.e. non-security specific, monitor utilities int get_monitor_event_with_timeout (void *monitor_, int *value_, char **address_, int timeout_); // Read one event off the monitor socket; return value and address // by reference, if not null, and event number by value. Returns -1 // in case of error. int get_monitor_event (void *monitor_, int *value_, char **address_); void expect_monitor_event (void *monitor_, int expected_event_); void print_unexpected_event_stderr (int event_, int err_, int expected_event_, int expected_err_); // expects that one or more occurrences of the expected event are received // via the specified socket monitor // returns the number of occurrences of the expected event // interrupts, if a ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL with EPIPE, ECONNRESET // or ECONNABORTED occurs; in this case, 0 is returned // this should be investigated further, see // https://github.com/zeromq/libzmq/issues/2644 int expect_monitor_event_multiple (void *server_mon_, int expected_event_, int expected_err_ = -1, bool optional_ = false); int64_t get_monitor_event_v2 (void *monitor_, uint64_t **value_, char **local_address_, char **remote_address_); void expect_monitor_event_v2 (void *monitor_, int64_t expected_event_, const char *expected_local_address_ = NULL, const char *expected_remote_address_ = NULL); const char *get_zmqEventName (uint64_t event); void print_events (void *socket, int timeout, int limit); #endif
sophomore_public/libzmq
tests/testutil_monitoring.hpp
C++
gpl-3.0
2,184
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil_security.hpp" #include <stdlib.h> #include <string.h> const char *test_zap_domain = "ZAPTEST"; void socket_config_null_client (void *server_, void *server_secret_) { LIBZMQ_UNUSED (server_); LIBZMQ_UNUSED (server_secret_); } void socket_config_null_server (void *server_, void *server_secret_) { TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( server_, ZMQ_ZAP_DOMAIN, test_zap_domain, strlen (test_zap_domain))); #ifdef ZMQ_ZAP_ENFORCE_DOMAIN int required = server_secret_ ? *static_cast<int *> (server_secret_) : 0; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (server_, ZMQ_ZAP_ENFORCE_DOMAIN, &required, sizeof (int))); #else LIBZMQ_UNUSED (server_secret_); #endif } static const char test_plain_username[] = "testuser"; static const char test_plain_password[] = "testpass"; void socket_config_plain_client (void *server_, void *server_secret_) { LIBZMQ_UNUSED (server_secret_); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server_, ZMQ_PLAIN_PASSWORD, test_plain_password, 8)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server_, ZMQ_PLAIN_USERNAME, test_plain_username, 8)); } void socket_config_plain_server (void *server_, void *server_secret_) { LIBZMQ_UNUSED (server_secret_); int as_server = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server_, ZMQ_PLAIN_SERVER, &as_server, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( server_, ZMQ_ZAP_DOMAIN, test_zap_domain, strlen (test_zap_domain))); } char valid_client_public[41]; char valid_client_secret[41]; char valid_server_public[41]; char valid_server_secret[41]; void setup_testutil_security_curve () { // Generate new keypairs for these tests TEST_ASSERT_SUCCESS_ERRNO ( zmq_curve_keypair (valid_client_public, valid_client_secret)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_curve_keypair (valid_server_public, valid_server_secret)); } void socket_config_curve_server (void *server_, void *server_secret_) { int as_server = 1; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server_, ZMQ_CURVE_SERVER, &as_server, sizeof (int))); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (server_, ZMQ_CURVE_SECRETKEY, server_secret_, 41)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( server_, ZMQ_ZAP_DOMAIN, test_zap_domain, strlen (test_zap_domain))); #ifdef ZMQ_ZAP_ENFORCE_DOMAIN int required = 1; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (server_, ZMQ_ZAP_ENFORCE_DOMAIN, &required, sizeof (int))); #endif } void socket_config_curve_client (void *client_, void *data_) { const curve_client_data_t *const curve_client_data = static_cast<const curve_client_data_t *> (data_); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( client_, ZMQ_CURVE_SERVERKEY, curve_client_data->server_public, 41)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( client_, ZMQ_CURVE_PUBLICKEY, curve_client_data->client_public, 41)); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( client_, ZMQ_CURVE_SECRETKEY, curve_client_data->client_secret, 41)); } void *zap_requests_handled; void zap_handler_generic (zap_protocol_t zap_protocol_, const char *expected_routing_id_) { void *control = zmq_socket (get_test_context (), ZMQ_REQ); TEST_ASSERT_NOT_NULL (control); TEST_ASSERT_SUCCESS_ERRNO ( zmq_connect (control, "inproc://handler-control")); void *handler = zmq_socket (get_test_context (), ZMQ_REP); TEST_ASSERT_NOT_NULL (handler); TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (handler, "inproc://zeromq.zap.01")); // Signal main thread that we are ready send_string_expect_success (control, "GO", 0); zmq_pollitem_t items[] = { {control, 0, ZMQ_POLLIN, 0}, {handler, 0, ZMQ_POLLIN, 0}, }; // if ordered not to receive the request, ignore the second poll item const int numitems = (zap_protocol_ == zap_do_not_recv) ? 1 : 2; // Process ZAP requests forever while (zmq_poll (items, numitems, -1) >= 0) { if (items[0].revents & ZMQ_POLLIN) { recv_string_expect_success (control, "STOP", 0); break; // Terminating - main thread signal } if (!(items[1].revents & ZMQ_POLLIN)) continue; char *version = s_recv (handler); if (!version) break; // Terminating - peer's socket closed if (zap_protocol_ == zap_disconnect) { free (version); break; } char *sequence = s_recv (handler); char *domain = s_recv (handler); char *address = s_recv (handler); char *routing_id = s_recv (handler); char *mechanism = s_recv (handler); bool authentication_succeeded = false; if (streq (mechanism, "CURVE")) { uint8_t client_key[32]; TEST_ASSERT_EQUAL_INT (32, TEST_ASSERT_SUCCESS_ERRNO (zmq_recv ( handler, client_key, 32, 0))); char client_key_text[41]; zmq_z85_encode (client_key_text, client_key, 32); authentication_succeeded = streq (client_key_text, valid_client_public); } else if (streq (mechanism, "PLAIN")) { char client_username[32]; int size = TEST_ASSERT_SUCCESS_ERRNO ( zmq_recv (handler, client_username, 32, 0)); client_username[size] = 0; char client_password[32]; size = TEST_ASSERT_SUCCESS_ERRNO ( zmq_recv (handler, client_password, 32, 0)); client_password[size] = 0; authentication_succeeded = streq (test_plain_username, client_username) && streq (test_plain_password, client_password); } else if (streq (mechanism, "NULL")) { authentication_succeeded = true; } else { char msg[128]; printf ("Unsupported mechanism: %s\n", mechanism); TEST_FAIL_MESSAGE (msg); } TEST_ASSERT_EQUAL_STRING ("1.0", version); TEST_ASSERT_EQUAL_STRING (expected_routing_id_, routing_id); send_string_expect_success ( handler, zap_protocol_ == zap_wrong_version ? "invalid_version" : version, ZMQ_SNDMORE); send_string_expect_success (handler, zap_protocol_ == zap_wrong_request_id ? "invalid_request_id" : sequence, ZMQ_SNDMORE); if (authentication_succeeded) { const char *status_code; switch (zap_protocol_) { case zap_status_internal_error: status_code = "500"; break; case zap_status_temporary_failure: status_code = "300"; break; case zap_status_invalid: status_code = "invalid_status"; break; default: status_code = "200"; } send_string_expect_success (handler, status_code, ZMQ_SNDMORE); send_string_expect_success (handler, "OK", ZMQ_SNDMORE); send_string_expect_success (handler, "anonymous", ZMQ_SNDMORE); if (zap_protocol_ == zap_too_many_parts) { send_string_expect_success (handler, "", ZMQ_SNDMORE); } if (zap_protocol_ != zap_do_not_send) send_string_expect_success (handler, "", 0); } else { send_string_expect_success (handler, "400", ZMQ_SNDMORE); send_string_expect_success (handler, "Invalid client public key", ZMQ_SNDMORE); send_string_expect_success (handler, "", ZMQ_SNDMORE); if (zap_protocol_ != zap_do_not_send) send_string_expect_success (handler, "", 0); } free (version); free (sequence); free (domain); free (address); free (routing_id); free (mechanism); zmq_atomic_counter_inc (zap_requests_handled); } TEST_ASSERT_SUCCESS_ERRNO (zmq_unbind (handler, "inproc://zeromq.zap.01")); close_zero_linger (handler); if (zap_protocol_ != zap_disconnect) { send_string_expect_success (control, "STOPPED", 0); } close_zero_linger (control); } void zap_handler (void *) { zap_handler_generic (zap_ok); } static void setup_handshake_socket_monitor (void *server_, void **server_mon_, const char *monitor_endpoint_) { // Monitor handshake events on the server TEST_ASSERT_SUCCESS_ERRNO (zmq_socket_monitor ( server_, monitor_endpoint_, ZMQ_EVENT_HANDSHAKE_SUCCEEDED | ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL | ZMQ_EVENT_HANDSHAKE_FAILED_AUTH | ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL)); // Create socket for collecting monitor events *server_mon_ = test_context_socket (ZMQ_PAIR); int linger = 0; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (*server_mon_, ZMQ_LINGER, &linger, sizeof (linger))); // Connect it to the inproc endpoints so they'll get events TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (*server_mon_, monitor_endpoint_)); } void setup_context_and_server_side (void **zap_control_, void **zap_thread_, void **server_, void **server_mon_, char *my_endpoint_, zmq_thread_fn zap_handler_, socket_config_fn socket_config_, void *socket_config_data_, const char *routing_id_) { // Spawn ZAP handler zap_requests_handled = zmq_atomic_counter_new (); TEST_ASSERT_NOT_NULL (zap_requests_handled); *zap_control_ = test_context_socket (ZMQ_REP); TEST_ASSERT_SUCCESS_ERRNO ( zmq_bind (*zap_control_, "inproc://handler-control")); int linger = 0; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (*zap_control_, ZMQ_LINGER, &linger, sizeof (linger))); if (zap_handler_ != NULL) { *zap_thread_ = zmq_threadstart (zap_handler_, NULL); recv_string_expect_success (*zap_control_, "GO", 0); } else *zap_thread_ = NULL; // Server socket will accept connections *server_ = test_context_socket (ZMQ_DEALER); TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (*server_, ZMQ_LINGER, &linger, sizeof (linger))); // As per API by default there's no limit to the size of a message, // but the sanitizer allocator will barf over a gig or so int64_t max_msg_size = 64 * 1024 * 1024; TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( *server_, ZMQ_MAXMSGSIZE, &max_msg_size, sizeof (int64_t))); socket_config_ (*server_, socket_config_data_); TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt ( *server_, ZMQ_ROUTING_ID, routing_id_, strlen (routing_id_))); bind_loopback_ipv4 (*server_, my_endpoint_, MAX_SOCKET_STRING); const char server_monitor_endpoint[] = "inproc://monitor-server"; setup_handshake_socket_monitor (*server_, server_mon_, server_monitor_endpoint); } void shutdown_context_and_server_side (void *zap_thread_, void *server_, void *server_mon_, void *zap_control_, bool zap_handler_stopped_) { if (zap_thread_ && !zap_handler_stopped_) { send_string_expect_success (zap_control_, "STOP", 0); recv_string_expect_success (zap_control_, "STOPPED", 0); TEST_ASSERT_SUCCESS_ERRNO ( zmq_unbind (zap_control_, "inproc://handler-control")); } test_context_socket_close (zap_control_); zmq_socket_monitor (server_, NULL, 0); test_context_socket_close (server_mon_); test_context_socket_close (server_); // Wait until ZAP handler terminates if (zap_thread_) zmq_threadclose (zap_thread_); zmq_atomic_counter_destroy (&zap_requests_handled); } void *create_and_connect_client (char *my_endpoint_, socket_config_fn socket_config_, void *socket_config_data_, void **client_mon_) { void *client = test_context_socket (ZMQ_DEALER); // As per API by default there's no limit to the size of a message, // but the sanitizer allocator will barf over a gig or so int64_t max_msg_size = 64 * 1024 * 1024; TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (client, ZMQ_MAXMSGSIZE, &max_msg_size, sizeof (int64_t))); socket_config_ (client, socket_config_data_); TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (client, my_endpoint_)); if (client_mon_) { setup_handshake_socket_monitor (client, client_mon_, "inproc://client-monitor"); } return client; } void expect_new_client_bounce_fail (char *my_endpoint_, void *server_, socket_config_fn socket_config_, void *socket_config_data_, void **client_mon_, int expected_client_event_, int expected_client_value_) { void *my_client_mon = NULL; TEST_ASSERT_TRUE (client_mon_ == NULL || expected_client_event_ == 0); if (expected_client_event_ != 0) client_mon_ = &my_client_mon; void *client = create_and_connect_client (my_endpoint_, socket_config_, socket_config_data_, client_mon_); expect_bounce_fail (server_, client); if (expected_client_event_ != 0) { int events_received = 0; events_received = expect_monitor_event_multiple ( my_client_mon, expected_client_event_, expected_client_value_, false); TEST_ASSERT_EQUAL_INT (1, events_received); test_context_socket_close (my_client_mon); } test_context_socket_close_zero_linger (client); }
sophomore_public/libzmq
tests/testutil_security.cpp
C++
gpl-3.0
14,617
/* SPDX-License-Identifier: MPL-2.0 */ #ifndef __TESTUTIL_SECURITY_HPP_INCLUDED__ #define __TESTUTIL_SECURITY_HPP_INCLUDED__ #include "testutil_unity.hpp" #include "testutil_monitoring.hpp" // security test utils typedef void (socket_config_fn) (void *, void *); // NULL specific functions void socket_config_null_client (void *server_, void *server_secret_); void socket_config_null_server (void *server_, void *server_secret_); // PLAIN specific functions void socket_config_plain_client (void *server_, void *server_secret_); void socket_config_plain_server (void *server_, void *server_secret_); // CURVE specific functions // We'll generate random test keys at startup extern char valid_client_public[41]; extern char valid_client_secret[41]; extern char valid_server_public[41]; extern char valid_server_secret[41]; void setup_testutil_security_curve (); void socket_config_curve_server (void *server_, void *server_secret_); struct curve_client_data_t { const char *server_public; const char *client_public; const char *client_secret; }; void socket_config_curve_client (void *client_, void *data_); // -------------------------------------------------------------------------- // This methods receives and validates ZAP requests (allowing or denying // each client connection). enum zap_protocol_t { zap_ok, // ZAP-compliant non-standard cases zap_status_temporary_failure, zap_status_internal_error, // ZAP protocol errors zap_wrong_version, zap_wrong_request_id, zap_status_invalid, zap_too_many_parts, zap_disconnect, zap_do_not_recv, zap_do_not_send }; extern void *zap_requests_handled; void zap_handler_generic (zap_protocol_t zap_protocol_, const char *expected_routing_id_ = "IDENT"); void zap_handler (void * /*unused_*/); // Security-specific monitor event utilities // assert_* are macros rather than functions, to allow assertion failures be // attributed to the causing source code line #define assert_no_more_monitor_events_with_timeout(monitor, timeout) \ { \ int event_count = 0; \ int event, err; \ while ((event = get_monitor_event_with_timeout ((monitor), &err, NULL, \ (timeout))) \ != -1) { \ if (event == ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL \ && (err == EPIPE || err == ECONNRESET \ || err == ECONNABORTED)) { \ fprintf (stderr, \ "Ignored event (skipping any further events): %x " \ "(err = %i == %s)\n", \ event, err, zmq_strerror (err)); \ continue; \ } \ ++event_count; \ /* TODO write this into a buffer and attach to the assertion msg below */ \ print_unexpected_event_stderr (event, err, 0, 0); \ } \ TEST_ASSERT_EQUAL_INT (0, event_count); \ } void setup_context_and_server_side ( void **zap_control_, void **zap_thread_, void **server_, void **server_mon_, char *my_endpoint_, zmq_thread_fn zap_handler_ = &zap_handler, socket_config_fn socket_config_ = &socket_config_curve_server, void *socket_config_data_ = valid_server_secret, const char *routing_id_ = "IDENT"); void shutdown_context_and_server_side (void *zap_thread_, void *server_, void *server_mon_, void *zap_control_, bool zap_handler_stopped_ = false); void *create_and_connect_client (char *my_endpoint_, socket_config_fn socket_config_, void *socket_config_data_, void **client_mon_ = NULL); void expect_new_client_bounce_fail (char *my_endpoint_, void *server_, socket_config_fn socket_config_, void *socket_config_data_, void **client_mon_ = NULL, int expected_client_event_ = 0, int expected_client_value_ = 0); #endif
sophomore_public/libzmq
tests/testutil_security.hpp
C++
gpl-3.0
5,216
/* SPDX-License-Identifier: MPL-2.0 */ #include "testutil_unity.hpp" #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <direct.h> #else #include <unistd.h> #endif int test_assert_success_message_errno_helper (int rc_, const char *msg_, const char *expr_, int line_) { if (rc_ == -1) { char buffer[512]; buffer[sizeof (buffer) - 1] = 0; // to ensure defined behavior with VC++ <= 2013 snprintf (buffer, sizeof (buffer) - 1, "%s failed%s%s%s, errno = %i (%s)", expr_, msg_ ? " (additional info: " : "", msg_ ? msg_ : "", msg_ ? ")" : "", zmq_errno (), zmq_strerror (zmq_errno ())); UNITY_TEST_FAIL (line_, buffer); } return rc_; } int test_assert_success_message_raw_errno_helper ( int rc_, const char *msg_, const char *expr_, int line_, bool zero) { if (rc_ == -1 || (zero && rc_ != 0)) { #if defined ZMQ_HAVE_WINDOWS int current_errno = WSAGetLastError (); #else int current_errno = errno; #endif char buffer[512]; buffer[sizeof (buffer) - 1] = 0; // to ensure defined behavior with VC++ <= 2013 snprintf ( buffer, sizeof (buffer) - 1, "%s failed%s%s%s with %d, errno = %i/%s", expr_, msg_ ? " (additional info: " : "", msg_ ? msg_ : "", msg_ ? ")" : "", rc_, current_errno, strerror (current_errno)); UNITY_TEST_FAIL (line_, buffer); } return rc_; } int test_assert_success_message_raw_zero_errno_helper (int rc_, const char *msg_, const char *expr_, int line_) { return test_assert_success_message_raw_errno_helper (rc_, msg_, expr_, line_, true); } int test_assert_failure_message_raw_errno_helper ( int rc_, int expected_errno_, const char *msg_, const char *expr_, int line_) { char buffer[512]; buffer[sizeof (buffer) - 1] = 0; // to ensure defined behavior with VC++ <= 2013 if (rc_ != -1) { snprintf (buffer, sizeof (buffer) - 1, "%s was unexpectedly successful%s%s%s, expected " "errno = %i, actual return value = %i", expr_, msg_ ? " (additional info: " : "", msg_ ? msg_ : "", msg_ ? ")" : "", expected_errno_, rc_); UNITY_TEST_FAIL (line_, buffer); } else { #if defined ZMQ_HAVE_WINDOWS int current_errno = WSAGetLastError (); #else int current_errno = errno; #endif if (current_errno != expected_errno_) { snprintf (buffer, sizeof (buffer) - 1, "%s failed with an unexpected error%s%s%s, expected " "errno = %i, actual errno = %i", expr_, msg_ ? " (additional info: " : "", msg_ ? msg_ : "", msg_ ? ")" : "", expected_errno_, current_errno); UNITY_TEST_FAIL (line_, buffer); } } return rc_; } void send_string_expect_success (void *socket_, const char *str_, int flags_) { const size_t len = str_ ? strlen (str_) : 0; const int rc = zmq_send (socket_, str_, len, flags_); TEST_ASSERT_EQUAL_INT ((int) len, rc); } void recv_string_expect_success (void *socket_, const char *str_, int flags_) { const size_t len = str_ ? strlen (str_) : 0; char buffer[255]; TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (sizeof (buffer), len, "recv_string_expect_success cannot be " "used for strings longer than 255 " "characters"); const int rc = TEST_ASSERT_SUCCESS_ERRNO ( zmq_recv (socket_, buffer, sizeof (buffer), flags_)); TEST_ASSERT_EQUAL_INT ((int) len, rc); if (str_) TEST_ASSERT_EQUAL_STRING_LEN (str_, buffer, len); } static void *internal_manage_test_context (bool init_, bool clear_) { static void *test_context = NULL; if (clear_) { TEST_ASSERT_NOT_NULL (test_context); TEST_ASSERT_SUCCESS_ERRNO (zmq_ctx_term (test_context)); test_context = NULL; } else { if (init_) { TEST_ASSERT_NULL (test_context); test_context = zmq_ctx_new (); TEST_ASSERT_NOT_NULL (test_context); } } return test_context; } static void internal_manage_test_sockets (void *socket_, bool add_) { static void *test_sockets[MAX_TEST_SOCKETS]; static size_t test_socket_count = 0; if (!socket_) { TEST_ASSERT_FALSE (add_); // force-close all sockets if (test_socket_count) { for (size_t i = 0; i < test_socket_count; ++i) { close_zero_linger (test_sockets[i]); } fprintf (stderr, "WARNING: Forced closure of %i sockets, this is an " "implementation error unless the test case failed\n", static_cast<int> (test_socket_count)); test_socket_count = 0; } } else { if (add_) { ++test_socket_count; TEST_ASSERT_LESS_THAN_MESSAGE (MAX_TEST_SOCKETS, test_socket_count, "MAX_TEST_SOCKETS must be " "increased, or you cannot use the " "test context"); test_sockets[test_socket_count - 1] = socket_; } else { bool found = false; for (size_t i = 0; i < test_socket_count; ++i) { if (test_sockets[i] == socket_) { found = true; } if (found) { if (i < test_socket_count) test_sockets[i] = test_sockets[i + 1]; } } TEST_ASSERT_TRUE_MESSAGE (found, "Attempted to close a socket that was " "not created by test_context_socket"); --test_socket_count; } } } void setup_test_context () { internal_manage_test_context (true, false); } void *get_test_context () { return internal_manage_test_context (false, false); } void teardown_test_context () { // this condition allows an explicit call to teardown_test_context from a // test. if this is never used, it should probably be removed, to detect // misuses if (get_test_context ()) { internal_manage_test_sockets (NULL, false); internal_manage_test_context (false, true); } } void *test_context_socket (int type_) { void *const socket = zmq_socket (get_test_context (), type_); TEST_ASSERT_NOT_NULL (socket); internal_manage_test_sockets (socket, true); return socket; } void *test_context_socket_close (void *socket_) { TEST_ASSERT_SUCCESS_ERRNO (zmq_close (socket_)); internal_manage_test_sockets (socket_, false); return socket_; } void *test_context_socket_close_zero_linger (void *socket_) { const int linger = 0; int rc = zmq_setsockopt (socket_, ZMQ_LINGER, &linger, sizeof (linger)); TEST_ASSERT_TRUE (rc == 0 || zmq_errno () == ETERM); return test_context_socket_close (socket_); } void test_bind (void *socket_, const char *bind_address_, char *my_endpoint_, size_t len_) { TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (socket_, bind_address_)); TEST_ASSERT_SUCCESS_ERRNO ( zmq_getsockopt (socket_, ZMQ_LAST_ENDPOINT, my_endpoint_, &len_)); } void bind_loopback (void *socket_, int ipv6_, char *my_endpoint_, size_t len_) { if (ipv6_ && !is_ipv6_available ()) { TEST_IGNORE_MESSAGE ("ipv6 is not available"); } TEST_ASSERT_SUCCESS_ERRNO ( zmq_setsockopt (socket_, ZMQ_IPV6, &ipv6_, sizeof (int))); test_bind (socket_, ipv6_ ? "tcp://[::1]:*" : "tcp://127.0.0.1:*", my_endpoint_, len_); } void bind_loopback_ipv4 (void *socket_, char *my_endpoint_, size_t len_) { bind_loopback (socket_, false, my_endpoint_, len_); } void bind_loopback_ipv6 (void *socket_, char *my_endpoint_, size_t len_) { bind_loopback (socket_, true, my_endpoint_, len_); } void bind_loopback_ipc (void *socket_, char *my_endpoint_, size_t len_) { if (!zmq_has ("ipc")) { TEST_IGNORE_MESSAGE ("ipc is not available"); } test_bind (socket_, "ipc://*", my_endpoint_, len_); } void bind_loopback_tipc (void *socket_, char *my_endpoint_, size_t len_) { if (!is_tipc_available ()) { TEST_IGNORE_MESSAGE ("tipc is not available"); } test_bind (socket_, "tipc://<*>", my_endpoint_, len_); } #if defined(ZMQ_HAVE_IPC) void make_random_ipc_endpoint (char *out_endpoint_) { #ifdef ZMQ_HAVE_WINDOWS char random_file[MAX_PATH]; { const errno_t rc = tmpnam_s (random_file); TEST_ASSERT_EQUAL (0, rc); } // TODO or use CreateDirectoryA and specify permissions? const int rc = _mkdir (random_file); TEST_ASSERT_EQUAL (0, rc); strcat (random_file, "/ipc"); #else char random_file[16]; strcpy (random_file, "tmpXXXXXX"); #ifdef HAVE_MKDTEMP TEST_ASSERT_TRUE (mkdtemp (random_file)); strcat (random_file, "/ipc"); #else int fd = mkstemp (random_file); TEST_ASSERT_TRUE (fd != -1); close (fd); #endif #endif strcpy (out_endpoint_, "ipc://"); strcat (out_endpoint_, random_file); } #endif
sophomore_public/libzmq
tests/testutil_unity.cpp
C++
gpl-3.0
9,767
#pragma once /* SPDX-License-Identifier: MPL-2.0 */ #include "../include/zmq.h" #include "testutil.hpp" #include <unity.h> // Internal helper functions that are not intended to be directly called from // tests. They must be declared in the header since they are used by macros. int test_assert_success_message_errno_helper (int rc_, const char *msg_, const char *expr_, int line); int test_assert_success_message_raw_errno_helper ( int rc_, const char *msg_, const char *expr_, int line, bool zero_ = false); int test_assert_success_message_raw_zero_errno_helper (int rc_, const char *msg_, const char *expr_, int line); int test_assert_failure_message_raw_errno_helper ( int rc_, int expected_errno_, const char *msg_, const char *expr_, int line); ///////////////////////////////////////////////////////////////////////////// // Macros extending Unity's TEST_ASSERT_* macros in a similar fashion. ///////////////////////////////////////////////////////////////////////////// // For TEST_ASSERT_SUCCESS_ERRNO, TEST_ASSERT_SUCCESS_MESSAGE_ERRNO and // TEST_ASSERT_FAILURE_ERRNO, 'expr' must be an expression evaluating // to a result in the style of a libzmq API function, i.e. an integer which // is non-negative in case of success, and -1 in case of a failure, and sets // the value returned by zmq_errno () to the error code. // TEST_ASSERT_SUCCESS_RAW_ERRNO and TEST_ASSERT_FAILURE_RAW_ERRNO are similar, // but used with the native socket API functions, and expect that the error // code can be retrieved in the native way (i.e. WSAGetLastError on Windows, // and errno otherwise). // Asserts that the libzmq API 'expr' is successful. In case of a failure, the // assertion message includes the literal 'expr', the error number as // determined by zmq_errno(), and the additional 'msg'. // In case of success, the result of the macro is the result of 'expr'. #define TEST_ASSERT_SUCCESS_MESSAGE_ERRNO(expr, msg) \ test_assert_success_message_errno_helper (expr, msg, #expr, __LINE__) // Asserts that the libzmq API 'expr' is successful. In case of a failure, the // assertion message includes the literal 'expr' and the error code. // A typical use would be: // TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (socket, endpoint)); // In case of success, the result of the macro is the result of 'expr'. // // If an additional message should be displayed in case of a failure, use // TEST_ASSERT_SUCCESS_MESSAGE_ERRNO. #define TEST_ASSERT_SUCCESS_ERRNO(expr) \ test_assert_success_message_errno_helper (expr, NULL, #expr, __LINE__) // Asserts that the socket API 'expr' is successful. In case of a failure, the // assertion message includes the literal 'expr' and the error code. // A typical use would be: // TEST_ASSERT_SUCCESS_RAW_ERRNO (send (fd, buffer, 64, 0)); // In case of success, the result of the macro is the result of 'expr'. // Success is strictly defined by a return value different from -1, as opposed // to checking that it is 0, like TEST_ASSERT_FAILURE_RAW_ZERO_ERRNO does. #define TEST_ASSERT_SUCCESS_RAW_ERRNO(expr) \ test_assert_success_message_raw_errno_helper (expr, NULL, #expr, __LINE__) // Asserts that the socket API 'expr' is successful. In case of a failure, the // assertion message includes the literal 'expr' and the error code. // A typical use would be: // TEST_ASSERT_SUCCESS_RAW_ZERO_ERRNO (send (fd, buffer, 64, 0)); // In case of success, the result of the macro is the result of 'expr'. // Success is strictly defined by a return value of 0, as opposed to checking // that it is not -1, like TEST_ASSERT_FAILURE_RAW_ERRNO does. #define TEST_ASSERT_SUCCESS_RAW_ZERO_ERRNO(expr) \ test_assert_success_message_raw_zero_errno_helper (expr, NULL, #expr, \ __LINE__) // Asserts that the socket API 'expr' is not successful, and the error code is // 'error_code'. In case of an unexpected succces, or a failure with an // unexpected error code, the assertion message includes the literal 'expr' // and, in case of a failure, the actual error code. #define TEST_ASSERT_FAILURE_RAW_ERRNO(error_code, expr) \ test_assert_failure_message_raw_errno_helper (expr, error_code, NULL, \ #expr, __LINE__) // Asserts that the libzmq API 'expr' is not successful, and the error code is // 'error_code'. In case of an unexpected succces, or a failure with an // unexpected error code, the assertion message includes the literal 'expr' // and, in case of a failure, the actual error code. #define TEST_ASSERT_FAILURE_ERRNO(error_code, expr) \ { \ int _rc = (expr); \ TEST_ASSERT_EQUAL_INT (-1, _rc); \ TEST_ASSERT_EQUAL_INT (error_code, errno); \ } ///////////////////////////////////////////////////////////////////////////// // Utility functions for testing sending and receiving. ///////////////////////////////////////////////////////////////////////////// // Sends a string via a libzmq socket, and expects the operation to be // successful (the meaning of which depends on the socket type and configured // options, and might include dropping the message). Otherwise, a Unity test // assertion is triggered. // 'socket_' must be the libzmq socket to use for sending. // 'str_' must be a 0-terminated string. // 'flags_' are as documented by the zmq_send function. void send_string_expect_success (void *socket_, const char *str_, int flags_); // Receives a message via a libzmq socket, and expects the operation to be // successful, and the message to be a given string. Otherwise, a Unity test // assertion is triggered. // 'socket_' must be the libzmq socket to use for receiving. // 'str_' must be a 0-terminated string. // 'flags_' are as documented by the zmq_recv function. void recv_string_expect_success (void *socket_, const char *str_, int flags_); // Sends a byte array via a libzmq socket, and expects the operation to be // successful (the meaning of which depends on the socket type and configured // options, and might include dropping the message). Otherwise, a Unity test // assertion is triggered. // 'socket_' must be the libzmq socket to use for sending. // 'array_' must be a C uint8_t array. The array size is automatically // determined via template argument deduction. // 'flags_' are as documented by the zmq_send function. template <size_t SIZE> void send_array_expect_success (void *socket_, const uint8_t (&array_)[SIZE], int flags_) { const int rc = zmq_send (socket_, array_, SIZE, flags_); TEST_ASSERT_EQUAL_INT (static_cast<int> (SIZE), rc); } // Receives a message via a libzmq socket, and expects the operation to be // successful, and the message to be a given byte array. Otherwise, a Unity // test assertion is triggered. // 'socket_' must be the libzmq socket to use for receiving. // 'array_' must be a C uint8_t array. The array size is automatically // determined via template argument deduction. // 'flags_' are as documented by the zmq_recv function. template <size_t SIZE> void recv_array_expect_success (void *socket_, const uint8_t (&array_)[SIZE], int flags_) { char buffer[255]; TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (sizeof (buffer), SIZE, "recv_string_expect_success cannot be " "used for strings longer than 255 " "characters"); const int rc = TEST_ASSERT_SUCCESS_ERRNO ( zmq_recv (socket_, buffer, sizeof (buffer), flags_)); TEST_ASSERT_EQUAL_INT (static_cast<int> (SIZE), rc); TEST_ASSERT_EQUAL_UINT8_ARRAY (array_, buffer, SIZE); } ///////////////////////////////////////////////////////////////////////////// // Utility function for handling a test libzmq context, that is set up and // torn down for each Unity test case, such that a clean context is available // for each test case, and some consistency checks can be performed. ///////////////////////////////////////////////////////////////////////////// // Use this is an test executable to perform a default setup and teardown of // the test context, which is appropriate for many libzmq test cases. #define SETUP_TEARDOWN_TESTCONTEXT \ void setUp () \ { \ setup_test_context (); \ } \ void tearDown () \ { \ teardown_test_context (); \ } // The maximum number of sockets that can be managed by the test context. #define MAX_TEST_SOCKETS 128 // Expected to be called during Unity's setUp function. void setup_test_context (); // Returns the test context, e.g. to create sockets in another thread using // zmq_socket, or set context options. void *get_test_context (); // Expected to be called during Unity's tearDown function. Checks that all // sockets created via test_context_socket have been properly closed using // test_context_socket_close or test_context_socket_close_zero_linger, and generates a warning otherwise. void teardown_test_context (); // Creates a libzmq socket on the test context, and tracks its lifecycle. // You MUST use test_context_socket_close or test_context_socket_close_zero_linger // to close a socket created via this function, otherwise undefined behaviour // will result. // CAUTION: this function is not thread-safe, and may only be used from the // main thread. void *test_context_socket (int type_); // Closes a socket created via test_context_socket. // CAUTION: this function is not thread-safe, and may only be used from the // main thread. void *test_context_socket_close (void *socket_); // Closes a socket created via test_context_socket after setting its linger // timeout to 0. // CAUTION: this function is not thread-safe, and may only be used from the // main thread. void *test_context_socket_close_zero_linger (void *socket_); ///////////////////////////////////////////////////////////////////////////// // Utility function for handling wildcard binds. ///////////////////////////////////////////////////////////////////////////// // All function binds a socket to some wildcard address, and retrieve the bound // endpoint via the ZMQ_LAST_ENDPOINT socket option to a given buffer. // Triggers a Unity test assertion in case of a failure (including the buffer // being too small for the resulting endpoint string). // Binds to an explicitly given (wildcard) address. // TODO redesign such that this function is not necessary to be exposed, but // the protocol to use is rather specified via an enum value void test_bind (void *socket_, const char *bind_address_, char *my_endpoint_, size_t len_); // Binds to a tcp endpoint using the ipv4 or ipv6 loopback wildcard address. void bind_loopback (void *socket_, int ipv6_, char *my_endpoint_, size_t len_); typedef void (*bind_function_t) (void *socket_, char *my_endpoint_, size_t len_); // Binds to a tcp endpoint using the ipv4 loopback wildcard address. void bind_loopback_ipv4 (void *socket_, char *my_endpoint_, size_t len_); // Binds to a tcp endpoint using the ipv6 loopback wildcard address. void bind_loopback_ipv6 (void *socket_, char *my_endpoint_, size_t len_); // Binds to an ipc endpoint using the ipc wildcard address. // Note that the returned address cannot be reused to bind a second socket. // If you need to do this, use make_random_ipc_endpoint instead. void bind_loopback_ipc (void *socket_, char *my_endpoint_, size_t len_); // Binds to an ipc endpoint using the tipc wildcard address. void bind_loopback_tipc (void *socket_, char *my_endpoint_, size_t len_); #if defined(ZMQ_HAVE_IPC) // utility function to create a random IPC endpoint, similar to what a ipc://* // wildcard binding does, but in a way it can be reused for multiple binds // TODO also add a len parameter here void make_random_ipc_endpoint (char *out_endpoint_); #endif
sophomore_public/libzmq
tests/testutil_unity.hpp
C++
gpl-3.0
13,189
/* SPDX-License-Identifier: MPL-2.0 */ #include <stdlib.h> #include <assert.h> #include <zmq.h> int main (void) { puts ("This tool generates a CurveZMQ keypair, as two printable strings " "you can"); puts ("use in configuration files or source code. The encoding uses Z85, " "which"); puts ( "is a base-85 format that is described in 0MQ RFC 32, and which has an"); puts ("implementation in the z85_codec.h source used by this tool. The " "keypair"); puts ( "always works with the secret key held by one party and the public key"); puts ("distributed (securely!) to peers wishing to connect to it."); char public_key[41]; char secret_key[41]; if (zmq_curve_keypair (public_key, secret_key)) { if (zmq_errno () == ENOTSUP) puts ("To use curve_keygen, please install libsodium and then " "rebuild libzmq."); exit (1); } puts ("\n== CURVE PUBLIC KEY =="); puts (public_key); puts ("\n== CURVE SECRET KEY =="); puts (secret_key); exit (0); }
sophomore_public/libzmq
tools/curve_keygen.cpp
C++
gpl-3.0
1,092
# CMake build script for ZeroMQ unit tests cmake_minimum_required(VERSION 2.8.1...3.31) set(unittests unittest_ypipe unittest_poller unittest_mtrie unittest_ip_resolver unittest_udp_address unittest_radix_tree unittest_curve_encoding) # if(ENABLE_DRAFTS) list(APPEND tests ) endif(ENABLE_DRAFTS) # add location of platform.hpp for Windows builds if(WIN32) add_definitions(-DZMQ_CUSTOM_PLATFORM_HPP) add_definitions(-D_WINSOCK_DEPRECATED_NO_WARNINGS) # Same name on 64bit systems link_libraries(ws2_32.lib) endif() include_directories("${ZeroMQ_SOURCE_DIR}/include" "${ZeroMQ_SOURCE_DIR}/src" "${ZeroMQ_BINARY_DIR}") include_directories("${ZeroMQ_SOURCE_DIR}/external/unity") foreach(test ${unittests}) # target_sources not supported before CMake 3.1 add_executable(${test} ${test}.cpp "unittest_resolver_common.hpp") # per-test directories not generated on OS X / Darwin if(NOT ${CMAKE_CXX_COMPILER_ID} MATCHES "Clang.*") link_directories(${test} PRIVATE "${ZeroMQ_SOURCE_DIR}/../lib") endif() target_link_libraries(${test} testutil-static) if(RT_LIBRARY) target_link_libraries(${test} ${RT_LIBRARY}) endif() if(CMAKE_SYSTEM_NAME MATCHES "QNX") target_link_libraries(${test} socket) target_link_libraries(${test} m) endif() if (WITH_GSSAPI_KRB5) target_link_libraries(${test} ${GSSAPI_KRB5_LIBRARIES}) endif() if(WIN32) add_test( NAME ${test} WORKING_DIRECTORY ${LIBRARY_OUTPUT_PATH} COMMAND ${test}) else() add_test(NAME ${test} COMMAND ${test}) endif() set_tests_properties(${test} PROPERTIES TIMEOUT 10) # TODO prevent libzmq (non-static) being in the list of link libraries at all get_target_property(LIBS ${test} LINK_LIBRARIES) list(REMOVE_ITEM LIBS libzmq) set_target_properties(${test} PROPERTIES LINK_LIBRARIES "${LIBS}") endforeach() # Check whether all tests in the current folder are present TODO duplicated with tests/CMakeLists.txt, define as a # function? file(READ "${CMAKE_CURRENT_LIST_FILE}" CURRENT_LIST_FILE_CONTENT) file(GLOB ALL_TEST_SOURCES "test_*.cpp") foreach(TEST_SOURCE ${ALL_TEST_SOURCES}) get_filename_component(TESTNAME "${TEST_SOURCE}" NAME_WE) string(REGEX MATCH "${TESTNAME}" MATCH_TESTNAME "${CURRENT_LIST_FILE_CONTENT}") if(NOT MATCH_TESTNAME) message(AUTHOR_WARNING "Test '${TESTNAME}' is not known to CTest.") endif() endforeach()
sophomore_public/libzmq
unittests/CMakeLists.txt
Text
gpl-3.0
2,417
/* SPDX-License-Identifier: MPL-2.0 */ #include "../tests/testutil_unity.hpp" // TODO: remove this ugly hack #ifdef close #undef close #endif #include <curve_mechanism_base.hpp> #include <msg.hpp> #include <random.hpp> #include <unity.h> #include <vector> void setUp () { } void tearDown () { } void test_roundtrip (zmq::msg_t *msg_) { #ifdef ZMQ_HAVE_CURVE const std::vector<uint8_t> original (static_cast<uint8_t *> (msg_->data ()), static_cast<uint8_t *> (msg_->data ()) + msg_->size ()); zmq::curve_encoding_t encoding_client ("CurveZMQMESSAGEC", "CurveZMQMESSAGES", false); zmq::curve_encoding_t encoding_server ("CurveZMQMESSAGES", "CurveZMQMESSAGEC", false); uint8_t client_public[32]; uint8_t client_secret[32]; TEST_ASSERT_SUCCESS_ERRNO ( crypto_box_keypair (client_public, client_secret)); uint8_t server_public[32]; uint8_t server_secret[32]; TEST_ASSERT_SUCCESS_ERRNO ( crypto_box_keypair (server_public, server_secret)); TEST_ASSERT_SUCCESS_ERRNO ( crypto_box_beforenm (encoding_client.get_writable_precom_buffer (), server_public, client_secret)); TEST_ASSERT_SUCCESS_ERRNO ( crypto_box_beforenm (encoding_server.get_writable_precom_buffer (), client_public, server_secret)); TEST_ASSERT_SUCCESS_ERRNO (encoding_client.encode (msg_)); // TODO: This is hacky... encoding_server.set_peer_nonce (0); int error_event_code; TEST_ASSERT_SUCCESS_ERRNO ( encoding_server.decode (msg_, &error_event_code)); TEST_ASSERT_EQUAL_INT (original.size (), msg_->size ()); if (!original.empty ()) { TEST_ASSERT_EQUAL_UINT8_ARRAY (&original[0], msg_->data (), original.size ()); } #else LIBZMQ_UNUSED (msg_); #endif } void test_roundtrip_empty () { #ifndef ZMQ_HAVE_CURVE TEST_IGNORE_MESSAGE ("CURVE support is disabled"); #endif zmq::msg_t msg; msg.init (); test_roundtrip (&msg); msg.close (); } void test_roundtrip_small () { #ifndef ZMQ_HAVE_CURVE TEST_IGNORE_MESSAGE ("CURVE support is disabled"); #endif zmq::msg_t msg; msg.init_size (32); memcpy (msg.data (), "0123456789ABCDEF0123456789ABCDEF", 32); test_roundtrip (&msg); msg.close (); } void test_roundtrip_large () { #ifndef ZMQ_HAVE_CURVE TEST_IGNORE_MESSAGE ("CURVE support is disabled"); #endif zmq::msg_t msg; msg.init_size (2048); for (size_t pos = 0; pos < 2048; pos += 32) { memcpy (static_cast<char *> (msg.data ()) + pos, "0123456789ABCDEF0123456789ABCDEF", 32); } test_roundtrip (&msg); msg.close (); } void test_roundtrip_empty_more () { #ifndef ZMQ_HAVE_CURVE TEST_IGNORE_MESSAGE ("CURVE support is disabled"); #endif zmq::msg_t msg; msg.init (); msg.set_flags (zmq::msg_t::more); test_roundtrip (&msg); TEST_ASSERT_TRUE (msg.flags () & zmq::msg_t::more); msg.close (); } int main () { setup_test_environment (); zmq::random_open (); UNITY_BEGIN (); RUN_TEST (test_roundtrip_empty); RUN_TEST (test_roundtrip_small); RUN_TEST (test_roundtrip_large); RUN_TEST (test_roundtrip_empty_more); zmq::random_close (); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_curve_encoding.cpp
C++
gpl-3.0
3,474
/* SPDX-License-Identifier: MPL-2.0 */ #include <unity.h> #include "../src/macros.hpp" #include "../tests/testutil.hpp" #include "../tests/testutil_unity.hpp" #include "../unittests/unittest_resolver_common.hpp" #include <ip_resolver.hpp> #include <ip.hpp> #ifndef _WIN32 #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #endif void setUp () { } void tearDown () { } class test_ip_resolver_t ZMQ_FINAL : public zmq::ip_resolver_t { public: test_ip_resolver_t (zmq::ip_resolver_options_t opts_) : ip_resolver_t (opts_) { } protected: struct dns_lut_t { const char *hostname; const char *ipv4; const char *ipv6; }; int do_getaddrinfo (const char *node_, const char *service_, const struct addrinfo *hints_, struct addrinfo **res_) ZMQ_FINAL { static const struct dns_lut_t dns_lut[] = { {"ip.zeromq.org", "10.100.0.1", "fdf5:d058:d656::1"}, {"ipv4only.zeromq.org", "10.100.0.2", "::ffff:10.100.0.2"}, {"ipv6only.zeromq.org", NULL, "fdf5:d058:d656::2"}, }; unsigned lut_len = sizeof (dns_lut) / sizeof (dns_lut[0]); struct addrinfo ai; TEST_ASSERT_NULL (service_); bool ipv6 = (hints_->ai_family == AF_INET6); bool no_dns = (hints_->ai_flags & AI_NUMERICHOST) != 0; const char *ip = NULL; if (!no_dns) { for (unsigned i = 0; i < lut_len; i++) { if (strcmp (dns_lut[i].hostname, node_) == 0) { if (ipv6) { ip = dns_lut[i].ipv6; } else { ip = dns_lut[i].ipv4; if (ip == NULL) { // No address associated with NAME return EAI_NODATA; } } } } } if (ip == NULL) { // No entry for 'node_' found in the LUT (or DNS is // forbidden), assume that it's a numeric IP address ip = node_; } // Call the real getaddrinfo implementation, making sure that it won't // attempt to resolve using DNS ai = *hints_; ai.ai_flags |= AI_NUMERICHOST; return zmq::ip_resolver_t::do_getaddrinfo (ip, NULL, &ai, res_); } unsigned int do_if_nametoindex (const char *ifname_) ZMQ_FINAL { static const char *dummy_interfaces[] = { "lo0", "eth0", "eth1", }; unsigned lut_len = sizeof (dummy_interfaces) / sizeof (dummy_interfaces[0]); for (unsigned i = 0; i < lut_len; i++) { if (strcmp (dummy_interfaces[i], ifname_) == 0) { // The dummy index will be the position in the array + 1 (0 is // invalid) return i + 1; } } // Not found return 0; } }; // Attempt a resolution and test the results. If 'expected_addr_' is NULL // assume that the resolution is meant to fail. // // On windows we can receive an IPv4 address even when an IPv6 is requested, if // we're in this situation then we compare to 'expected_addr_v4_failover_' // instead. static void test_resolve (zmq::ip_resolver_options_t opts_, const char *name_, const char *expected_addr_, uint16_t expected_port_ = 0, uint16_t expected_zone_ = 0, const char *expected_addr_v4_failover_ = NULL) { zmq::ip_addr_t addr; int family = opts_.ipv6 () ? AF_INET6 : AF_INET; if (family == AF_INET6 && !is_ipv6_available ()) { TEST_IGNORE_MESSAGE ("ipv6 is not available"); } // Generate an invalid but well-defined 'ip_addr_t'. Avoids testing // uninitialized values if the code is buggy. memset (&addr, 0xba, sizeof (addr)); test_ip_resolver_t resolver (opts_); int rc = resolver.resolve (&addr, name_); if (expected_addr_ == NULL) { // TODO also check the expected errno TEST_ASSERT_EQUAL (-1, rc); return; } TEST_ASSERT_SUCCESS_ERRNO (rc); validate_address (family, &addr, expected_addr_, expected_port_, expected_zone_, expected_addr_v4_failover_); } // Helper macro to define the v4/v6 function pairs #define MAKE_TEST_V4V6(_test) \ static void _test##_ipv4 () { _test (false); } \ \ static void _test##_ipv6 () { _test (true); } static void test_bind_any (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.bindable (true).expect_port (true).ipv6 (ipv6_); const char *expected = ipv6_ ? "::" : "0.0.0.0"; test_resolve (resolver_opts, "*:*", expected, 0); } MAKE_TEST_V4V6 (test_bind_any) static void test_bind_any_port0 (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.bindable (true).expect_port (true).ipv6 (ipv6_); // Should be equivalent to "*:*" const char *expected = ipv6_ ? "::" : "0.0.0.0"; test_resolve (resolver_opts, "*:0", expected, 0); } MAKE_TEST_V4V6 (test_bind_any_port0) static void test_nobind_any (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (ipv6_); // Wildcard should be rejected if we're not looking for a // bindable address test_resolve (resolver_opts, "*:*", NULL); } MAKE_TEST_V4V6 (test_nobind_any) static void test_nobind_any_port (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (ipv6_); // Wildcard should be rejected if we're not looking for a // bindable address test_resolve (resolver_opts, "*:1234", NULL); } MAKE_TEST_V4V6 (test_nobind_any_port) static void test_nobind_addr_anyport (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (ipv6_); // Wildcard port should be rejected for non-bindable addresses test_resolve (resolver_opts, "127.0.0.1:*", NULL); } MAKE_TEST_V4V6 (test_nobind_addr_anyport) static void test_nobind_addr_port0 (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (ipv6_); // Connecting to port 0 is allowed, although it might not be massively // useful const char *expected = ipv6_ ? "::ffff:127.0.0.1" : "127.0.0.1"; const char *fallback = ipv6_ ? "127.0.0.1" : NULL; test_resolve (resolver_opts, "127.0.0.1:0", expected, 0, 0, fallback); } MAKE_TEST_V4V6 (test_nobind_addr_port0) static void test_parse_ipv4_simple () { zmq::ip_resolver_options_t resolver_opts; test_resolve (resolver_opts, "1.2.128.129", "1.2.128.129"); } static void test_parse_ipv4_zero () { zmq::ip_resolver_options_t resolver_opts; test_resolve (resolver_opts, "0.0.0.0", "0.0.0.0"); } static void test_parse_ipv4_max () { zmq::ip_resolver_options_t resolver_opts; test_resolve (resolver_opts, "255.255.255.255", "255.255.255.255"); } static void test_parse_ipv4_brackets () { zmq::ip_resolver_options_t resolver_opts; // Not particularly useful, but valid test_resolve (resolver_opts, "[1.2.128.129]", "1.2.128.129"); } static void test_parse_ipv4_brackets_missingl () { zmq::ip_resolver_options_t resolver_opts; test_resolve (resolver_opts, "1.2.128.129]", NULL); } static void test_parse_ipv4_brackets_missingr () { zmq::ip_resolver_options_t resolver_opts; test_resolve (resolver_opts, "[1.2.128.129", NULL); } static void test_parse_ipv4_brackets_bad () { zmq::ip_resolver_options_t resolver_opts; test_resolve (resolver_opts, "[1.2.128].129", NULL); } static void test_parse_ipv4_reject_port () { zmq::ip_resolver_options_t resolver_opts; // No port expected, should be rejected test_resolve (resolver_opts, "1.2.128.129:123", NULL); } static void test_parse_ipv4_reject_any () { zmq::ip_resolver_options_t resolver_opts; // No port expected, should be rejected test_resolve (resolver_opts, "1.2.128.129:*", NULL); } static void test_parse_ipv4_reject_ipv6 () { zmq::ip_resolver_options_t resolver_opts; // No port expected, should be rejected test_resolve (resolver_opts, "::1", NULL); } static void test_parse_ipv4_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "1.2.128.129:123", "1.2.128.129", 123); } static void test_parse_ipv4_port0 () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); // Port 0 is accepted and is equivalent to * test_resolve (resolver_opts, "1.2.128.129:0", "1.2.128.129", 0); } static void test_parse_ipv4_port_garbage () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); // The code doesn't validate that the port doesn't contain garbage test_resolve (resolver_opts, "1.2.3.4:567bad", "1.2.3.4", 567); } static void test_parse_ipv4_port_missing () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "1.2.3.4", NULL); } static void test_parse_ipv4_port_bad () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "1.2.3.4:bad", NULL); } static void test_parse_ipv4_port_brackets () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "[192.168.1.1]:5555", "192.168.1.1", 5555); } static void test_parse_ipv4_port_brackets_bad () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "[192.168.1.1:]5555", NULL); } static void test_parse_ipv4_port_brackets_bad2 () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "[192.168.1.1:5555]", NULL); } static void test_parse_ipv4_wild_brackets_bad () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "[192.168.1.1:*]", NULL); } static void test_parse_ipv4_port_ipv6_reject () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true); test_resolve (resolver_opts, "[::1]:1234", NULL); } static void test_parse_ipv6_simple () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "::1", "::1"); } static void test_parse_ipv6_simple2 () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "abcd:1234::1:0:234", "abcd:1234::1:0:234"); } static void test_parse_ipv6_zero () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "::", "::"); } static void test_parse_ipv6_max () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); } static void test_parse_ipv6_brackets () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "[::1]", "::1"); } static void test_parse_ipv6_brackets_missingl () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "::1]", NULL); } static void test_parse_ipv6_brackets_missingr () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "[::1", NULL); } static void test_parse_ipv6_brackets_bad () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "[abcd:1234::1:]0:234", NULL); } static void test_parse_ipv6_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).expect_port (true); test_resolve (resolver_opts, "[1234::1]:80", "1234::1", 80); } static void test_parse_ipv6_port_any () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).expect_port (true).bindable (true); test_resolve (resolver_opts, "[1234::1]:*", "1234::1", 0); } static void test_parse_ipv6_port_nobrackets () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).expect_port (true); // Should this be allowed? Seems error-prone but so far ZMQ accepts it. test_resolve (resolver_opts, "abcd:1234::1:0:234:123", "abcd:1234::1:0:234", 123); } static void test_parse_ipv4_in_ipv6 () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); // Parsing IPv4 should also work if an IPv6 is requested, it returns an // IPv6 with the IPv4 address embedded (except sometimes on Windows where // we end up with an IPv4 anyway) test_resolve (resolver_opts, "11.22.33.44", "::ffff:11.22.33.44", 0, 0, "11.22.33.44"); } static void test_parse_ipv4_in_ipv6_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).expect_port (true); test_resolve (resolver_opts, "11.22.33.44:55", "::ffff:11.22.33.44", 55, 0, "11.22.33.44"); } static void test_parse_ipv6_scope_int () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "3000:4:5::1:234%2", "3000:4:5::1:234", 0, 2); } static void test_parse_ipv6_scope_zero () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "3000:4:5::1:234%0", NULL); } static void test_parse_ipv6_scope_int_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (true); test_resolve (resolver_opts, "3000:4:5::1:234%2:1111", "3000:4:5::1:234", 1111, 2); } static void test_parse_ipv6_scope_if () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "3000:4:5::1:234%eth1", "3000:4:5::1:234", 0, 3); } static void test_parse_ipv6_scope_if_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (true); test_resolve (resolver_opts, "3000:4:5::1:234%eth0:8080", "3000:4:5::1:234", 8080, 2); } static void test_parse_ipv6_scope_if_port_brackets () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).ipv6 (true); test_resolve (resolver_opts, "[3000:4:5::1:234%eth0]:8080", "3000:4:5::1:234", 8080, 2); } static void test_parse_ipv6_scope_badif () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true); test_resolve (resolver_opts, "3000:4:5::1:234%bad0", NULL); } static void test_dns_ipv4_simple () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "ip.zeromq.org", "10.100.0.1"); } static void test_dns_ipv4_only () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "ipv4only.zeromq.org", "10.100.0.2"); } static void test_dns_ipv4_invalid () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "invalid.zeromq.org", NULL); } static void test_dns_ipv4_ipv6 () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "ipv6only.zeromq.org", NULL); } static void test_dns_ipv4_numeric () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); // Numeric IPs should still work test_resolve (resolver_opts, "5.4.3.2", "5.4.3.2"); } static void test_dns_ipv4_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.expect_port (true).allow_dns (true); test_resolve (resolver_opts, "ip.zeromq.org:1234", "10.100.0.1", 1234); } static void test_dns_ipv6_simple () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).allow_dns (true); test_resolve (resolver_opts, "ip.zeromq.org", "fdf5:d058:d656::1"); } static void test_dns_ipv6_only () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).allow_dns (true); test_resolve (resolver_opts, "ipv6only.zeromq.org", "fdf5:d058:d656::2"); } static void test_dns_ipv6_invalid () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).allow_dns (true); test_resolve (resolver_opts, "invalid.zeromq.org", NULL); } static void test_dns_ipv6_ipv4 () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).allow_dns (true); // If a host doesn't have an IPv6 then it should resolve as an embedded v4 // address in an IPv6 test_resolve (resolver_opts, "ipv4only.zeromq.org", "::ffff:10.100.0.2"); } static void test_dns_ipv6_numeric () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).allow_dns (true); // Numeric IPs should still work test_resolve (resolver_opts, "fdf5:d058:d656::1", "fdf5:d058:d656::1"); } static void test_dns_ipv6_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (true).expect_port (true).allow_dns (true); test_resolve (resolver_opts, "ip.zeromq.org:1234", "fdf5:d058:d656::1", 1234); } void test_dns_brackets () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "[ip.zeromq.org]", "10.100.0.1"); } void test_dns_brackets_bad () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "[ip.zeromq].org", NULL); } void test_dns_brackets_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "[ip.zeromq.org]:22", "10.100.0.1", 22); } void test_dns_brackets_port_bad () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true); test_resolve (resolver_opts, "[ip.zeromq.org:22]", NULL); } void test_dns_deny (bool ipv6_) { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (false).ipv6 (ipv6_); // DNS resolution shouldn't work when disallowed test_resolve (resolver_opts, "ip.zeromq.org", NULL); } MAKE_TEST_V4V6 (test_dns_deny) void test_dns_ipv6_scope () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true).ipv6 (true); // Not sure if that's very useful but you could technically add a scope // identifier to a hostname test_resolve (resolver_opts, "ip.zeromq.org%lo0", "fdf5:d058:d656::1", 0, 1); } void test_dns_ipv6_scope_port () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true).expect_port (true).ipv6 (true); // Not sure if that's very useful but you could technically add a scope // identifier to a hostname test_resolve (resolver_opts, "ip.zeromq.org%lo0:4444", "fdf5:d058:d656::1", 4444, 1); } void test_dns_ipv6_scope_port_brackets () { zmq::ip_resolver_options_t resolver_opts; resolver_opts.allow_dns (true).expect_port (true).ipv6 (true); test_resolve (resolver_opts, "[ip.zeromq.org%lo0]:4444", "fdf5:d058:d656::1", 4444, 1); } static void test_addr (int family_, const char *addr_, bool multicast_) { if (family_ == AF_INET6 && !is_ipv6_available ()) { TEST_IGNORE_MESSAGE ("ipv6 is not available"); } zmq::ip_resolver_options_t resolver_opts; resolver_opts.ipv6 (family_ == AF_INET6); test_ip_resolver_t resolver (resolver_opts); zmq::ip_addr_t addr; TEST_ASSERT_SUCCESS_ERRNO (resolver.resolve (&addr, addr_)); TEST_ASSERT_EQUAL (family_, addr.family ()); TEST_ASSERT_EQUAL (multicast_, addr.is_multicast ()); } static void test_addr_unicast_ipv4 () { test_addr (AF_INET, "1.2.3.4", false); } static void test_addr_unicast_ipv6 () { test_addr (AF_INET6, "abcd::1", false); } static void test_addr_multicast_ipv4 () { test_addr (AF_INET, "230.1.2.3", true); } static void test_addr_multicast_ipv6 () { test_addr (AF_INET6, "ffab::1234", true); } static void test_addr_multicast_ipv4_min () { test_addr (AF_INET, "224.0.0.0", true); } static void test_addr_multicast_ipv6_min () { test_addr (AF_INET6, "ff00::", true); } static void test_addr_multicast_ipv4_max () { test_addr (AF_INET, "239.255.255.255", true); } static void test_addr_multicast_ipv6_max () { test_addr (AF_INET6, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", true); } static void test_addr_multicast_ipv4_sub () { test_addr (AF_INET, "223.255.255.255", false); } static void test_addr_multicast_ipv6_sub () { test_addr (AF_INET6, "feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", false); } static void test_addr_multicast_ipv4_over () { test_addr (AF_INET, "240.0.0.0", false); } int main (void) { zmq::initialize_network (); setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_bind_any_ipv4); RUN_TEST (test_bind_any_ipv6); RUN_TEST (test_bind_any_port0_ipv4); RUN_TEST (test_bind_any_port0_ipv6); RUN_TEST (test_nobind_any_ipv4); RUN_TEST (test_nobind_any_ipv6); RUN_TEST (test_nobind_any_port_ipv4); RUN_TEST (test_nobind_any_port_ipv6); RUN_TEST (test_nobind_addr_anyport_ipv4); RUN_TEST (test_nobind_addr_anyport_ipv6); RUN_TEST (test_nobind_addr_port0_ipv4); RUN_TEST (test_nobind_addr_port0_ipv6); RUN_TEST (test_parse_ipv4_simple); RUN_TEST (test_parse_ipv4_zero); RUN_TEST (test_parse_ipv4_max); RUN_TEST (test_parse_ipv4_brackets); RUN_TEST (test_parse_ipv4_brackets_missingl); RUN_TEST (test_parse_ipv4_brackets_missingr); RUN_TEST (test_parse_ipv4_brackets_bad); RUN_TEST (test_parse_ipv4_reject_port); RUN_TEST (test_parse_ipv4_reject_any); RUN_TEST (test_parse_ipv4_reject_ipv6); RUN_TEST (test_parse_ipv4_port); RUN_TEST (test_parse_ipv4_port0); RUN_TEST (test_parse_ipv4_port_garbage); RUN_TEST (test_parse_ipv4_port_missing); RUN_TEST (test_parse_ipv4_port_bad); RUN_TEST (test_parse_ipv4_port_brackets); RUN_TEST (test_parse_ipv4_port_brackets_bad); RUN_TEST (test_parse_ipv4_port_brackets_bad2); RUN_TEST (test_parse_ipv4_wild_brackets_bad); RUN_TEST (test_parse_ipv4_port_ipv6_reject); RUN_TEST (test_parse_ipv6_simple); RUN_TEST (test_parse_ipv6_simple2); RUN_TEST (test_parse_ipv6_zero); RUN_TEST (test_parse_ipv6_max); RUN_TEST (test_parse_ipv6_brackets); RUN_TEST (test_parse_ipv6_brackets_missingl); RUN_TEST (test_parse_ipv6_brackets_missingr); RUN_TEST (test_parse_ipv6_brackets_bad); RUN_TEST (test_parse_ipv6_port); RUN_TEST (test_parse_ipv6_port_any); RUN_TEST (test_parse_ipv6_port_nobrackets); RUN_TEST (test_parse_ipv4_in_ipv6); RUN_TEST (test_parse_ipv4_in_ipv6_port); RUN_TEST (test_parse_ipv6_scope_int); RUN_TEST (test_parse_ipv6_scope_zero); RUN_TEST (test_parse_ipv6_scope_int_port); RUN_TEST (test_parse_ipv6_scope_if); RUN_TEST (test_parse_ipv6_scope_if_port); RUN_TEST (test_parse_ipv6_scope_if_port_brackets); RUN_TEST (test_parse_ipv6_scope_badif); RUN_TEST (test_dns_ipv4_simple); RUN_TEST (test_dns_ipv4_only); RUN_TEST (test_dns_ipv4_invalid); RUN_TEST (test_dns_ipv4_ipv6); RUN_TEST (test_dns_ipv4_numeric); RUN_TEST (test_dns_ipv4_port); RUN_TEST (test_dns_ipv6_simple); RUN_TEST (test_dns_ipv6_only); RUN_TEST (test_dns_ipv6_invalid); RUN_TEST (test_dns_ipv6_ipv4); RUN_TEST (test_dns_ipv6_numeric); RUN_TEST (test_dns_ipv6_port); RUN_TEST (test_dns_brackets); RUN_TEST (test_dns_brackets_bad); RUN_TEST (test_dns_deny_ipv4); RUN_TEST (test_dns_deny_ipv6); RUN_TEST (test_dns_ipv6_scope); RUN_TEST (test_dns_ipv6_scope_port); RUN_TEST (test_dns_ipv6_scope_port_brackets); RUN_TEST (test_addr_unicast_ipv4); RUN_TEST (test_addr_unicast_ipv6); RUN_TEST (test_addr_multicast_ipv4); RUN_TEST (test_addr_multicast_ipv6); RUN_TEST (test_addr_multicast_ipv4_min); RUN_TEST (test_addr_multicast_ipv6_min); RUN_TEST (test_addr_multicast_ipv4_max); RUN_TEST (test_addr_multicast_ipv6_max); RUN_TEST (test_addr_multicast_ipv4_sub); RUN_TEST (test_addr_multicast_ipv6_sub); RUN_TEST (test_addr_multicast_ipv4_over); zmq::shutdown_network (); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_ip_resolver.cpp
C++
gpl-3.0
25,095
/* SPDX-License-Identifier: MPL-2.0 */ #include "../tests/testutil.hpp" #if defined(min) #undef min #endif #include <generic_mtrie_impl.hpp> #include <unity.h> void setUp () { } void tearDown () { } int getlen (const zmq::generic_mtrie_t<int>::prefix_t &data_) { return static_cast<int> (strlen (reinterpret_cast<const char *> (data_))); } void test_create () { zmq::generic_mtrie_t<int> mtrie; } void mtrie_count (int *pipe_, int *count_) { LIBZMQ_UNUSED (pipe_); ++*count_; } void test_check_empty_match_nonempty_data () { zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); int count = 0; mtrie.match (test_name, getlen (test_name), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (0, count); } void test_check_empty_match_empty_data () { zmq::generic_mtrie_t<int> mtrie; int count = 0; mtrie.match (NULL, 0, mtrie_count, &count); TEST_ASSERT_EQUAL_INT (0, count); } void test_add_single_entry_match_exact () { int pipe; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); bool res = mtrie.add (test_name, getlen (test_name), &pipe); TEST_ASSERT_TRUE (res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); int count = 0; mtrie.match (test_name, getlen (test_name), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (1, count); } void test_add_single_entry_twice_match_exact () { int pipe; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); bool res = mtrie.add (test_name, getlen (test_name), &pipe); TEST_ASSERT_TRUE (res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); res = mtrie.add (test_name, getlen (test_name), &pipe); TEST_ASSERT_FALSE (res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); int count = 0; mtrie.match (test_name, getlen (test_name), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (1, count); } void test_add_two_entries_with_same_name_match_exact () { int pipe_1, pipe_2; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); bool res = mtrie.add (test_name, getlen (test_name), &pipe_1); TEST_ASSERT_TRUE (res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); res = mtrie.add (test_name, getlen (test_name), &pipe_2); TEST_ASSERT_FALSE (res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); int count = 0; mtrie.match (test_name, getlen (test_name), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (2, count); } void test_add_two_entries_match_prefix_and_exact () { int pipe_1, pipe_2; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name_prefix = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); const zmq::generic_mtrie_t<int>::prefix_t test_name_full = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foobar"); bool res = mtrie.add (test_name_prefix, getlen (test_name_prefix), &pipe_1); TEST_ASSERT_TRUE (res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); res = mtrie.add (test_name_full, getlen (test_name_full), &pipe_2); TEST_ASSERT_TRUE (res); TEST_ASSERT_EQUAL_INT (2, mtrie.num_prefixes ()); int count = 0; mtrie.match (test_name_full, getlen (test_name_full), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (2, count); } void test_add_rm_single_entry_match_exact () { int pipe; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); mtrie.add (test_name, getlen (test_name), &pipe); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); zmq::generic_mtrie_t<int>::rm_result res = mtrie.rm (test_name, getlen (test_name), &pipe); TEST_ASSERT_EQUAL (zmq::generic_mtrie_t<int>::last_value_removed, res); TEST_ASSERT_EQUAL_INT (0, mtrie.num_prefixes ()); int count = 0; mtrie.match (test_name, getlen (test_name), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (0, count); } void test_rm_nonexistent_0_size_empty () { int pipe; zmq::generic_mtrie_t<int> mtrie; zmq::generic_mtrie_t<int>::rm_result res = mtrie.rm (0, 0, &pipe); TEST_ASSERT_EQUAL (zmq::generic_mtrie_t<int>::not_found, res); TEST_ASSERT_EQUAL_INT (0, mtrie.num_prefixes ()); } void test_rm_nonexistent_empty () { int pipe; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t test_name = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> ("foo"); zmq::generic_mtrie_t<int>::rm_result res = mtrie.rm (test_name, getlen (test_name), &pipe); TEST_ASSERT_EQUAL (zmq::generic_mtrie_t<int>::not_found, res); TEST_ASSERT_EQUAL_INT (0, mtrie.num_prefixes ()); int count = 0; mtrie.match (test_name, getlen (test_name), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (0, count); } void test_add_and_rm_other (const char *add_name_, const char *rm_name_) { int addpipe, rmpipe; zmq::generic_mtrie_t<int> mtrie; const zmq::generic_mtrie_t<int>::prefix_t add_name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (add_name_); const zmq::generic_mtrie_t<int>::prefix_t rm_name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (rm_name_); mtrie.add (add_name_data, getlen (add_name_data), &addpipe); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); zmq::generic_mtrie_t<int>::rm_result res = mtrie.rm (rm_name_data, getlen (rm_name_data), &rmpipe); TEST_ASSERT_EQUAL (zmq::generic_mtrie_t<int>::not_found, res); TEST_ASSERT_EQUAL_INT (1, mtrie.num_prefixes ()); { int count = 0; mtrie.match (add_name_data, getlen (add_name_data), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (1, count); } if (strncmp (add_name_, rm_name_, std::min (strlen (add_name_), strlen (rm_name_) + 1)) != 0) { int count = 0; mtrie.match (rm_name_data, getlen (rm_name_data), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (0, count); } } void test_rm_nonexistent_nonempty_samename () { // TODO this triggers an assertion test_add_and_rm_other ("foo", "foo"); } void test_rm_nonexistent_nonempty_differentname () { test_add_and_rm_other ("foo", "bar"); } void test_rm_nonexistent_nonempty_prefix () { // TODO here, a test assertion fails test_add_and_rm_other ("foobar", "foo"); } void test_rm_nonexistent_nonempty_prefixed () { test_add_and_rm_other ("foo", "foobar"); } void add_indexed_expect_unique (zmq::generic_mtrie_t<int> &mtrie_, int *pipes_, const char **names_, size_t i_) { const zmq::generic_mtrie_t<int>::prefix_t name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (names_[i_]); bool res = mtrie_.add (name_data, getlen (name_data), &pipes_[i_]); TEST_ASSERT_EQUAL ( zmq::generic_mtrie_t<int>::last_value_removed, res); // FIXME asserting equality between enum and bool? I think first arg for macro should be "true" } void test_rm_nonexistent_between () { int pipes[3]; const char *names[] = {"foo1", "foo2", "foo3"}; zmq::generic_mtrie_t<int> mtrie; add_indexed_expect_unique (mtrie, pipes, names, 0); add_indexed_expect_unique (mtrie, pipes, names, 2); TEST_ASSERT_EQUAL_INT (2, mtrie.num_prefixes ()); const zmq::generic_mtrie_t<int>::prefix_t name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (names[1]); zmq::generic_mtrie_t<int>::rm_result res = mtrie.rm (name_data, getlen (name_data), &pipes[1]); TEST_ASSERT_EQUAL (zmq::generic_mtrie_t<int>::not_found, res); TEST_ASSERT_EQUAL_INT (2, mtrie.num_prefixes ()); } template <size_t N> void add_entries (zmq::generic_mtrie_t<int> &mtrie_, int (&pipes_)[N], const char *(&names_)[N]) { for (size_t i = 0; i < N; ++i) { add_indexed_expect_unique (mtrie_, pipes_, names_, i); } TEST_ASSERT_EQUAL_INT (N, mtrie_.num_prefixes ()); } void test_add_multiple () { int pipes[3]; const char *names[] = {"foo1", "foo2", "foo3"}; zmq::generic_mtrie_t<int> mtrie; add_entries (mtrie, pipes, names); for (size_t i = 0; i < sizeof (names) / sizeof (names[0]); ++i) { const zmq::generic_mtrie_t<int>::prefix_t name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (names[i]); int count = 0; mtrie.match (name_data, getlen (name_data), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (1, count); } } void test_add_multiple_reverse () { int pipes[3]; const char *names[] = {"foo1", "foo2", "foo3"}; zmq::generic_mtrie_t<int> mtrie; for (int i = 2; i >= 0; --i) { add_indexed_expect_unique (mtrie, pipes, names, static_cast<size_t> (i)); } TEST_ASSERT_EQUAL_INT (3, mtrie.num_prefixes ()); for (size_t i = 0; i < 3; ++i) { const zmq::generic_mtrie_t<int>::prefix_t name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (names[i]); int count = 0; mtrie.match (name_data, getlen (name_data), mtrie_count, &count); TEST_ASSERT_EQUAL_INT (1, count); } } template <size_t N> void add_and_rm_entries (const char *(&names_)[N]) { int pipes[N]; zmq::generic_mtrie_t<int> mtrie; add_entries (mtrie, pipes, names_); for (size_t i = 0; i < N; ++i) { const zmq::generic_mtrie_t<int>::prefix_t name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (names_[i]); zmq::generic_mtrie_t<int>::rm_result res = mtrie.rm (name_data, getlen (name_data), &pipes[i]); TEST_ASSERT_EQUAL (zmq::generic_mtrie_t<int>::last_value_removed, res); } TEST_ASSERT_EQUAL_INT (0, mtrie.num_prefixes ()); } void test_rm_multiple_in_order () { const char *names[] = {"foo1", "foo2", "foo3"}; add_and_rm_entries (names); } void test_rm_multiple_reverse_order () { const char *names[] = {"foo3", "foo2", "foo1"}; add_and_rm_entries (names); } void check_name (zmq::generic_mtrie_t<int>::prefix_t data_, size_t len_, const char *name_) { TEST_ASSERT_EQUAL_UINT (strlen (name_), len_); TEST_ASSERT_EQUAL_STRING_LEN (name_, data_, len_); } template <size_t N> void add_entries_rm_pipes_unique (const char *(&names_)[N]) { int pipes[N]; zmq::generic_mtrie_t<int> mtrie; add_entries (mtrie, pipes, names_); for (size_t i = 0; i < N; ++i) { mtrie.rm (&pipes[i], check_name, names_[i], false); } } void test_rm_with_callback_multiple_in_order () { const char *names[] = {"foo1", "foo2", "foo3"}; add_entries_rm_pipes_unique (names); } void test_rm_with_callback_multiple_reverse_order () { const char *names[] = {"foo3", "foo2", "foo1"}; add_entries_rm_pipes_unique (names); } void check_count (zmq::generic_mtrie_t<int>::prefix_t data_, size_t len_, int *count_) { LIBZMQ_UNUSED (data_); LIBZMQ_UNUSED (len_); --(*count_); TEST_ASSERT_GREATER_OR_EQUAL (0, *count_); } void add_duplicate_entry (zmq::generic_mtrie_t<int> &mtrie_, int (&pipes_)[2]) { const char *name = "foo"; const zmq::generic_mtrie_t<int>::prefix_t name_data = reinterpret_cast<zmq::generic_mtrie_t<int>::prefix_t> (name); bool res = mtrie_.add (name_data, getlen (name_data), &pipes_[0]); TEST_ASSERT_TRUE (res); TEST_ASSERT_EQUAL_INT (1, mtrie_.num_prefixes ()); res = mtrie_.add (name_data, getlen (name_data), &pipes_[1]); TEST_ASSERT_FALSE (res); TEST_ASSERT_EQUAL_INT (1, mtrie_.num_prefixes ()); } void test_rm_with_callback_duplicate () { int pipes[2]; zmq::generic_mtrie_t<int> mtrie; add_duplicate_entry (mtrie, pipes); int count = 1; mtrie.rm (&pipes[0], check_count, &count, false); count = 1; mtrie.rm (&pipes[1], check_count, &count, false); } void test_rm_with_callback_duplicate_uniq_only () { int pipes[2]; zmq::generic_mtrie_t<int> mtrie; add_duplicate_entry (mtrie, pipes); int count = 0; mtrie.rm (&pipes[0], check_count, &count, true); count = 1; mtrie.rm (&pipes[1], check_count, &count, true); } int main (void) { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_create); RUN_TEST (test_check_empty_match_nonempty_data); RUN_TEST (test_check_empty_match_empty_data); RUN_TEST (test_add_single_entry_match_exact); RUN_TEST (test_add_single_entry_twice_match_exact); RUN_TEST (test_add_rm_single_entry_match_exact); RUN_TEST (test_add_two_entries_match_prefix_and_exact); RUN_TEST (test_add_two_entries_with_same_name_match_exact); RUN_TEST (test_rm_nonexistent_0_size_empty); RUN_TEST (test_rm_nonexistent_empty); RUN_TEST (test_rm_nonexistent_nonempty_samename); RUN_TEST (test_rm_nonexistent_nonempty_differentname); RUN_TEST (test_rm_nonexistent_nonempty_prefix); RUN_TEST (test_rm_nonexistent_nonempty_prefixed); RUN_TEST (test_rm_nonexistent_between); RUN_TEST (test_add_multiple); RUN_TEST (test_add_multiple_reverse); RUN_TEST (test_rm_multiple_in_order); RUN_TEST (test_rm_multiple_reverse_order); RUN_TEST (test_rm_with_callback_multiple_in_order); RUN_TEST (test_rm_with_callback_multiple_reverse_order); RUN_TEST (test_rm_with_callback_duplicate); RUN_TEST (test_rm_with_callback_duplicate_uniq_only); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_mtrie.cpp
C++
gpl-3.0
14,049
/* SPDX-License-Identifier: MPL-2.0 */ #include "../tests/testutil.hpp" #include <poller.hpp> #include <i_poll_events.hpp> #include <ip.hpp> #include <unity.h> #ifndef _WIN32 #include <unistd.h> #define closesocket close #endif void setUp () { } void tearDown () { } void test_create () { zmq::thread_ctx_t thread_ctx; zmq::poller_t poller (thread_ctx); } #if 0 // TODO this triggers an assertion. should it be a valid use case? void test_start_empty () { zmq::thread_ctx_t thread_ctx; zmq::poller_t poller (thread_ctx); poller.start (); msleep (SETTLE_TIME); } #endif struct test_events_t : zmq::i_poll_events { test_events_t (zmq::fd_t fd_, zmq::poller_t &poller_) : _fd (fd_), _poller (poller_) { (void) _fd; } void in_event () ZMQ_OVERRIDE { _poller.rm_fd (_handle); _handle = (zmq::poller_t::handle_t) NULL; // this must only be incremented after rm_fd in_events.add (1); } void out_event () ZMQ_OVERRIDE { // TODO } void timer_event (int id_) ZMQ_OVERRIDE { LIBZMQ_UNUSED (id_); _poller.rm_fd (_handle); _handle = (zmq::poller_t::handle_t) NULL; // this must only be incremented after rm_fd timer_events.add (1); } void set_handle (zmq::poller_t::handle_t handle_) { _handle = handle_; } zmq::atomic_counter_t in_events, timer_events; private: zmq::fd_t _fd; zmq::poller_t &_poller; zmq::poller_t::handle_t _handle; }; void wait_in_events (test_events_t &events_) { void *watch = zmq_stopwatch_start (); while (events_.in_events.get () < 1) { msleep (1); #ifdef ZMQ_BUILD_DRAFT TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (SETTLE_TIME, zmq_stopwatch_intermediate (watch), "Timeout waiting for in event"); #endif } zmq_stopwatch_stop (watch); } void wait_timer_events (test_events_t &events_) { void *watch = zmq_stopwatch_start (); while (events_.timer_events.get () < 1) { msleep (1); #ifdef ZMQ_BUILD_DRAFT TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (SETTLE_TIME, zmq_stopwatch_intermediate (watch), "Timeout waiting for timer event"); #endif } zmq_stopwatch_stop (watch); } void create_nonblocking_fdpair (zmq::fd_t *r_, zmq::fd_t *w_) { int rc = zmq::make_fdpair (r_, w_); TEST_ASSERT_EQUAL_INT (0, rc); TEST_ASSERT_NOT_EQUAL (zmq::retired_fd, *r_); TEST_ASSERT_NOT_EQUAL (zmq::retired_fd, *w_); zmq::unblock_socket (*r_); zmq::unblock_socket (*w_); } void send_signal (zmq::fd_t w_) { #if defined ZMQ_HAVE_EVENTFD const uint64_t inc = 1; ssize_t sz = write (w_, &inc, sizeof (inc)); assert (sz == sizeof (inc)); #else { char msg[] = "test"; int rc = send (w_, msg, sizeof (msg), 0); assert (rc == sizeof (msg)); } #endif } void close_fdpair (zmq::fd_t w_, zmq::fd_t r_) { int rc = closesocket (w_); TEST_ASSERT_EQUAL_INT (0, rc); #if !defined ZMQ_HAVE_EVENTFD rc = closesocket (r_); TEST_ASSERT_EQUAL_INT (0, rc); #else LIBZMQ_UNUSED (r_); #endif } void test_add_fd_and_start_and_receive_data () { zmq::thread_ctx_t thread_ctx; zmq::poller_t poller (thread_ctx); zmq::fd_t r, w; create_nonblocking_fdpair (&r, &w); test_events_t events (r, poller); zmq::poller_t::handle_t handle = poller.add_fd (r, &events); events.set_handle (handle); poller.set_pollin (handle); poller.start (); send_signal (w); wait_in_events (events); // required cleanup close_fdpair (w, r); } void test_add_fd_and_remove_by_timer () { zmq::fd_t r, w; create_nonblocking_fdpair (&r, &w); zmq::thread_ctx_t thread_ctx; zmq::poller_t poller (thread_ctx); test_events_t events (r, poller); zmq::poller_t::handle_t handle = poller.add_fd (r, &events); events.set_handle (handle); poller.add_timer (50, &events, 0); poller.start (); wait_timer_events (events); // required cleanup close_fdpair (w, r); } #ifdef _WIN32 void test_add_fd_with_pending_failing_connect () { zmq::thread_ctx_t thread_ctx; zmq::poller_t poller (thread_ctx); zmq::fd_t bind_socket = socket (AF_INET, SOCK_STREAM, 0); sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); addr.sin_port = 0; TEST_ASSERT_EQUAL_INT (0, bind (bind_socket, reinterpret_cast<const sockaddr *> (&addr), sizeof (addr))); int addr_len = static_cast<int> (sizeof (addr)); TEST_ASSERT_EQUAL_INT (0, getsockname (bind_socket, reinterpret_cast<sockaddr *> (&addr), &addr_len)); zmq::fd_t connect_socket = socket (AF_INET, SOCK_STREAM, 0); zmq::unblock_socket (connect_socket); TEST_ASSERT_EQUAL_INT ( -1, connect (connect_socket, reinterpret_cast<const sockaddr *> (&addr), sizeof (addr))); TEST_ASSERT_EQUAL_INT (WSAEWOULDBLOCK, WSAGetLastError ()); test_events_t events (connect_socket, poller); zmq::poller_t::handle_t handle = poller.add_fd (connect_socket, &events); events.set_handle (handle); poller.set_pollin (handle); poller.start (); wait_in_events (events); int value; int value_len = sizeof (value); TEST_ASSERT_EQUAL_INT (0, getsockopt (connect_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char *> (&value), &value_len)); TEST_ASSERT_EQUAL_INT (WSAECONNREFUSED, value); // required cleanup close (connect_socket); close (bind_socket); } #endif int main (void) { UNITY_BEGIN (); zmq::initialize_network (); setup_test_environment (); RUN_TEST (test_create); RUN_TEST (test_add_fd_and_start_and_receive_data); RUN_TEST (test_add_fd_and_remove_by_timer); #if defined _WIN32 RUN_TEST (test_add_fd_with_pending_failing_connect); #endif zmq::shutdown_network (); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_poller.cpp
C++
gpl-3.0
6,333
/* SPDX-License-Identifier: MPL-2.0 */ #include "../tests/testutil.hpp" #include <radix_tree.hpp> #include <stdint.hpp> #include <set> #include <string> #include <string.h> #include <unity.h> #include <vector> void setUp () { } void tearDown () { } bool tree_add (zmq::radix_tree_t &tree_, const std::string &key_) { return tree_.add (reinterpret_cast<const unsigned char *> (key_.data ()), key_.size ()); } bool tree_rm (zmq::radix_tree_t &tree_, const std::string &key_) { return tree_.rm (reinterpret_cast<const unsigned char *> (key_.data ()), key_.size ()); } bool tree_check (zmq::radix_tree_t &tree_, const std::string &key_) { return tree_.check (reinterpret_cast<const unsigned char *> (key_.data ()), key_.size ()); } void test_empty () { zmq::radix_tree_t tree; TEST_ASSERT_TRUE (tree.size () == 0); } void test_add_single_entry () { zmq::radix_tree_t tree; TEST_ASSERT_TRUE (tree_add (tree, "foo")); } void test_add_same_entry_twice () { zmq::radix_tree_t tree; TEST_ASSERT_TRUE (tree_add (tree, "test")); TEST_ASSERT_FALSE (tree_add (tree, "test")); } void test_rm_when_empty () { zmq::radix_tree_t tree; TEST_ASSERT_FALSE (tree_rm (tree, "test")); } void test_rm_single_entry () { zmq::radix_tree_t tree; tree_add (tree, "temporary"); TEST_ASSERT_TRUE (tree_rm (tree, "temporary")); } void test_rm_unique_entry_twice () { zmq::radix_tree_t tree; tree_add (tree, "test"); TEST_ASSERT_TRUE (tree_rm (tree, "test")); TEST_ASSERT_FALSE (tree_rm (tree, "test")); } void test_rm_duplicate_entry () { zmq::radix_tree_t tree; tree_add (tree, "test"); tree_add (tree, "test"); TEST_ASSERT_FALSE (tree_rm (tree, "test")); TEST_ASSERT_TRUE (tree_rm (tree, "test")); } void test_rm_common_prefix () { zmq::radix_tree_t tree; tree_add (tree, "checkpoint"); tree_add (tree, "checklist"); TEST_ASSERT_FALSE (tree_rm (tree, "check")); } void test_rm_common_prefix_entry () { zmq::radix_tree_t tree; tree_add (tree, "checkpoint"); tree_add (tree, "checklist"); tree_add (tree, "check"); TEST_ASSERT_TRUE (tree_rm (tree, "check")); } void test_rm_null_entry () { zmq::radix_tree_t tree; tree_add (tree, ""); TEST_ASSERT_TRUE (tree_rm (tree, "")); } void test_check_empty () { zmq::radix_tree_t tree; TEST_ASSERT_FALSE (tree_check (tree, "foo")); } void test_check_added_entry () { zmq::radix_tree_t tree; tree_add (tree, "entry"); TEST_ASSERT_TRUE (tree_check (tree, "entry")); } void test_check_common_prefix () { zmq::radix_tree_t tree; tree_add (tree, "introduce"); tree_add (tree, "introspect"); TEST_ASSERT_FALSE (tree_check (tree, "intro")); } void test_check_prefix () { zmq::radix_tree_t tree; tree_add (tree, "toasted"); TEST_ASSERT_FALSE (tree_check (tree, "toast")); TEST_ASSERT_FALSE (tree_check (tree, "toaste")); TEST_ASSERT_FALSE (tree_check (tree, "toaster")); } void test_check_nonexistent_entry () { zmq::radix_tree_t tree; tree_add (tree, "red"); TEST_ASSERT_FALSE (tree_check (tree, "blue")); } void test_check_query_longer_than_entry () { zmq::radix_tree_t tree; tree_add (tree, "foo"); TEST_ASSERT_TRUE (tree_check (tree, "foobar")); } void test_check_null_entry_added () { zmq::radix_tree_t tree; tree_add (tree, ""); TEST_ASSERT_TRUE (tree_check (tree, "all queries return true")); } void test_size () { zmq::radix_tree_t tree; // Adapted from the example on wikipedia. std::vector<std::string> keys; keys.push_back ("tester"); keys.push_back ("water"); keys.push_back ("slow"); keys.push_back ("slower"); keys.push_back ("test"); keys.push_back ("team"); keys.push_back ("toast"); for (size_t i = 0; i < keys.size (); ++i) TEST_ASSERT_TRUE (tree_add (tree, keys[i])); TEST_ASSERT_TRUE (tree.size () == keys.size ()); for (size_t i = 0; i < keys.size (); ++i) TEST_ASSERT_FALSE (tree_add (tree, keys[i])); TEST_ASSERT_TRUE (tree.size () == 2 * keys.size ()); for (size_t i = 0; i < keys.size (); ++i) TEST_ASSERT_FALSE (tree_rm (tree, keys[i])); TEST_ASSERT_TRUE (tree.size () == keys.size ()); for (size_t i = 0; i < keys.size (); ++i) TEST_ASSERT_TRUE (tree_rm (tree, keys[i])); TEST_ASSERT_TRUE (tree.size () == 0); } void return_key (unsigned char *data_, size_t size_, void *arg_) { std::vector<std::string> *vec = reinterpret_cast<std::vector<std::string> *> (arg_); std::string key; for (size_t i = 0; i < size_; ++i) key.push_back (static_cast<char> (data_[i])); vec->push_back (key); } void test_apply () { zmq::radix_tree_t tree; std::set<std::string> keys; keys.insert ("tester"); keys.insert ("water"); keys.insert ("slow"); keys.insert ("slower"); keys.insert ("test"); keys.insert ("team"); keys.insert ("toast"); const std::set<std::string>::iterator end = keys.end (); for (std::set<std::string>::iterator it = keys.begin (); it != end; ++it) tree_add (tree, *it); std::vector<std::string> *vec = new std::vector<std::string> (); tree.apply (return_key, static_cast<void *> (vec)); for (size_t i = 0; i < vec->size (); ++i) TEST_ASSERT_TRUE (keys.count ((*vec)[i]) > 0); delete vec; } int main (void) { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_empty); RUN_TEST (test_add_single_entry); RUN_TEST (test_add_same_entry_twice); RUN_TEST (test_rm_when_empty); RUN_TEST (test_rm_single_entry); RUN_TEST (test_rm_unique_entry_twice); RUN_TEST (test_rm_duplicate_entry); RUN_TEST (test_rm_common_prefix); RUN_TEST (test_rm_common_prefix_entry); RUN_TEST (test_rm_null_entry); RUN_TEST (test_check_empty); RUN_TEST (test_check_added_entry); RUN_TEST (test_check_common_prefix); RUN_TEST (test_check_prefix); RUN_TEST (test_check_nonexistent_entry); RUN_TEST (test_check_query_longer_than_entry); RUN_TEST (test_check_null_entry_added); RUN_TEST (test_size); RUN_TEST (test_apply); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_radix_tree.cpp
C++
gpl-3.0
6,306
/* SPDX-License-Identifier: MPL-2.0 */ #ifndef __UNITTEST_RESOLVER_COMMON_INCLUDED__ #define __UNITTEST_RESOLVER_COMMON_INCLUDED__ #include <ip_resolver.hpp> #include <string.h> // Attempt a resolution and test the results. // // On windows we can receive an IPv4 address even when an IPv6 is requested, if // we're in this situation then we compare to 'expected_addr_v4_failover_' // instead. void validate_address (int family, const zmq::ip_addr_t *addr_, const char *expected_addr_, uint16_t expected_port_ = 0, uint16_t expected_zone_ = 0, const char *expected_addr_v4_failover_ = NULL) { #if defined ZMQ_HAVE_WINDOWS if (family == AF_INET6 && expected_addr_v4_failover_ != NULL && addr_->family () == AF_INET) { // We've requested an IPv6 but the system gave us an IPv4, use the // failover address family = AF_INET; expected_addr_ = expected_addr_v4_failover_; } #else (void) expected_addr_v4_failover_; #endif TEST_ASSERT_EQUAL (family, addr_->family ()); if (family == AF_INET6) { struct in6_addr expected_addr; const sockaddr_in6 *ip6_addr = &addr_->ipv6; TEST_ASSERT_EQUAL ( 1, test_inet_pton (AF_INET6, expected_addr_, &expected_addr)); int neq = memcmp (&ip6_addr->sin6_addr, &expected_addr, sizeof (expected_addr_)); TEST_ASSERT_EQUAL (0, neq); TEST_ASSERT_EQUAL (htons (expected_port_), ip6_addr->sin6_port); TEST_ASSERT_EQUAL (expected_zone_, ip6_addr->sin6_scope_id); } else { struct in_addr expected_addr; const sockaddr_in *ip4_addr = &addr_->ipv4; TEST_ASSERT_EQUAL ( 1, test_inet_pton (AF_INET, expected_addr_, &expected_addr)); TEST_ASSERT_EQUAL (expected_addr.s_addr, ip4_addr->sin_addr.s_addr); TEST_ASSERT_EQUAL (htons (expected_port_), ip4_addr->sin_port); } } #endif // __UNITTEST_RESOLVER_COMMON_INCLUDED__
sophomore_public/libzmq
unittests/unittest_resolver_common.hpp
C++
gpl-3.0
2,076
/* SPDX-License-Identifier: MPL-2.0 */ #include <unity.h> #include "../tests/testutil.hpp" #include "../unittests/unittest_resolver_common.hpp" #include <ip.hpp> #include <udp_address.hpp> void setUp () { } void tearDown () { } // Test an UDP address resolution. If 'dest_addr_' is NULL assume the // resolution is supposed to fail. static void test_resolve (bool bind_, int family_, const char *name_, const char *target_addr_, uint16_t expected_port_, const char *bind_addr_, bool multicast_) { if (family_ == AF_INET6 && !is_ipv6_available ()) { TEST_IGNORE_MESSAGE ("ipv6 is not available"); } zmq::udp_address_t addr; int rc = addr.resolve (name_, bind_, family_ == AF_INET6); if (target_addr_ == NULL) { TEST_ASSERT_EQUAL (-1, rc); TEST_ASSERT_EQUAL (EINVAL, errno); return; } TEST_ASSERT_EQUAL (0, rc); TEST_ASSERT_EQUAL (multicast_, addr.is_mcast ()); if (bind_addr_ == NULL) { // Bind ANY if (family_ == AF_INET) { bind_addr_ = "0.0.0.0"; } else { bind_addr_ = "::"; } } validate_address (family_, addr.target_addr (), target_addr_, expected_port_); validate_address (family_, addr.bind_addr (), bind_addr_, expected_port_); } static void test_resolve_bind (int family_, const char *name_, const char *dest_addr_, uint16_t expected_port_ = 0, const char *bind_addr_ = NULL, bool multicast_ = false) { test_resolve (true, family_, name_, dest_addr_, expected_port_, bind_addr_, multicast_); } static void test_resolve_connect (int family_, const char *name_, const char *dest_addr_, uint16_t expected_port_ = 0, const char *bind_addr_ = NULL, bool multicast_ = false) { test_resolve (false, family_, name_, dest_addr_, expected_port_, bind_addr_, multicast_); } static void test_resolve_ipv4_simple () { test_resolve_connect (AF_INET, "127.0.0.1:5555", "127.0.0.1", 5555); } static void test_resolve_ipv6_simple () { test_resolve_connect (AF_INET6, "[::1]:123", "::1", 123); } static void test_resolve_ipv4_bind () { test_resolve_bind (AF_INET, "127.0.0.1:5555", "127.0.0.1", 5555, "127.0.0.1"); } static void test_resolve_ipv6_bind () { test_resolve_bind (AF_INET6, "[abcd::1234:1]:5555", "abcd::1234:1", 5555, "abcd::1234:1"); } static void test_resolve_ipv4_bind_any () { test_resolve_bind (AF_INET, "*:*", "0.0.0.0", 0, "0.0.0.0"); } static void test_resolve_ipv6_bind_any () { test_resolve_bind (AF_INET6, "*:*", "::", 0, "::"); } static void test_resolve_ipv4_bind_anyport () { test_resolve_bind (AF_INET, "127.0.0.1:*", "127.0.0.1", 0, "127.0.0.1"); } static void test_resolve_ipv6_bind_anyport () { test_resolve_bind (AF_INET6, "[1:2:3:4::5]:*", "1:2:3:4::5", 0, "1:2:3:4::5"); } static void test_resolve_ipv4_bind_any_port () { test_resolve_bind (AF_INET, "*:5555", "0.0.0.0", 5555, "0.0.0.0"); } static void test_resolve_ipv6_bind_any_port () { test_resolve_bind (AF_INET6, "*:5555", "::", 5555, "::"); } static void test_resolve_ipv4_connect_any () { // Cannot use wildcard for connection test_resolve_connect (AF_INET, "*:5555", NULL); } static void test_resolve_ipv6_connect_any () { // Cannot use wildcard for connection test_resolve_connect (AF_INET6, "*:5555", NULL); } static void test_resolve_ipv4_connect_anyport () { test_resolve_connect (AF_INET, "127.0.0.1:*", NULL); } static void test_resolve_ipv6_connect_anyport () { test_resolve_connect (AF_INET6, "[::1]:*", NULL); } static void test_resolve_ipv4_connect_port0 () { test_resolve_connect (AF_INET, "127.0.0.1:0", "127.0.0.1", 0); } static void test_resolve_ipv6_connect_port0 () { test_resolve_connect (AF_INET6, "[2000:abcd::1]:0", "2000:abcd::1", 0); } static void test_resolve_ipv4_bind_mcast () { test_resolve_bind (AF_INET, "239.0.0.1:1234", "239.0.0.1", 1234, "0.0.0.0", true); } static void test_resolve_ipv6_bind_mcast () { test_resolve_bind (AF_INET6, "[ff00::1]:1234", "ff00::1", 1234, "::", true); } static void test_resolve_ipv4_connect_mcast () { test_resolve_connect (AF_INET, "239.0.0.1:2222", "239.0.0.1", 2222, NULL, true); } static void test_resolve_ipv6_connect_mcast () { test_resolve_connect (AF_INET6, "[ff00::1]:2222", "ff00::1", 2222, NULL, true); } static void test_resolve_ipv4_mcast_src_bind () { test_resolve_bind (AF_INET, "127.0.0.1;230.2.8.12:5555", "230.2.8.12", 5555, "127.0.0.1", true); } static void test_resolve_ipv6_mcast_src_bind () { if (!is_ipv6_available ()) { TEST_IGNORE_MESSAGE ("ipv6 is not available"); } zmq::udp_address_t addr; int rc = addr.resolve ("[::1];[ffab::4]:5555", true, true); // For the time being this fails because we only support binding multicast // by interface name, not interface IP TEST_ASSERT_EQUAL (-1, rc); TEST_ASSERT_EQUAL (ENODEV, errno); } static void test_resolve_ipv4_mcast_src_bind_any () { test_resolve_bind (AF_INET, "*;230.2.8.12:5555", "230.2.8.12", 5555, "0.0.0.0", true); } static void test_resolve_ipv6_mcast_src_bind_any () { test_resolve_bind (AF_INET6, "*;[ffff::]:5555", "ffff::", 5555, "::", true); } static void test_resolve_ipv4_mcast_src_connect () { test_resolve_connect (AF_INET, "8.9.10.11;230.2.8.12:5555", "230.2.8.12", 5555, "8.9.10.11", true); } static void test_resolve_ipv6_mcast_src_connect () { if (!is_ipv6_available ()) { TEST_IGNORE_MESSAGE ("ipv6 is not available"); } zmq::udp_address_t addr; int rc = addr.resolve ("[1:2:3::4];[ff01::1]:5555", false, true); // For the time being this fails because we only support binding multicast // by interface name, not interface IP TEST_ASSERT_EQUAL (-1, rc); TEST_ASSERT_EQUAL (ENODEV, errno); } static void test_resolve_ipv4_mcast_src_connect_any () { test_resolve_connect (AF_INET, "*;230.2.8.12:5555", "230.2.8.12", 5555, "0.0.0.0", true); } static void test_resolve_ipv6_mcast_src_connect_any () { test_resolve_connect (AF_INET6, "*;[ff10::1]:5555", "ff10::1", 5555, "::", true); } static void test_resolve_ipv4_mcast_src_bind_bad () { test_resolve_bind (AF_INET, "127.0.0.1;1.2.3.4:5555", NULL); } static void test_resolve_ipv6_mcast_src_bind_bad () { test_resolve_bind (AF_INET6, "[::1];[fe00::1]:5555", NULL); } static void test_resolve_ipv4_mcast_src_connect_bad () { test_resolve_connect (AF_INET, "127.0.0.1;1.2.3.4:5555", NULL); } static void test_resolve_ipv6_mcast_src_connect_bad () { test_resolve_connect (AF_INET6, "[::1];[fe00:1]:5555", NULL); } int main (void) { zmq::initialize_network (); setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_resolve_ipv4_simple); RUN_TEST (test_resolve_ipv6_simple); RUN_TEST (test_resolve_ipv4_bind); RUN_TEST (test_resolve_ipv6_bind); RUN_TEST (test_resolve_ipv4_bind_any); RUN_TEST (test_resolve_ipv6_bind_any); RUN_TEST (test_resolve_ipv4_bind_anyport); RUN_TEST (test_resolve_ipv6_bind_anyport); RUN_TEST (test_resolve_ipv4_bind_any_port); RUN_TEST (test_resolve_ipv6_bind_any_port); RUN_TEST (test_resolve_ipv4_connect_any); RUN_TEST (test_resolve_ipv6_connect_any); RUN_TEST (test_resolve_ipv4_connect_anyport); RUN_TEST (test_resolve_ipv6_connect_anyport); RUN_TEST (test_resolve_ipv4_connect_port0); RUN_TEST (test_resolve_ipv6_connect_port0); RUN_TEST (test_resolve_ipv4_bind_mcast); RUN_TEST (test_resolve_ipv6_bind_mcast); RUN_TEST (test_resolve_ipv4_connect_mcast); RUN_TEST (test_resolve_ipv6_connect_mcast); RUN_TEST (test_resolve_ipv4_mcast_src_bind); RUN_TEST (test_resolve_ipv6_mcast_src_bind); RUN_TEST (test_resolve_ipv4_mcast_src_bind_any); RUN_TEST (test_resolve_ipv6_mcast_src_bind_any); RUN_TEST (test_resolve_ipv4_mcast_src_connect); RUN_TEST (test_resolve_ipv6_mcast_src_connect); RUN_TEST (test_resolve_ipv4_mcast_src_connect_any); RUN_TEST (test_resolve_ipv6_mcast_src_connect_any); RUN_TEST (test_resolve_ipv4_mcast_src_bind_bad); RUN_TEST (test_resolve_ipv6_mcast_src_bind_bad); RUN_TEST (test_resolve_ipv4_mcast_src_connect_bad); RUN_TEST (test_resolve_ipv6_mcast_src_connect_bad); zmq::shutdown_network (); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_udp_address.cpp
C++
gpl-3.0
9,127
/* SPDX-License-Identifier: MPL-2.0 */ #include "../tests/testutil.hpp" #include <ypipe.hpp> #include <unity.h> void setUp () { } void tearDown () { } void test_create () { zmq::ypipe_t<int, 1> ypipe; } void test_check_read_empty () { zmq::ypipe_t<int, 1> ypipe; TEST_ASSERT_FALSE (ypipe.check_read ()); } void test_read_empty () { zmq::ypipe_t<int, 1> ypipe; int read_value = -1; TEST_ASSERT_FALSE (ypipe.read (&read_value)); TEST_ASSERT_EQUAL (-1, read_value); } void test_write_complete_and_check_read_and_read () { const int value = 42; zmq::ypipe_t<int, 1> ypipe; ypipe.write (value, false); TEST_ASSERT_FALSE (ypipe.check_read ()); int read_value = -1; TEST_ASSERT_FALSE (ypipe.read (&read_value)); TEST_ASSERT_EQUAL_INT (-1, read_value); } void test_write_complete_and_flush_and_check_read_and_read () { const int value = 42; zmq::ypipe_t<int, 1> ypipe; ypipe.write (value, false); ypipe.flush (); TEST_ASSERT_TRUE (ypipe.check_read ()); int read_value = -1; TEST_ASSERT_TRUE (ypipe.read (&read_value)); TEST_ASSERT_EQUAL_INT (value, read_value); } int main (void) { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_create); RUN_TEST (test_check_read_empty); RUN_TEST (test_read_empty); RUN_TEST (test_write_complete_and_check_read_and_read); RUN_TEST (test_write_complete_and_flush_and_check_read_and_read); return UNITY_END (); }
sophomore_public/libzmq
unittests/unittest_ypipe.cpp
C++
gpl-3.0
1,480
#!/bin/sh # # This script extracts the 0MQ version from include/zmq.h, which is the master # location for this information. # if [ ! -f include/zmq.h ]; then echo "version.sh: error: include/zmq.h does not exist" 1>&2 exit 1 fi MAJOR=`grep -E '^#define +ZMQ_VERSION_MAJOR +[0-9]+$' include/zmq.h` MINOR=`grep -E '^#define +ZMQ_VERSION_MINOR +[0-9]+$' include/zmq.h` PATCH=`grep -E '^#define +ZMQ_VERSION_PATCH +[0-9]+$' include/zmq.h` if [ -z "$MAJOR" -o -z "$MINOR" -o -z "$PATCH" ]; then echo "version.sh: error: could not extract version from include/zmq.h" 1>&2 exit 1 fi MAJOR=`echo $MAJOR | awk '{ print $3 }'` MINOR=`echo $MINOR | awk '{ print $3 }'` PATCH=`echo $PATCH | awk '{ print $3 }'` echo $MAJOR.$MINOR.$PATCH | tr -d '\n'
sophomore_public/libzmq
version.sh
Shell
gpl-3.0
755
############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### #*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain
Tirem12/rjw
.gitattributes
Git
mit
2,518
## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. # User-specific files *.suo *.user *.userosscache *.sln.docstates *.csproj.user # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ Assemblies/ 1.1/Assemblies/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # DNX project.lock.json project.fragment.lock.json artifacts/ *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted #*.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignoreable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings node_modules/ orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc /Archived /MyTo-Do.txt /LL_post.txt /creditsnew.txt /Assemblies/UnityEngine.UI.dll /Assemblies/UnityEngine.dll /Assemblies/TextMeshPro-1.0.55.56.0b11.dll /Assemblies/NVorbis.dll /Assemblies/NAudio.dll /Assemblies/HugsLib.dll /Assemblies/Assembly-CSharp.dll /Assemblies/Assembly-CSharp-firstpass.dll /Assemblies/0Harmony.dll /RimJobWorld.Main.sln *.csproj /.gitignore
Tirem12/rjw
.gitignore
Git
mit
4,715
<?xml version="1.0" encoding="utf-8"?> <ModMetaData> <name>RimJobWorld</name> <author>Ed86</author> <url>https://gitgud.io/Ed86/rjw</url> <supportedVersions> <li>1.1</li> </supportedVersions> <packageId>rim.job.world</packageId> <modDependencies> <li> <packageId>brrainz.harmony</packageId> <displayName>Harmony</displayName> <steamWorkshopUrl>steam://url/CommunityFilePage/2009463077</steamWorkshopUrl> <downloadUrl>https://github.com/pardeike/HarmonyRimWorld/releases/latest</downloadUrl> </li> <li> <packageId>UnlimitedHugs.HugsLib</packageId> <displayName>HugsLib</displayName> <downloadUrl>https://github.com/UnlimitedHugs/RimworldHugsLib/releases/latest</downloadUrl> <steamWorkshopUrl>steam://url/CommunityFilePage/818773962</steamWorkshopUrl> </li> </modDependencies> <loadAfter> <li>UnlimitedHugs.HugsLib</li> <li>brrainz.harmony</li> </loadAfter> <incompatibleWith> <li>Dalrae.GaramRaceAddon</li> <li>IGNI.LostForest</li> </incompatibleWith> <description> M for Mature Load mod at bottom of mod list: Harmony Core HugsLib ++Mods RimJobWorld RJW mods and patches Support dev: https://www.patreon.com/Ed86 Forum: https://www.loverslab.com/files/file/7257-rimjobworld/ Discord: https://discord.gg/CXwHhv8 </description> </ModMetaData>
Tirem12/rjw
About/About.xml
XML
mit
1,307
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Manifest> <identifier>RimJobWorld</identifier> <version>4.3.1</version> <dependencies> <li>HugsLib</li> </dependencies> <incompatibleWith /> <loadAfter> <li>HugsLib</li> </loadAfter> <suggests> </suggests> <manifestUri>https://gitgud.io/Ed86/rjw/raw/master/About/Manifest.xml</manifestUri> <downloadUri>https://gitgud.io/Ed86/rjw</downloadUri> </Manifest>
Tirem12/rjw
About/Manifest.xml
XML
mit
427
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.BackstoryDef> <defName>rjw_childC</defName> <baseDescription>[PAWN_nameDef] was born in civil settlement.</baseDescription> <title>Child</title> <titleShort>Child</titleShort> <slot>Childhood</slot> <categoryName>Civil</categoryName> </rjw.BackstoryDef> <rjw.BackstoryDef> <defName>rjw_childT</defName> <baseDescription>[PAWN_nameDef] was born in a tribe.</baseDescription> <title>Child</title> <titleShort>Child</titleShort> <slot>Childhood</slot> <categoryName>Tribal</categoryName> </rjw.BackstoryDef> </Defs>
Tirem12/rjw
Defs/BackstoryDefs/BackstoryDefs.xml
XML
mit
595
<?xml version="1.0" encoding="utf-8" ?> <Defs> <BodyPartDef> <defName>Genitals</defName> <label>genitals</label> <hitPoints>12</hitPoints> <frostbiteVulnerability>0.01</frostbiteVulnerability> <skinCovered>true</skinCovered> <solid>false</solid> <canSuggestAmputation>false</canSuggestAmputation> <bleedRate>1.0</bleedRate> <tags> <li>RJW_Fertility</li> </tags> </BodyPartDef> <BodyPartDef> <defName>Chest</defName> <label>chest</label> <hitPoints>24</hitPoints> <frostbiteVulnerability>0.01</frostbiteVulnerability> <skinCovered>true</skinCovered> <solid>false</solid> <canSuggestAmputation>false</canSuggestAmputation> <bleedRate>1.0</bleedRate> </BodyPartDef> <BodyPartDef> <defName>Anus</defName> <label>anus</label> <hitPoints>8</hitPoints> <frostbiteVulnerability>0.01</frostbiteVulnerability> <skinCovered>true</skinCovered> <solid>false</solid> <canSuggestAmputation>false</canSuggestAmputation> <bleedRate>1.0</bleedRate> </BodyPartDef> </Defs>
Tirem12/rjw
Defs/BodyPartDefs/BodyParts_Humanlike.xml
XML
mit
1,017
<?xml version="1.0" encoding="utf-8" ?> <Defs> <BodyPartDef> <defName>MechGenitals</defName> <label>mechanoid implanter</label> <hitPoints>20</hitPoints> <skinCovered>true</skinCovered> <solid>true</solid> <canSuggestAmputation>false</canSuggestAmputation> <bleedRate>0</bleedRate> <frostbiteVulnerability>0.0</frostbiteVulnerability> <tags> <li>RJW_Fertility</li> </tags> </BodyPartDef> </Defs>
Tirem12/rjw
Defs/BodyPartDefs/BodyParts_Mech.xml
XML
mit
424
<?xml version="1.0" encoding="utf-8" ?> <Defs> <BodyPartTagDef> <defName>RJW_Fertility</defName> <label>fertility_source</label> <description>Neccessary for reproduction</description> <vital>false</vital> </BodyPartTagDef> </Defs>
Tirem12/rjw
Defs/BodyPartTagDefs/BodyPartTags_FertilitySource.xml
XML
mit
242
<?xml version="1.0" encoding="utf-8" ?> <Defs> <DamageDef> <defName>ViralDamage</defName> <workerClass>DamageWorker_AddInjury</workerClass> <label>viral damage</label> <externalViolence>false</externalViolence> <deathMessage>{0} has died of a disease.</deathMessage> <hediff>VirusPerma</hediff> <hediffSkin>VirusPerma</hediffSkin> <hediffSolid>VirusPerma</hediffSolid> <makesBlood>false</makesBlood> <harmAllLayersUntilOutside>false</harmAllLayersUntilOutside> </DamageDef> </Defs>
Tirem12/rjw
Defs/DamageDefs/Damage_Viral.xml
XML
mit
503
<?xml version="1.0" encoding="utf-8" ?> <Defs> <ThingDef ParentName="MakeableDrugBase"> <defName>Aphrodisiac</defName> <label>Aphrodisiac drug</label> <description>A smokable drug made from humpshroom.</description> <graphicData> <texPath>Things/Item/Drug/Penoxycyline</texPath> <graphicClass>Graphic_StackCount</graphicClass> </graphicData> <rotatable>false</rotatable> <statBases> <WorkToMake>450</WorkToMake> <MarketValue>50</MarketValue> <Mass>0.05</Mass> <DeteriorationRate>6</DeteriorationRate> <Flammability>1.3</Flammability> </statBases> <techLevel>Medieval</techLevel> <ingestible> <foodType>Plant, Processed</foodType> <joyKind>Chemical</joyKind> <joy>0.80</joy> <baseIngestTicks>720</baseIngestTicks> <nurseable>true</nurseable> <drugCategory>Social</drugCategory> <ingestSound>Ingest_Smoke</ingestSound> <ingestEffect>Smoke_Joint</ingestEffect> <ingestEffectEat>EatVegetarian</ingestEffectEat> <ingestHoldOffsetStanding> <northDefault> <offset>(0.27,0,0.08)</offset> <behind>true</behind> </northDefault> <east> <offset>(0.45,0,0.08)</offset> </east> <south> <offset>(0.27,0,0.08)</offset> </south> <west> <offset>(-0.50,0,0.08)</offset> <flip>true</flip> </west> </ingestHoldOffsetStanding> <ingestHoldUsesTable>false</ingestHoldUsesTable> <ingestCommandString>Smoke {0}</ingestCommandString> <ingestReportString>Smoking {0}.</ingestReportString> <ingestReportStringEat>Consuming {0}.</ingestReportStringEat> <useEatingSpeedStat>false</useEatingSpeedStat> <outcomeDoers> <li Class="IngestionOutcomeDoer_GiveHediff"> <hediffDef>HumpShroomEffect</hediffDef> <severity>0.6</severity> <toleranceChemical>HumpShroom</toleranceChemical> </li> <li Class="IngestionOutcomeDoer_GiveHediff"> <hediffDef>HumpShroomTolerance</hediffDef> <severity>0.042</severity> <divideByBodySize>true</divideByBodySize> </li> <li Class="IngestionOutcomeDoer_OffsetNeed"> <need>Sex</need> <offset>-0.5</offset> </li> </outcomeDoers> </ingestible> <recipeMaker> <recipeUsers> <li>CraftingSpot</li> <li>DrugLab</li> </recipeUsers> <workSpeedStat>DrugCookingSpeed</workSpeedStat> <workSkill>Cooking</workSkill> </recipeMaker> <costList> <HumpShroom>4</HumpShroom> </costList> <comps> <li Class="CompProperties_Drug"> <chemical>HumpShroom</chemical> <addictiveness>0.030</addictiveness> <minToleranceToAddict>0.15</minToleranceToAddict> <existingAddictionSeverityOffset>0.1</existingAddictionSeverityOffset> <needLevelOffset>1</needLevelOffset> <listOrder>30</listOrder> </li> </comps> </ThingDef> </Defs>
Tirem12/rjw
Defs/Drugs/Aphrodisiac.xml
XML
mit
2,782
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!--As usual stolen from CnP--> <ThingDef ParentName="MakeableDrugPillBase"> <defName>RJW_Contraceptive</defName> <label>Contraception pills</label> <description>Deliver severe hit to fertility for one quadrum.</description> <graphicData> <texPath>Things/Item/Contraceptive</texPath> <graphicClass>Graphic_StackCount</graphicClass> </graphicData> <rotatable>false</rotatable> <statBases> <WorkToMake>120</WorkToMake> <MarketValue>15</MarketValue> <Mass>0.05</Mass> </statBases> <techLevel>Industrial</techLevel> <ingestible> <drugCategory>Medical</drugCategory> <outcomeDoers> <li Class="IngestionOutcomeDoer_GiveHediff"> <hediffDef>RJW_Contraceptive</hediffDef> <severity>1.0</severity> </li> </outcomeDoers> </ingestible> <recipeMaker> <researchPrerequisite>DrugProduction</researchPrerequisite> <recipeUsers> <li>DrugLab</li> </recipeUsers> </recipeMaker> <costList> <MedicineHerbal>1</MedicineHerbal> </costList> <comps> <li Class="CompProperties_Drug"> <addictiveness>0</addictiveness> <listOrder>1000</listOrder> <overdoseSeverityOffset> <min>0.08</min> <max>0.14</max> </overdoseSeverityOffset> </li> </comps> </ThingDef> <HediffDef> <defName>RJW_Contraceptive</defName> <hediffClass>HediffWithComps</hediffClass> <label>contraceptive</label> <description>Contraception pills deliver severe hit to fertility for one quadrum.</description> <defaultLabelColor>(0.75, 0.75, 1.0)</defaultLabelColor> <isBad>false</isBad> <comps> <!-- Disappears after a season's time --> <li Class="HediffCompProperties_Disappears"> <disappearsAfterTicks> <min>900000</min> <max>900000</max> </disappearsAfterTicks> </li> </comps> <stages> <li> <label>Contracepted</label> <capMods> <li> <capacity>RJW_Fertility</capacity> <setMax>0.1</setMax> </li> </capMods> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/Drugs/Contraceptive.xml
XML
mit
2,050
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!--As usual stolen from CnP--> <ThingDef ParentName="MakeableDrugPillBase"> <defName>RJW_FertPill</defName> <label>Hyperfertility pills</label> <description>Enhances fertility for 48 hours. Also works as a mild aphrodisiac.</description> <graphicData> <texPath>Things/Item/FertPill</texPath> <graphicClass>Graphic_StackCount</graphicClass> </graphicData> <rotatable>false</rotatable> <statBases> <WorkToMake>120</WorkToMake> <MarketValue>15</MarketValue> <Mass>0.05</Mass> </statBases> <techLevel>Industrial</techLevel> <ingestible> <drugCategory>Medical</drugCategory> <outcomeDoers> <li Class="IngestionOutcomeDoer_GiveHediff"> <hediffDef>RJW_FertPill</hediffDef> <severity>1.0</severity> </li> <li Class="IngestionOutcomeDoer_OffsetNeed"> <need>Sex</need> <offset>-0.25</offset> </li> </outcomeDoers> </ingestible> <recipeMaker> <researchPrerequisite>DrugProduction</researchPrerequisite> <recipeUsers> <li>DrugLab</li> </recipeUsers> </recipeMaker> <costList> <MedicineHerbal>1</MedicineHerbal> <HumpShroom>1</HumpShroom> </costList> <comps> <li Class="CompProperties_Drug"> <addictiveness>0</addictiveness> <listOrder>1000</listOrder> <overdoseSeverityOffset> <min>0.08</min> <max>0.14</max> </overdoseSeverityOffset> </li> </comps> </ThingDef> <HediffDef> <defName>RJW_FertPill</defName> <hediffClass>HediffWithComps</hediffClass> <label>fertpill</label> <description>Enhanced fertility. A mild aphrodisiac.</description> <defaultLabelColor>(0.75, 0.75, 1.0)</defaultLabelColor> <isBad>false</isBad> <comps> <!-- Disappears after 2 days time --> <li Class="HediffCompProperties_Disappears"> <disappearsAfterTicks> <min>120000</min> <max>120000</max> </disappearsAfterTicks> </li> </comps> <stages> <li> <label>Hyperfertility</label> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>4</offset> </li> </capMods> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/Drugs/FertPill.xml
XML
mit
2,150
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Plant --> <ThingDef ParentName="CavePlantBase"> <defName>PlantHumpShroom</defName> <label>humpshroom shroom</label> <description>Thick shroom with tough flesh, thick juice and smooth soft skin. Exhibits aphrodisiac effects when consumed.</description> <statBases> <MaxHitPoints>85</MaxHitPoints> <Beauty>2</Beauty> <Nutrition>0.15</Nutrition> <MeditationFocusStrength>1.0</MeditationFocusStrength> </statBases> <graphicData> <texPath>Things/Item/Humpshroom/Humpshroom</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <selectable>true</selectable> <pathCost>10</pathCost> <plant> <fertilityMin>0.01</fertilityMin> <fertilitySensitivity>0.25</fertilitySensitivity> <growDays>15.00</growDays> <harvestTag>Standard</harvestTag> <harvestedThingDef>HumpShroom</harvestedThingDef> <harvestYield>2</harvestYield> <sowMinSkill>4</sowMinSkill> <sowTags> <li>Hydroponic</li> </sowTags> <topWindExposure>0.1</topWindExposure> <visualSizeRange>0.4~0.7</visualSizeRange> </plant> <comps> <li Class="CompProperties_Glower"> <glowRadius>1</glowRadius> <glowColor>(255,105,180,0)</glowColor> </li> <li Class="CompProperties_MeditationFocus"> <statDef>MeditationFocusStrength</statDef> <focusTypes> <li>Sex</li> </focusTypes> </li> </comps> </ThingDef> <!--Consumable item--> <ThingDef ParentName="DrugBase"> <defName>HumpShroom</defName> <label>Hump shroom</label> <description>A shroom with tough flesh, thick juice and smooth soft skin. Exhibits aphrodisiac effects when consumed.</description> <tradeability>Sellable</tradeability> <socialPropernessMatters>true</socialPropernessMatters> <tickerType>Rare</tickerType> <graphicData> <texPath>Things/Item/Humpshroom/HumpshroomCollected</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <thingCategories> <li>PlantFoodRaw</li> </thingCategories> <statBases> <MarketValue>10</MarketValue> <Mass>0.1</Mass> <DeteriorationRate>4</DeteriorationRate> <Nutrition>0.40</Nutrition> </statBases> <techLevel>Neolithic</techLevel> <ingestible> <baseIngestTicks>100</baseIngestTicks> <chairSearchRadius>4</chairSearchRadius> <preferability>RawTasty</preferability> <tasteThought></tasteThought> <foodType>VegetableOrFruit</foodType> <maxNumToIngestAtOnce>1</maxNumToIngestAtOnce> <optimalityOffsetHumanlikes>-6</optimalityOffsetHumanlikes> <optimalityOffsetFeedingAnimals>-11</optimalityOffsetFeedingAnimals> <ingestEffect>EatVegetarian</ingestEffect> <ingestSound>RawVegetable_Eat</ingestSound> <joy>0.5</joy> <joyKind>Social</joyKind> <nurseable>true</nurseable> <drugCategory>Social</drugCategory> <outcomeDoers> <li Class="IngestionOutcomeDoer_GiveHediff"> <hediffDef>HumpShroomEffect</hediffDef> <severity>0.50</severity> <toleranceChemical>HumpShroom</toleranceChemical> </li> <li Class="IngestionOutcomeDoer_GiveHediff"> <hediffDef>HumpShroomTolerance</hediffDef> <severity>0.032</severity> <divideByBodySize>true</divideByBodySize> </li> <li Class="IngestionOutcomeDoer_OffsetNeed"> <need>Sex</need> <offset>-0.5</offset> </li> <li Class="IngestionOutcomeDoer_OffsetPsyfocus"> <offset>1.0</offset> </li> </outcomeDoers> </ingestible> <comps> <li Class="CompProperties_Forbiddable" /> <li Class="CompProperties_Ingredients" /> <li Class="CompProperties_Rottable"> <daysToRotStart>30</daysToRotStart> <rotDestroys>true</rotDestroys> </li> <li Class="CompProperties_Drug"> <chemical>HumpShroom</chemical> <addictiveness>0.050</addictiveness> <minToleranceToAddict>0.15</minToleranceToAddict> <existingAddictionSeverityOffset>0.1</existingAddictionSeverityOffset> <needLevelOffset>1</needLevelOffset> <listOrder>30</listOrder> </li> </comps> </ThingDef> <HediffDef> <defName>HumpShroomEffect</defName> <hediffClass>HediffWithComps</hediffClass> <label>Induced libido</label> <description>Hump shroom aphrodisiac effects.</description> <defaultLabelColor>(1,0,0.5)</defaultLabelColor> <scenarioCanAdd>true</scenarioCanAdd> <maxSeverity>1.0</maxSeverity> <comps> <li Class="HediffCompProperties_SeverityPerDay"> <severityPerDay>-0.9</severityPerDay> </li> </comps> <stages> <li> <restFallFactor>1.33</restFallFactor> <statOffsets> <SexFrequency>2</SexFrequency> </statOffsets> </li> </stages> </HediffDef> <ThoughtDef> <defName>HumpShroomEffect</defName> <workerClass>ThoughtWorker_Hediff</workerClass> <hediff>HumpShroomEffect</hediff> <validWhileDespawned>true</validWhileDespawned> <stages> <li> <label>Humpshroom aftertaste</label> <description>Tastes funny.</description> <baseMoodEffect>1</baseMoodEffect> </li> </stages> </ThoughtDef> <!-- Ambrosia addiction --> <ChemicalDef> <defName>HumpShroom</defName> <label>humpshroom</label> <addictionHediff>HumpShroomAddiction</addictionHediff> <toleranceHediff>HumpShroomTolerance</toleranceHediff> <onGeneratedAddictedToleranceChance>0.8</onGeneratedAddictedToleranceChance> </ChemicalDef> <NeedDef ParentName="DrugAddictionNeedBase"> <defName>Chemical_HumpShroom</defName> <needClass>Need_Chemical</needClass> <label>humpshroom</label> <description>Person is now hooked on shrooms. Without them, their bedroom performance may fall.</description> <listPriority>10</listPriority> </NeedDef> <HediffDef ParentName="DrugToleranceBase"> <defName>HumpShroomTolerance</defName> <label>humpshroom tolerance</label> <description>Hump shroom effects tolerance.</description> <isBad>false</isBad> <comps> <li Class="HediffCompProperties_SeverityPerDay"> <severityPerDay>-0.020</severityPerDay> </li> <li Class="HediffCompProperties_DrugEffectFactor"> <chemical>HumpShroom</chemical> </li> </comps> </HediffDef> <HediffDef ParentName="AddictionBase"> <defName>HumpShroomAddiction</defName> <hediffClass>Hediff_Addiction</hediffClass> <label>humpshroom addiction</label> <description>Hump shroom effects addiction.</description> <causesNeed>Chemical_HumpShroom</causesNeed> <comps> <li Class="HediffCompProperties_SeverityPerDay"> <severityPerDay>-0.1</severityPerDay> </li> </comps> <stages> <li> </li> <li> <label>withdrawal</label> </li> </stages> </HediffDef> <ThoughtDef> <defName>HumpShroomWithdrawal</defName> <workerClass>ThoughtWorker_Hediff</workerClass> <hediff>HumpShroomAddiction</hediff> <validWhileDespawned>true</validWhileDespawned> <stages> <li> <visible>false</visible> </li> <li> <label>humpshroom withdrawal</label> <description>I just feel nothing down there.</description> <baseMoodEffect>-5</baseMoodEffect> </li> </stages> </ThoughtDef> </Defs>
Tirem12/rjw
Defs/Drugs/Humpshroom.xml
XML
mit
7,033
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef Name="BondageBase" Abstract="True"> <hediffClass>Hediff</hediffClass> <defaultLabelColor>(0.5, 0.5, 0.9)</defaultLabelColor> <makesSickThought>false</makesSickThought> <isBad>false</isBad> <tendable>false</tendable> <scenarioCanAdd>false</scenarioCanAdd> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>Armbinder</defName> <label>armbinder</label> <labelNoun>an armbinder</labelNoun> <description>An armbinder. A restraint device that binds the arms behind the body.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>ChastityBelt</defName> <label>chastity belt</label> <labelNoun>a chastity belt</labelNoun> <description>A chastity belt. Restricts access to the vagina and anus from its lover, and its wearer.</description> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>ChastityCage</defName> <label>chastity cage</label> <labelNoun>a chastity cage</labelNoun> <description>A chastity cage. Restricts access to the penis from its lover, and its wearer.</description> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>Chains</defName> <label>chains</label> <labelNoun>chains</labelNoun> <description>A series of chains that restrict its wearer.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.35</setMax> </li> <li> <capacity>Moving</capacity> <setMax>0.35</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>Yoke</defName> <label>yoke</label> <labelNoun>a yoke</labelNoun> <description>Keeps the arms and head of the wearer locked relative to their body in a raised-arm position.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>BoundHands</defName> <label>bound hands</label> <labelNoun>bound hands</labelNoun> <description>Bound hands.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>BoundLegs</defName> <label>bound legs</label> <labelNoun>bound legs</labelNoun> <description>Bound legs.</description> <stages> <li> <capMods> <li> <capacity>Moving</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>ClosedGag</defName> <label>closed gag</label> <labelNoun>a closed gag</labelNoun> <description>A closed gag that prevents its wearer from speaking.</description> <stages> <li> <capMods> <li> <capacity>Talking</capacity> <setMax>0.00</setMax> </li> <li> <capacity>Eating</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>OpenGag</defName> <label>open gag</label> <labelNoun>an open gag</labelNoun> <description>An open gag that only allows its wearer to mutter incomprehensibly.</description> <stages> <li> <capMods> <li> <capacity>Talking</capacity> <setMax>0.00</setMax> </li> <li> <capacity>Eating</capacity> <offset>-0.25</offset> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>RJW_Restraints</defName> <label>Restraints</label> <labelNoun>restraints</labelNoun> <description>A set of restraints.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> <li> <capacity>Moving</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <!-- insect restraints --> <HediffDef ParentName="BondageBase"> <defName>RJW_Cocoon</defName> <hediffClass>rjw.Cocoon</hediffClass> <label>Cocoon</label> <labelNoun>A cocoon</labelNoun> <description>A cocoon that tends to its host until ready to procreate.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> <li> <capacity>Moving</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Bondage.xml
XML
mit
4,796
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!--master hediff adding up the smaller semen splatches--> <HediffDef> <defName>Hediff_Bukkake</defName> <hediffClass>rjw.Hediff_Bukkake</hediffClass> <label>Bukkake</label> <description>Ejaculated onto.</description> <makesSickThought>false</makesSickThought> <initialSeverity>0.01</initialSeverity> <maxSeverity>1</maxSeverity> <!--<injuryProps>--> <!--<canMerge>true</canMerge>--><!-- this might not even be required--> <!--</injuryProps>--> <!--<scenarioCanAdd>true</scenarioCanAdd>--> <isBad>false</isBad> <tendable>false</tendable> <stages> <li> <label>minor</label> <becomeVisible>false</becomeVisible> </li> <li> <minSeverity>0.3</minSeverity> <label>little</label> <statOffsets> <Vulnerability>0.2</Vulnerability> <SocialImpact>-0.1</SocialImpact> </statOffsets> </li> <li> <minSeverity>0.6</minSeverity> <label>extensive</label> <statOffsets> <Vulnerability>0.3</Vulnerability> <SocialImpact>-0.3</SocialImpact> </statOffsets> </li> <li> <minSeverity>0.8</minSeverity> <label>full</label> <statOffsets> <Vulnerability>-0.1</Vulnerability><!--pawns prefer victims not being completely drenched--> <SocialImpact>-0.5</SocialImpact> </statOffsets> </li> </stages> </HediffDef> <HediffDef Name="Hediff_Semen"> <hediffClass>rjw.Hediff_Semen</hediffClass> <defName>Hediff_Semen</defName> <label>semen</label> <labelNoun>semen</labelNoun> <description>Semen.</description> <labelNounPretty>semen on {1}</labelNounPretty> <defaultLabelColor>(0.95,0.95,0.95)</defaultLabelColor> <isBad>false</isBad> <tendable>false</tendable> <makesSickThought>false</makesSickThought> <makesAlert>false</makesAlert> <maxSeverity>1</maxSeverity> <initialSeverity>0.001</initialSeverity> <injuryProps> <canMerge>true</canMerge> </injuryProps> <stages> <li> <label>little</label> </li> <li> <minSeverity>0.25</minSeverity> <label>some</label> </li> <li> <minSeverity>0.5</minSeverity> <label>dripping</label> </li> <li> <minSeverity>0.8</minSeverity> <label>drenched</label> </li> </stages> <comps> <li Class="HediffCompProperties_SelfHeal"> <!--0.01*100*1800/60.0000--> <healIntervalTicksStanding>1800</healIntervalTicksStanding><!-- 1 day = 60.000 ticks --> <healAmount>0.01</healAmount><!--dries by itself, completely drying from 1.0 to 0.0 takes ~72h--> </li> </comps> </HediffDef> <HediffDef ParentName="Hediff_Semen"> <defName>Hediff_InsectSpunk</defName> <description>Insect spunk.</description> <label>insect spunk</label> <labelNoun>insect spunk</labelNoun> <labelNounPretty>insect spunk on {1}</labelNounPretty> <defaultLabelColor>(0.6,0.83,0.35)</defaultLabelColor> </HediffDef> <HediffDef ParentName="Hediff_Semen"> <defName>Hediff_MechaFluids</defName> <description>Mechanoid fluids.</description> <label>mechanoid fluids</label> <labelNoun>mechanoid fluids</labelNoun> <labelNounPretty>mecha fluids on {1}</labelNounPretty> <defaultLabelColor>(0.37,0.71,0.82)</defaultLabelColor> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Bukkake.xml
XML
mit
3,249
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!--Pawns with ovi's plant egg.--> <rjw.HediffDef_InsectEgg Name="RJW_ImplantEgg" Abstract="True"> <defName>RJW_InsectEgg</defName> <label>Egg</label> <hediffClass>rjw.Hediff_InsectEgg</hediffClass> <description>Parasitic egg(s) that enter the host's body and feeds off their nutrients until ready to hatch. Just be glad they don't hatch by bursting out of your chest.</description> <defaultLabelColor>(0.8, 0.8, 0.35)</defaultLabelColor> <initialSeverity>0.01</initialSeverity> <isBad>false</isBad> <tendable>false</tendable> <eggsize>1</eggsize> <!--eggsize 1 = 100%, 0 - can hold unlimited eggs, up to 100 eggs per sex--> <selffertilized>false</selffertilized> <!--egg will be implanted fertilized--> <stages> <li> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> </capMods> </li> <li> <minSeverity>0.02</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.02</offset> </li> </capMods> </li> <li> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <minSeverity>0.10</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.10</offset> </li> </capMods> </li> <li> <minSeverity>0.15</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> </capMods> </li> <li> <minSeverity>0.20</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.20</offset> </li> </capMods> </li> <li> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <minSeverity>0.30</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.30</offset> </li> </capMods> </li> <li> <minSeverity>0.40</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.40</offset> </li> </capMods> </li> <li> <minSeverity>0.50</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.50</offset> </li> </capMods> </li> <li> <minSeverity>0.75</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.75</offset> </li> </capMods> </li> <li> <minSeverity>0.9</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-1.0</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_InsectEgg> <!--Placeholder egg/unsupported/any races--> <rjw.HediffDef_InsectEgg ParentName="RJW_ImplantEgg"> <defName>RJW_UnknownEgg</defName> <parentDef>Unknown</parentDef> <!-- exact match--> </rjw.HediffDef_InsectEgg> <!--vanilla insects, can fertilize each other --> <rjw.HediffDef_InsectEgg ParentName="RJW_ImplantEgg"> <defName>RJW_InsectHiveEgg</defName> <parentDefs> <!-- partial match of pawn.kindDef.defName--> <li>Megascarab</li> <li>Spelopede</li> <li>Megaspider</li> <li>Queen</li> <!-- Better infestations--> </parentDefs> </rjw.HediffDef_InsectEgg> <!--Used for JobDriver_RapeEnemyByMech. Mechs implant things when success rape.--> <rjw.HediffDef_MechImplants Name="RJW_ImplantMech" Abstract="True"> <hediffClass>rjw.Hediff_MechImplants</hediffClass> <defaultLabelColor>(0.8, 0.8, 0.35)</defaultLabelColor> <initialSeverity>0.1</initialSeverity> <parentDefs> <li>Mech_Lancer</li> <li>Mech_Scyther</li> <li>Mech_Centipede</li> <li>Mech_Pikeman</li> </parentDefs> <tendable>false</tendable> </rjw.HediffDef_MechImplants> <rjw.HediffDef_MechImplants ParentName="RJW_ImplantMech"> <hediffClass>rjw.Hediff_MicroComputer</hediffClass> <defName>RJW_MicroComputer</defName> <tendable>false</tendable> <isBad>true</isBad> <label>MicroComputer</label> <description>A small computer that enters a host through one of their orifices. Can analyze vital signs and location data, and relay that information back to its implanter.</description> <minEventInterval>30000</minEventInterval> <maxEventInterval>90000</maxEventInterval> <randomHediffDefs> <li>RJW_Orgasm</li> <li>TransportCums</li> <li>TransportEggs</li> </randomHediffDefs> </rjw.HediffDef_MechImplants> <rjw.HediffDef_EnemyImplants> <defName>Parasite</defName> <hediffClass>rjw.Hediff_Parasite</hediffClass> <defaultLabelColor>(0.7, 1.0, 0.7)</defaultLabelColor> <initialSeverity>0.1</initialSeverity> <isBad>true</isBad> <label>pregnant</label> <description>A organism that lives inside a host and feeds off its nutrients, giving the host severe discomfort.</description> <comps> <li Class="HediffCompProperties_Discoverable"> <sendLetterWhenDiscovered>true</sendLetterWhenDiscovered> <discoverLetterLabel>{0} Parasited</discoverLetterLabel> <discoverLetterText>{0} is parasited!</discoverLetterText> </li> </comps> <stages> <li> <label>early-stage-hidden</label> <becomeVisible>false</becomeVisible> <vomitMtbDays>2.5</vomitMtbDays> </li> <li> <label>middle-stage</label> <minSeverity>0.333</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> </capMods> </li> <li> <label>late-stage</label> <minSeverity>0.666</minSeverity> <vomitMtbDays>2</vomitMtbDays> <capMods> <li> <capacity>Moving</capacity> <offset>-0.30</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_EnemyImplants> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_EnemyImplants.xml
XML
mit
5,873
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>FeelingBroken</defName> <hediffClass>rjw.AdvancedHediffWithComps</hediffClass> <label>Feeling broken</label> <defaultLabelColor>(0.5, 0.7, 0.45)</defaultLabelColor> <makesSickThought>false</makesSickThought> <initialSeverity>0.025</initialSeverity> <maxSeverity>1</maxSeverity> <scenarioCanAdd>true</scenarioCanAdd> <tendable>false</tendable> <description>Mind broken. No longer capable of emotion.</description> <isBad>false</isBad> <comps> <li Class="rjw.HediffCompProperties_FeelingBrokenSeverityReduce"> <severityPerDayReduce> <points> <li>(1,0)</li> <li>(10,-0.025)</li> </points> </severityPerDayReduce> </li> <li Class="rjw.HediffCompProperties_FeelingBrokenSeverityIncrease"> <severityPerDayIncrease> <points> <li>(0,0.1)</li> <li>(1,1)</li> </points> </severityPerDayIncrease> </li> </comps> <stages> <li> <label>early-stage</label> <becomeVisible>false</becomeVisible> </li> <li> <label>in a trance</label> <minSeverity>0.1</minSeverity> <painOffset>0.1</painOffset> <capMods> <li> <capacity>Consciousness</capacity> <postFactor>0.8</postFactor> </li> </capMods> </li> <li> <label>broken</label> <minSeverity>0.3</minSeverity> <painOffset>0.05</painOffset> <capMods> <li> <capacity>Consciousness</capacity> <postFactor>0.7</postFactor> </li> </capMods> <statOffsets> <Vulnerability>0.25</Vulnerability> </statOffsets> </li> <li> <label>Extremely broken</label> <minSeverity>0.5</minSeverity> <painOffset>-0.1</painOffset> <capMods> <li> <capacity>Consciousness</capacity> <postFactor>0.6</postFactor> </li> </capMods> <statOffsets> <Vulnerability>0.5</Vulnerability> </statOffsets> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_FeelingBroken.xml
XML
mit
1,987
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>RJW_IUD</defName> <label>IUD</label> <hediffClass>HediffWithComps</hediffClass> <description>A small copper device inserted into the womb that prevents pregnancy.</description> <defaultLabelColor>(0.8, 0.8, 0.35)</defaultLabelColor> <isBad>false</isBad> <scenarioCanAdd>true</scenarioCanAdd> <stages> <li> <capMods> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef> <defName>IncreasedFertility</defName> <label>Increased fertility</label> <description>Increased fertility, for baby making.</description> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(0.7, 1.0, 0.7)</defaultLabelColor> <isBad>false</isBad> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <becomeVisible>false</becomeVisible> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> </capMods> </li> </stages> </HediffDef> <HediffDef> <defName>DecreasedFertility</defName> <label>Low fertility</label> <description>Low fertility.</description> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(1, 0.2, 0.2)</defaultLabelColor> <isBad>false</isBad> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <becomeVisible>false</becomeVisible> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>-0.5</offset> <setMax>0.25</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef> <defName>ImpregnationBlocker</defName> <label>Archotech pregnancy blocker</label> <description>A complex device that prevents the ovaries from producing eggs.</description> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(0.7, 1.0, 0.7)</defaultLabelColor> <isBad>false</isBad> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <becomeVisible>true</becomeVisible> <capMods> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef> <defName>FertilityEnhancer</defName> <label>Archotech fertility enhancer</label> <description>A complex device that increases the likelihood of pregnancy.</description> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(0.7, 1.0, 0.7)</defaultLabelColor> <isBad>false</isBad> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <becomeVisible>true</becomeVisible> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> </capMods> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Fertility.xml
XML
mit
2,764
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- <HediffDef> <defName>RJW_lactating</defName> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(1, 0.41, 0.81)</defaultLabelColor> <isBad>false</isBad> <label>lactating</label> <comps> <li Class="HediffCompProperties_Disappears"> <disappearsAfterTicks> <min>2750000</min> <max>3000000</max> </disappearsAfterTicks> </li> </comps> </HediffDef> --> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Lactating.xml
XML
mit
460
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>RJW_Orgasm</defName> <hediffClass>rjw.Hediff_Orgasm</hediffClass> <label>Orgasm</label> <defaultLabelColor>(0.5, 0.7, 0.45)</defaultLabelColor> <makesSickThought>false</makesSickThought> <initialSeverity>0.1</initialSeverity> <maxSeverity>1</maxSeverity> <scenarioCanAdd>false</scenarioCanAdd> <tendable>false</tendable> <description>"Ohh, yeahh, hah, hnnh, OH!"</description> <comps> <li Class="HediffCompProperties_SeverityPerDay"> <severityPerDay>-1</severityPerDay> </li> </comps> <stages> <li> <label>Slightly</label> <capMods> <li> <capacity>Consciousness</capacity> <postFactor>0.9</postFactor> </li> <li> <capacity>Manipulation</capacity> <postFactor>0.9</postFactor> </li> <li> <capacity>Moving</capacity> <postFactor>0.9</postFactor> </li> <li> <capacity>Talking</capacity> <postFactor>0.9</postFactor> </li> </capMods> <statOffsets> <Vulnerability>0.2</Vulnerability> </statOffsets> </li> <li> <label>Heavy</label> <minSeverity>0.2</minSeverity> <capMods> <li> <capacity>Consciousness</capacity> <postFactor>0.65</postFactor> </li> <li> <capacity>Manipulation</capacity> <postFactor>0.65</postFactor> </li> <li> <capacity>Moving</capacity> <postFactor>0.65</postFactor> </li> <li> <capacity>Talking</capacity> <postFactor>0.65</postFactor> </li> </capMods> <statOffsets> <Vulnerability>0.3</Vulnerability> </statOffsets> </li> <li> <label>Extremely</label> <minSeverity>0.501</minSeverity> <capMods> <li> <capacity>Consciousness</capacity> <postFactor>0.3</postFactor> </li> <li> <capacity>Manipulation</capacity> <postFactor>0.65</postFactor> </li> <li> <capacity>Moving</capacity> <postFactor>0.2</postFactor> </li> <li> <capacity>Talking</capacity> <postFactor>0.5</postFactor> </li> </capMods> <statOffsets> <Vulnerability>0.6</Vulnerability> </statOffsets> </li> </stages> </HediffDef> <HediffDef> <defName>TransportCums</defName> <hediffClass>rjw.Hediff_TransportCums</hediffClass> <description>Cumming inside.</description> <isBad>false</isBad> </HediffDef> <HediffDef> <defName>TransportEggs</defName> <hediffClass>rjw.Hediff_TransportEggs</hediffClass> <description>Laying egg inside.</description> <isBad>false</isBad> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_MCEvents.xml
XML
mit
2,659
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Severity will be set to equal (1.0 - blood_filtration) in xxx.update_std_effects --> <HediffDef> <defName>Immunodeficiency</defName> <hediffClass>rjw.Hediff_ID</hediffClass> <defaultLabelColor>(1.0, 0.0, 0.0)</defaultLabelColor> <label>Immunodeficiency</label> <makesSickThought>false</makesSickThought> <minSeverity>0.600</minSeverity> <description>Very susceptible to disease.</description> <initialSeverity>0.601</initialSeverity> <tendable>false</tendable> <stages> <li> <minSeverity>0.60</minSeverity> <label>minor</label> <restFallFactor>1.10</restFallFactor> <capMods> <li> <capacity>Consciousness</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <minSeverity>0.75</minSeverity> <label>major</label> <restFallFactor>1.30</restFallFactor> <capMods> <li> <capacity>Consciousness</capacity> <offset>-0.10</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.15</offset> </li> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> </capMods> </li> <li> <minSeverity>0.90</minSeverity> <label>extreme</label> <restFallFactor>1.50</restFallFactor> <capMods> <li> <capacity>Consciousness</capacity> <offset>-0.15</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.30</offset> </li> <li> <capacity>Moving</capacity> <offset>-0.30</offset> </li> </capMods> </li> </stages> </HediffDef> <HediffDef> <defName>VirusPerma</defName> <hediffClass>Hediff_Injury</hediffClass> <tendable>false</tendable> <displayWound>true</displayWound> <chanceToCauseNoPain>1.0</chanceToCauseNoPain> <description>Viral damage.</description> <label>viral damage</label> <comps> <li Class="HediffCompProperties_GetsPermanent"> <permanentLabel>permanent viral damage</permanentLabel> <instantlyPermanentLabel>permanent viral damage</instantlyPermanentLabel> </li> </comps> <injuryProps> <painPerSeverity>0.0</painPerSeverity> <averagePainPerSeverityPermanent>0.0</averagePainPerSeverityPermanent> <destroyedLabel>Destroyed by disease</destroyedLabel> <destroyedOutLabel>Destroyed by disease</destroyedOutLabel> </injuryProps> </HediffDef> <HediffDef ParentName="AddedBodyPartBase"> <defName>PegArm</defName> <label>peg arm</label> <labelNoun>a peg arm</labelNoun> <description>A peg arm.</description> <addedPartProps> <solid>true</solid> <partEfficiency>0.00</partEfficiency> <betterThanNatural>false</betterThanNatural> </addedPartProps> <spawnThingOnRemoved>WoodLog</spawnThingOnRemoved> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Other.xml
XML
mit
2,817
<?xml version="1.0" encoding="utf-8" ?> <!--all pregnancies--> <Defs> <HediffDef Name="RJW_pregnancy_template" Abstract="True"> <label>Pregnant</label> <description>Baby in the oven.</description> <defaultLabelColor>(1, 0.41, 0.81)</defaultLabelColor> <initialSeverity>0.001</initialSeverity> <isBad>false</isBad> <stages> <li> <label>early-stage</label> <vomitMtbDays>2.5</vomitMtbDays> </li> <li> <label>middle-stage</label> <minSeverity>0.333</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> </capMods> </li> <li> <label>late-stage</label> <minSeverity>0.666</minSeverity> <vomitMtbDays>2</vomitMtbDays> <capMods> <li> <capacity>Moving</capacity> <offset>-0.30</offset> </li> </capMods> </li> <li> <label>having contractions</label> <minSeverity>0.98</minSeverity> <painOffset>0.3</painOffset> <capMods> <li> <capacity>Moving</capacity> <setMax>0.0</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="RJW_pregnancy_template"> <defName>RJW_pregnancy</defName> <hediffClass>rjw.Hediff_BasePregnancy</hediffClass> </HediffDef> <HediffDef ParentName="RJW_pregnancy_template"> <defName>RJW_pregnancy_beast</defName> <hediffClass>rjw.Hediff_BestialPregnancy</hediffClass> </HediffDef> <HediffDef ParentName="RJW_pregnancy_template"> <defName>RJW_pregnancy_mech</defName> <hediffClass>rjw.Hediff_MechanoidPregnancy</hediffClass> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Pregnancy.xml
XML
mit
1,606
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.HediffDef_PartBase Name="RJW_PrivatePartBase" Abstract="True"> <!-- <everVisible>true</everVisible> --> <FluidType></FluidType> <!-- string, make into something else, someday, maybe--> <isBad>false</isBad> <comps> <li Class="rjw.CompProperties_HediffBodyPart" /> </comps> <priceImpact>false</priceImpact> </rjw.HediffDef_PartBase> <!-- natural parts (purist love) --> <rjw.HediffDef_PartBase ParentName="RJW_PrivatePartBase" Name="NaturalPrivatePartBase" Abstract="True"> <hediffClass>rjw.Hediff_PartBaseNatural</hediffClass> <defaultLabelColor>(0.5, 0.8, 0.5)</defaultLabelColor> <addedPartProps> <solid>false</solid> <partEfficiency>1.0</partEfficiency> </addedPartProps> </rjw.HediffDef_PartBase> <!-- Humanlikes should generally spawn with severity between 0 and 1. The higher sizes are for growth or ultra endowed races. --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBase" Name="NaturalPrivatePartPenis" Abstract="True"> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Small</label> <minSeverity>0.20</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.40</minSeverity> </li> <li> <label>Large</label> <minSeverity>0.60</minSeverity> </li> <li> <label>Huge</label> <minSeverity>0.80</minSeverity> <capMods> <li> <!-- A few inches extra isn't really going to make a difference, but it's funny so... --> <capacity>Moving</capacity> <offset>-0.05</offset> </li> </capMods> </li> <!-- Humanlikes should generally spawn with severity between 0 and 1. The higher sizes are for growth or ultra endowed races. --> <li> <label>Towering</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.10</offset> </li> </capMods> </li> </stages> <modExtensions> <li Class="rjw.PartSizeExtension"> <density>1.0</density> <lengths> <li>0</li> <li>5.0</li> <li>10.0</li> <!-- 14.0 is average --> <li>18.0</li> <li>25.0</li> <li>35.0</li> <!-- World record (Cabrera doesn't count). --> <!-- Can always add more later. --> </lengths> <girths> <li>0</li> <li>5.0</li> <li>10.0</li> <!-- 12.0 is average --> <li>13.0</li> <li>17.0</li> <li>21.0</li> </girths> </li> </modExtensions> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBase" Name="NaturalPrivatePartVagina" Abstract="True"> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Tight</label> <minSeverity>0.20</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.40</minSeverity> </li> <li> <label>Accomodating</label> <minSeverity>0.60</minSeverity> </li> <li> <label>Cavernous</label> <minSeverity>0.80</minSeverity> </li> <li> <label>Abyssal</label> <minSeverity>1.01</minSeverity> </li> </stages> <modExtensions> <li Class="rjw.PartSizeExtension"> <!-- Matches with penis sizes. --> <lengths> <li>0</li> <li>5.0</li> <li>10.0</li> <!-- 14.0 is average --> <li>18.0</li> <li>25.0</li> <li>35.0</li> <!-- World record (Cabrera doesn't count). --> </lengths> <girths> <li>0</li> <li>5.0</li> <li>10.0</li> <!-- 12.0 is average --> <li>13.0</li> <li>17.0</li> <li>21.0</li> </girths> </li> </modExtensions> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBase" Name="NaturalPrivatePartAnus" Abstract="True"> <FluidType></FluidType> <DefaultBodyPart>Anus</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Tight</label> <minSeverity>0.20</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.40</minSeverity> </li> <li> <label>Accomodating</label> <minSeverity>0.60</minSeverity> </li> <li> <label>Cavernous</label> <minSeverity>0.80</minSeverity> </li> <li> <label>Abyssal</label> <minSeverity>1.01</minSeverity> </li> </stages> <modExtensions> <li Class="rjw.PartSizeExtension"> <!-- Matches with penis sizes. --> <girths> <li>0</li> <li>5.0</li> <li>10.0</li> <!-- 12.0 is average --> <li>13.0</li> <li>17.0</li> <li>21.0</li> </girths> </li> </modExtensions> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBase" Name="NaturalPrivatePartBreast" Abstract="True"> <FluidType>Milk</FluidType> <DefaultBodyPart>Chest</DefaultBodyPart> <stages> <li> <!-- Male breast stage--> <label>Nipples</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Tiny</label> <minSeverity>0.02</minSeverity> </li> <li> <label>Small</label> <minSeverity>0.20</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.40</minSeverity> </li> <li> <label>Large</label> <minSeverity>0.60</minSeverity> </li> <li> <label>Huge</label> <minSeverity>0.80</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <label>Enormous</label> <minSeverity>1.00</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.10</offset> </li> </capMods> </li> <!-- Humanlikes should generally spawn with severity between 0 and 1. The higher sizes are for growth or ultra endowed races. --> <li> <label>Massive</label> <minSeverity>1.2</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> </capMods> </li> <li> <label>Gargantuan</label> <minSeverity>1.4</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.20</offset> </li> </capMods> </li> <li> <label>Colossal</label> <minSeverity>1.6</minSeverity> <!-- Norma Stitz is obviously not crippled, but she's not winning any races either. --> <capMods> <li> <capacity>Moving</capacity> <offset>-0.25</offset> </li> </capMods> </li> </stages> <modExtensions> <li Class="rjw.PartSizeExtension"> <!-- Human standard would be 1.0. Leave out for no weight display. --> <density>1.0</density> <cupSizes> <li>0</li> <li>1</li> <li>2</li> <li>4</li> <!-- DD is average --> <li>7</li> <li>11</li> <li>15</li> <li>19</li> <li>25</li> <li>31</li> <!-- World record is 2x this. Can always add more later. --> </cupSizes> </li> </modExtensions> </rjw.HediffDef_PartBase> <!-- artifical parts (transhumanist love) --> <rjw.HediffDef_PartBase ParentName="RJW_PrivatePartBase" Name="ArtificialPrivatePartBase" Abstract="True"> <hediffClass>rjw.Hediff_PartBaseArtifical</hediffClass> <defaultLabelColor>(0.5, 0.5, 0.9)</defaultLabelColor> <addedPartProps> <solid>true</solid> <partEfficiency>1.0</partEfficiency> </addedPartProps> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartBase" Name="ArtificialPrivatePartLotech" Abstract="True"> <addedPartProps> <betterThanNatural>false</betterThanNatural> </addedPartProps> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartBase" Name="ArtificialPrivatePartHitech" Abstract="True"> <addedPartProps> <betterThanNatural>true</betterThanNatural> </addedPartProps> <priceImpact>true</priceImpact> </rjw.HediffDef_PartBase> <!-- Placeholder hediffs for unsupported pawns? --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>GenericPenis</defName> <label>generic penis</label> <labelNoun>a penis</labelNoun> <description>A penis. Generic placeholder part for unsuported race.</description> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>GenericVagina</defName> <label>generic vagina</label> <labelNoun>a vagina</labelNoun> <description>A vagina. Generic placeholder part for unsuported race.</description> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartAnus"> <defName>GenericAnus</defName> <label>generic anus</label> <labelNoun>an anus</labelNoun> <description>An anus. Generic placeholder part for unsuported race.</description> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBreast"> <defName>GenericBreasts</defName> <label>generic breasts</label> <labelNoun>breasts</labelNoun> <description>A pair of breasts. Generic placeholder part for unsuported race.</description> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts.xml
XML
mit
9,245
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>HorsePenis</defName> <label>equine penis</label> <labelNoun>an equine penis</labelNoun> <description>A large horse penis. Flares out during sex.</description> <descriptionHyperlinks><ThingDef>HorsePenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HorsePenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>HorseVagina</defName> <label>equine vagina</label> <labelNoun>an equine vagina</labelNoun> <description>A mare vagina.</description> <descriptionHyperlinks><ThingDef>HorseVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HorseVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>CatPenis</defName> <label>feline penis</label> <labelNoun>a feline penis</labelNoun> <description>A spine-covered feline penis.</description> <descriptionHyperlinks><ThingDef>CatPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>CatPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>CatVagina</defName> <label>feline vagina</label> <labelNoun>a feline vagina</labelNoun> <description>A feline vagina.</description> <descriptionHyperlinks><ThingDef>CatVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>CatVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>DogPenis</defName> <label>canine penis</label> <labelNoun>a dog penis</labelNoun> <description>A bright red dog penis. The knot will expand during sex, locking its lover to their partner for a long time.</description> <descriptionHyperlinks><ThingDef>DogPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>DogPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>DogVagina</defName> <label>canine vagina</label> <labelNoun>a dog vagina</labelNoun> <description>A dog vagina.</description> <descriptionHyperlinks><ThingDef>DogVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>DogVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>DragonPenis</defName> <label>dragon penis</label> <labelNoun>a dragon penis</labelNoun> <description>A dragon penis. Has a knot that expands similarly to a dog's penis, but the ribbings on both sides takes its lover to greater heights of pleasure.</description> <descriptionHyperlinks><ThingDef>DragonPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>DragonPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>DragonVagina</defName> <label>dragon vagina</label> <labelNoun>a dragon vagina</labelNoun> <description>A dragon vagina. Has a similar texture to their outer hide.</description> <descriptionHyperlinks><ThingDef>DragonVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>DragonVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>RaccoonPenis</defName> <label>procyonine penis</label> <labelNoun>a procyonine penis</labelNoun> <description>A raccoon penis.</description> <descriptionHyperlinks><ThingDef>RaccoonPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>RaccoonPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>HemiPenis</defName> <label>hemipenis</label> <labelNoun>a hemipenis</labelNoun> <description>Twice the members for double the fun.</description> <descriptionHyperlinks><ThingDef>HemiPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HemiPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>CrocodilianPenis</defName> <label>crocodilian penis</label> <labelNoun>a crocodilian penis</labelNoun> <description>A crocodilian penis. Large and permenantly erect.</description> <descriptionHyperlinks><ThingDef>CrocodilianPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>CrocodilianPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBreast"> <defName>UdderBreasts</defName> <label>udder</label> <labelNoun>an udders</labelNoun> <description>A animal like "breasts" with 4 nipples.</description> <descriptionHyperlinks><ThingDef>UdderBreasts</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>UdderBreasts</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>NarrowVagina</defName> <label>narrow vagina</label> <labelNoun>a narrow vagina</labelNoun> <description>A tight, narrow vagina.</description> <descriptionHyperlinks><ThingDef>NarrowVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>NarrowVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>NeedlePenis</defName> <label>needle penis</label> <labelNoun>a needle penis</labelNoun> <description>A small and thin penis.</description> <descriptionHyperlinks><ThingDef>NeedlePenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>NeedlePenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>RodentVagina</defName> <label>rodent vagina</label> <labelNoun>a rodent vagina</labelNoun> <description>A rodent vagina.</description> <descriptionHyperlinks><ThingDef>RodentVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>RodentVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>RodentPenis</defName> <label>rodent penis</label> <labelNoun>a rodent penis</labelNoun> <description>A rodent penis.</description> <descriptionHyperlinks><ThingDef>RodentPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>RodentPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>CloacalPenis</defName> <label>cloacal penis</label> <labelNoun>a cloacal penis</labelNoun> <description>A cloacal penis.</description> <descriptionHyperlinks><ThingDef>CloacalPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>CloacalPenis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>CloacalVagina</defName> <label>cloacal vagina</label> <labelNoun>a cloacal vagina</labelNoun> <description>A cloacal vagina.</description> <descriptionHyperlinks><ThingDef>CloacalVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>CloacalVagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartAnus"> <defName>CloacalAnus</defName> <label>cloacal anus</label> <labelNoun>cloacal anus</labelNoun> <description>A cloacal anus.</description> <descriptionHyperlinks><ThingDef>CloacalAnus</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>CloacalAnus</spawnThingOnRemoved> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts_Animal.xml
XML
mit
7,664
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Demon privates --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>DemonTentaclePenis</defName> <label>demon tentacles</label> <labelNoun>demon tentacles</labelNoun> <description>Tentacles capable of reaching corners of the body you never thought possible.</description> <descriptionHyperlinks><ThingDef>DemonTentaclePenis</ThingDef></descriptionHyperlinks> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>DemonPenis</defName> <label>demon penis</label> <labelNoun>a demon penis</labelNoun> <description>A large, daunting mass that can cause its lovers to succumb to debauchery.</description> <descriptionHyperlinks><ThingDef>DemonPenis</ThingDef></descriptionHyperlinks> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>DemonVagina</defName> <label>demon vagina</label> <labelNoun>a demon vagina</labelNoun> <description>A tight vagina that can send its lovers to heaven.</description> <descriptionHyperlinks><ThingDef>DemonVagina</ThingDef></descriptionHyperlinks> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartAnus"> <defName>DemonAnus</defName> <label>demon anus</label> <labelNoun>a demon anus</labelNoun> <description>A demon anus.</description> <descriptionHyperlinks><ThingDef>DemonAnus</ThingDef></descriptionHyperlinks> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts_Demon.xml
XML
mit
1,523
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Regular privates --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>Penis</defName> <label>penis</label> <labelNoun>a penis</labelNoun> <description>A penis.</description> <descriptionHyperlinks><ThingDef>Penis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>Penis</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>Vagina</defName> <label>vagina</label> <labelNoun>a vagina</labelNoun> <description>A vagina.</description> <descriptionHyperlinks><ThingDef>Vagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>Vagina</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <!-- Natural anuses --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartAnus"> <defName>Anus</defName> <label>anus</label> <labelNoun>an anus</labelNoun> <description>A anus.</description> <descriptionHyperlinks><ThingDef>Anus</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>Anus</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <!-- Natural Breasts --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBreast"> <defName>Breasts</defName> <label>breasts</label> <labelNoun>a pair of breasts</labelNoun> <description>A pair of breasts.</description> <descriptionHyperlinks><ThingDef>Breasts</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>Breasts</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <!-- Natural Breasts or rather lack of --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBase"> <defName>FeaturelessChest</defName> <label>featureless chest</label> <labelNoun>a featureless chest</labelNoun> <description>a flat chest without any nipples where there should be.</description> <descriptionHyperlinks><ThingDef>FeaturelessChest</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>FeaturelessChest</spawnThingOnRemoved> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts_Human.xml
XML
mit
2,006
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Simple prosthetic privates --> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartLotech"> <hediffClass>Hediff_Implant</hediffClass> <!-- do not count it as Hediff_AddedPart for transhumanist/prostophobe --> <defName>PegDick</defName> <label>peg dick</label> <labelNoun>a peg dick</labelNoun> <description>A simple, static member.</description> <descriptionHyperlinks><ThingDef>PegDick</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>PegDick</spawnThingOnRemoved> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.03</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> <li> <label>Big</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.09</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>0</offset> </li> </capMods> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.12</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> <li> <label>Towering</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.5</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartLotech"> <defName>HydraulicPenis</defName> <label>hydraulic penis</label> <labelNoun>a hydraulic penis</labelNoun> <description>Simulating a normal penis, it can enlarge itself with hydraulics.</description> <descriptionHyperlinks><ThingDef>HydraulicPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HydraulicPenis</spawnThingOnRemoved> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.03</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Big</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.09</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.12</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Towering</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.5</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>-0.25</setMax> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartLotech"> <defName>HydraulicVagina</defName> <label>hydraulic vagina</label> <labelNoun>a hydraulic vagina</labelNoun> <description>It uses simple hydraulics to simulate the tightness of a regular vagina.</description> <descriptionHyperlinks><ThingDef>HydraulicVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HydraulicVagina</spawnThingOnRemoved> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Tight</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Loose</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Gaping</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> <li> <capacity>RJW_Fertility</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Gigantic</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>-0.25</setMax> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartLotech"> <defName>HydraulicAnus</defName> <label>hydraulic anus</label> <labelNoun>a hydraulic anus</labelNoun> <description>An anus that uses simple hydraulics to tighten.</description> <descriptionHyperlinks><ThingDef>HydraulicAnus</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HydraulicAnus</spawnThingOnRemoved> <DefaultBodyPart>Anus</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> </capMods> </li> <li> <label>Tight</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> </capMods> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> </capMods> </li> <li> <label>Loose</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> </capMods> </li> <li> <label>Gaping</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.06</offset> </li> </capMods> </li> <li> <label>Gigantic</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> <li> <capacity>RJW_Fertility</capacity> <setMax>-0.25</setMax> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartLotech"> <defName>HydraulicBreasts</defName> <label>hydraulic breasts</label> <labelNoun>a pair of hydraulic breasts</labelNoun> <description>A pair obviously unnatural implants.</description> <descriptionHyperlinks><ThingDef>HydraulicBreasts</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>HydraulicBreasts</spawnThingOnRemoved> <DefaultBodyPart>Chest</DefaultBodyPart> <stages> <li> <label>Flat</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.006</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.006</offset> </li> </capMods> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.012</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.012</offset> </li> </capMods> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.025</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.025</offset> </li> </capMods> </li> <li> <label>Large</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.1</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.1</offset> </li> </capMods> </li> <li> <label>Massive</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.4</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.4</offset> </li> </capMods> </li> <li> <label>Back-breaking</label> <minSeverity>1.5</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.8</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.8</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <!-- Bionic privates --> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>BionicPenis</defName> <label>bionic penis</label> <labelNoun>a bionic penis</labelNoun> <description>An advanced artificial penis. It uses fine-tuned pressure sensors and PID control loops to analyze its lover's contractions. It can expand, contract and even vibrate to adapt to its lover's preferences.</description> <descriptionHyperlinks><ThingDef>BionicPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>BionicPenis</spawnThingOnRemoved> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> </li> <li> <label>Big</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> </capMods> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.02</offset> </li> </capMods> </li> <li> <label>Towering</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.25</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>BionicVagina</defName> <label>bionic vagina</label> <labelNoun>a bionic vagina</labelNoun> <description>An advanced bionic vagina. It uses internal pressure sensors to accomodate its user's size, speed.</description> <descriptionHyperlinks><ThingDef>BionicVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>BionicVagina</spawnThingOnRemoved> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Tight</label> <minSeverity>0.05</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> </li> <li> <label>Loose</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> </capMods> </li> <li> <label>Gaping</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.02</offset> </li> </capMods> </li> <li> <label>Gigantic</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.10</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>BionicAnus</defName> <label>bionic anus</label> <labelNoun>an bionic anus</labelNoun> <description>An advanced bionic anus.</description> <descriptionHyperlinks><ThingDef>BionicAnus</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>BionicAnus</spawnThingOnRemoved> <DefaultBodyPart>Anus</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Tight</label> <minSeverity>0.05</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> </li> <li> <label>Loose</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> </capMods> </li> <li> <label>Gaping</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.02</offset> </li> </capMods> </li> <li> <label>Gigantic</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.10</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>BionicBreasts</defName> <label>bionic breasts</label> <labelNoun>a bionic breasts</labelNoun> <description>An advanced bionic breasts.</description> <descriptionHyperlinks><ThingDef>BionicBreasts</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>BionicBreasts</spawnThingOnRemoved> <DefaultBodyPart>Chest</DefaultBodyPart> <stages> <li> <label>Flat</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.012</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.012</offset> </li> </capMods> </li> <li> <label>Large</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.025</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.025</offset> </li> </capMods> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <label>Massive</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.25</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.25</offset> </li> </capMods> </li> <li> <label>Back-breaking</label> <minSeverity>1.5</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.5</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.5</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> <!-- Archotech --> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>ArchotechPenis</defName> <label>archotech penis</label> <description>An archotech penis.</description> <descriptionHyperlinks><ThingDef>ArchotechPenis</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>ArchotechPenis</spawnThingOnRemoved> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Big</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>ArchotechVagina</defName> <label>archotech vagina</label> <description>An archotech vagina.</description> <descriptionHyperlinks><ThingDef>ArchotechVagina</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>ArchotechVagina</spawnThingOnRemoved> <FluidType>Cum</FluidType> <DefaultBodyPart>Genitals</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Tight</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Loose</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Gaping</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>RJW_Fertility</capacity> <offset>0.25</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>ArchotechAnus</defName> <label>archotech anus</label> <description>An archotech anus.</description> <descriptionHyperlinks><ThingDef>ArchotechAnus</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>ArchotechAnus</spawnThingOnRemoved> <DefaultBodyPart>Anus</DefaultBodyPart> <stages> <li> <label>Micro</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>0.25</offset> </li> <li> <capacity>Metabolism</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Tight</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>0.25</offset> </li> <li> <capacity>Metabolism</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>0.25</offset> </li> <li> <capacity>Metabolism</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Loose</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>0.25</offset> </li> <li> <capacity>Metabolism</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> <li> <label>Gaping</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>0.25</offset> </li> <li> <capacity>Metabolism</capacity> <offset>0.05</offset> </li> </capMods> <statOffsets> <ImmunityGainSpeed>0.05</ImmunityGainSpeed> <ToxicSensitivity>-0.05</ToxicSensitivity> </statOffsets> </li> </stages> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="ArtificialPrivatePartHitech"> <defName>ArchotechBreasts</defName> <label>archotech breasts</label> <description>A pair of archotech breasts.</description> <descriptionHyperlinks><ThingDef>ArchotechBreasts</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>ArchotechBreasts</spawnThingOnRemoved> <FluidType>Milk</FluidType> <DefaultBodyPart>Chest</DefaultBodyPart> <stages> <li> <label>Flat</label> <minSeverity>0.01</minSeverity> <capMods> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> <li> <label>Small</label> <minSeverity>0.05</minSeverity> <capMods> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.012</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.012</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> <li> <label>Large</label> <minSeverity>0.70</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.025</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.025</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> <li> <label>Huge</label> <minSeverity>0.90</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.05</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> <li> <label>Massive</label> <minSeverity>1.01</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.15</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> <li> <label>Back-breaking</label> <minSeverity>1.5</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.3</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.3</offset> </li> <li> <capacity>BloodPumping</capacity> <offset>0.2</offset> </li> </capMods> </li> </stages> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts_Implants.xml
XML
mit
27,594
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Insect privates --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>OvipositorF</defName> <label>ovipositor (Female)</label> <labelNoun>an ovipositor</labelNoun> <description>An ovipositor. Lays eggs inside host.</description> <descriptionHyperlinks><ThingDef>OvipositorF</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>OvipositorF</spawnThingOnRemoved> <produceEggs>true</produceEggs> <!-- time to produce new egg --> <minEggTick>12000</minEggTick> <maxEggTick>60000</maxEggTick> <FluidType>InsectJelly</FluidType> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>OvipositorM</defName> <label>ovipositor (Male)</label> <labelNoun>an ovipositor</labelNoun> <description>An ovipositor. Fertilizes eggs inside host.</description> <descriptionHyperlinks><ThingDef>OvipositorM</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>OvipositorM</spawnThingOnRemoved> <FluidType>InsectJelly</FluidType> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartAnus"> <defName>InsectAnus</defName> <label>insect anus</label> <labelNoun>an insect anus</labelNoun> <description>An insect anus.</description> <descriptionHyperlinks><ThingDef>InsectAnus</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>InsectAnus</spawnThingOnRemoved> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts_Insect.xml
XML
mit
1,479
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- Slime privates --> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartPenis"> <defName>SlimeTentacles</defName> <label>slime tentacles</label> <labelNoun>slime tentacles</labelNoun> <description>Slick, translucent tentacles that can conform into any shape desired.</description> <descriptionHyperlinks><ThingDef>SlimeGlob</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>SlimeGlob</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartVagina"> <defName>SlimeVagina</defName> <label>slime vagina</label> <labelNoun>slime vagina</labelNoun> <description>A slick, translucent vagina that can grow or shrink to accomodate any penis.</description> <descriptionHyperlinks><ThingDef>SlimeGlob</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>SlimeGlob</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartAnus"> <defName>SlimeAnus</defName> <label>slime anus</label> <labelNoun>a slime anus</labelNoun> <description>A slick, translucent anus that can tighten and conform to fit anything.</description> <descriptionHyperlinks><ThingDef>SlimeGlob</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>SlimeGlob</spawnThingOnRemoved> </rjw.HediffDef_PartBase> <rjw.HediffDef_PartBase ParentName="NaturalPrivatePartBreast"> <defName>SlimeBreasts</defName> <label>slime breasts</label> <labelNoun>a pair of slime breasts</labelNoun> <description>A pair of slick, translucent breasts that can grow or shrink to any desired size.</description> <descriptionHyperlinks><ThingDef>SlimeGlob</ThingDef></descriptionHyperlinks> <spawnThingOnRemoved>SlimeGlob</spawnThingOnRemoved> </rjw.HediffDef_PartBase> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/Hediffs_PrivateParts_Slime.xml
XML
mit
1,822
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.PartStagesDef> <defName>RJW_PartStages</defName> <!-- Every bra manufacturer has a slightly different scheme for bra sizes. --> <!-- This is the scheme used by Ewa Michalak, 5cm band size interval and 2.54cm cup size interval. --> <!-- Ewa Michalak sells the largest non-custom bras in the world. --> <bandSizeInterval>5</bandSizeInterval> <cupSizeInterval>2.54</cupSizeInterval> <!-- Pretend all humans have the same band size. --> <bandSizeBase>85</bandSizeBase> <cupSizeLabels> <li>-</li> <li>A</li> <li>B</li> <li>C</li> <li>D</li> <li>DD</li> <li>E</li> <li>F</li> <li>FF</li> <li>G</li> <li>GG</li> <li>H</li> <li>HH</li> <li>J</li> <li>JJ</li> <li>K</li> <li>KK</li> <li>L</li> <li>LL</li> <li>M</li> <li>MM</li> <li>N</li> <!-- Largest non-custom cup size sold by Ewa Michalak. --> <li>NN</li> <li>O</li> <li>OO</li> <li>P</li> <li>PP</li> <li>Q</li> <li>QQ</li> <li>R</li> <li>RR</li> <li>???</li> </cupSizeLabels> </rjw.PartStagesDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_PrivateParts/PartStages.xml
XML
mit
1,143
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef Name="STDBase" Abstract="True"> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(0.8, 0.8, 0.35)</defaultLabelColor> <initialSeverity>0.010</initialSeverity> </HediffDef> <HediffDef Abstract="True" ParentName="STDBase" Name="HIVBase"> <hediffClass>HediffWithComps</hediffClass> <tendable>true</tendable> <stages> <li> <minSeverity>0.000</minSeverity> <label>detectable</label> </li> <li> <minSeverity>0.100</minSeverity> <label>minor</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <minSeverity>0.200</minSeverity> <label>minor</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.10</offset> </li> </capMods> </li> <li> <minSeverity>0.300</minSeverity> <label>minor</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.15</offset> </li> </capMods> </li> <li> <minSeverity>0.400</minSeverity> <label>moderate</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.20</offset> </li> </capMods> </li> <li> <minSeverity>0.500</minSeverity> <label>major</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.30</offset> </li> </capMods> </li> <li> <minSeverity>0.600</minSeverity> <label>major</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.40</offset> </li> </capMods> </li> <li> <minSeverity>0.700</minSeverity> <label>major</label> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.50</offset> </li> </capMods> </li> <li> <minSeverity>0.800</minSeverity> <label>extreme</label> <lifeThreatening>true</lifeThreatening> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.70</offset> </li> </capMods> </li> <li> <minSeverity>0.900</minSeverity> <label>extreme</label> <lifeThreatening>true</lifeThreatening> <capMods> <li> <capacity>BloodFiltration</capacity> <offset>-0.95</offset> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="HIVBase"> <defName>AcuteHIV</defName> <label>HIV - Acute</label> <description>An immunodeficiency virus that spreads through sexual contact.</description> <makesSickThought>true</makesSickThought> <maxSeverity>1</maxSeverity> <tendable>true</tendable> <comps> <li Class="HediffCompProperties_Discoverable"> <sendLetterWhenDiscovered>false</sendLetterWhenDiscovered> </li> <li Class="HediffCompProperties_TendDuration"> <baseTendDurationHours>24</baseTendDurationHours> <!-- Daily --> <severityPerDayTended>-0.022</severityPerDayTended> </li> <li Class="HediffCompProperties_Immunizable"> <immunityPerDayNotSick>-0.060</immunityPerDayNotSick> <immunityPerDaySick>0.280</immunityPerDaySick> <severityPerDayNotImmune>0.130</severityPerDayNotImmune> <severityPerDayImmune>-0.600</severityPerDayImmune> </li> </comps> </HediffDef> <HediffDef ParentName="HIVBase"> <defName>ChronicHIV</defName> <label>HIV - Chronic</label> <description>An immunodeficiency virus that spreads through sexual contact.</description> <makesSickThought>false</makesSickThought> <minSeverity>0.001</minSeverity> <maxSeverity>1.000</maxSeverity> <tendable>true</tendable> <comps> <li Class="HediffCompProperties_Discoverable"> <sendLetterWhenDiscovered>false</sendLetterWhenDiscovered> </li> <li Class="HediffCompProperties_TendDuration"> <baseTendDurationHours>240</baseTendDurationHours> <!-- Every 10 days --> <severityPerDayTended>-0.0013</severityPerDayTended> </li> <li Class="HediffCompProperties_Immunizable"> <severityPerDayNotImmune>0.0048</severityPerDayNotImmune> </li> </comps> </HediffDef> <HediffDef ParentName="STDBase"> <defName>Herpes</defName> <label>Herpes</label> <description>Genital sores that spread through sexual contact.</description> <makesSickThought>false</makesSickThought> <minSeverity>0.001</minSeverity> <maxSeverity>0.650</maxSeverity> <tendable>true</tendable> <comps> <li Class="HediffCompProperties_Discoverable"> <sendLetterWhenDiscovered>false</sendLetterWhenDiscovered> </li> <li Class="HediffCompProperties_TendDuration"> <baseTendDurationHours>240</baseTendDurationHours> <!-- Every 10 days --> <severityPerDayTended>-0.050</severityPerDayTended> </li> <li Class="HediffCompProperties_Immunizable"> <severityPerDayNotImmune>0.035</severityPerDayNotImmune> </li> </comps> <stages> <li> <minSeverity>0.000</minSeverity> <label>minor</label> <painOffset>0.05</painOffset> </li> <li> <minSeverity>0.250</minSeverity> <label>moderate</label> <painOffset>0.10</painOffset> </li> <li> <minSeverity>0.500</minSeverity> <label>major</label> <painOffset>0.15</painOffset> </li> </stages> </HediffDef> <HediffDef ParentName="STDBase"> <defName>Warts</defName> <label>Warts</label> <description>Genital warts that spread through sexual contact.</description> <makesSickThought>false</makesSickThought> <minSeverity>0.000</minSeverity> <maxSeverity>0.650</maxSeverity> <tendable>true</tendable> <comps> <li Class="HediffCompProperties_Discoverable"> <sendLetterWhenDiscovered>false</sendLetterWhenDiscovered> </li> <li Class="HediffCompProperties_TendDuration"> <baseTendDurationHours>24</baseTendDurationHours> <!-- Everyday --> <severityPerDayTended>-0.138</severityPerDayTended> </li> <li Class="HediffCompProperties_Immunizable"> <immunityPerDayNotSick>-0.090</immunityPerDayNotSick> <immunityPerDaySick>0.165</immunityPerDaySick> <severityPerDayNotImmune>0.225</severityPerDayNotImmune> <severityPerDayImmune>-0.400</severityPerDayImmune> </li> </comps> <stages> <li> <minSeverity>0.000</minSeverity> <label>minor</label> </li> <li> <minSeverity>0.400</minSeverity> <label>major</label> </li> </stages> </HediffDef> <HediffDef ParentName="STDBase"> <defName>Syphilis</defName> <description>A bacterial infection that spreads through sexual contact.</description> <label>Syphilis</label> <makesSickThought>true</makesSickThought> <initialSeverity>0.200</initialSeverity> <minSeverity>0.000</minSeverity> <lethalSeverity>1.000</lethalSeverity> <tendable>true</tendable> <comps> <li Class="HediffCompProperties_Discoverable"> <sendLetterWhenDiscovered>false</sendLetterWhenDiscovered> </li> <li Class="HediffCompProperties_TendDuration"> <baseTendDurationHours>36</baseTendDurationHours> <!-- 2 times every 3 days --> <severityPerDayTended>-0.160</severityPerDayTended> </li> <li Class="HediffCompProperties_Immunizable"> <immunityPerDayNotSick>-0.045</immunityPerDayNotSick> <immunityPerDaySick>0.060</immunityPerDaySick> <severityPerDayNotImmune>0.080</severityPerDayNotImmune> <severityPerDayImmune>-0.240</severityPerDayImmune> </li> </comps> <stages> <li> <minSeverity>0.000</minSeverity> <label>minor</label> </li> <li> <minSeverity>0.360</minSeverity> <label>moderate</label> <capMods> <li> <capacity>Consciousness</capacity> <offset>-0.05</offset> </li> </capMods> </li> <li> <minSeverity>0.600</minSeverity> <label>major</label> <painOffset>0.05</painOffset> <capMods> <li> <capacity>Consciousness</capacity> <offset>-0.15</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.10</offset> </li> </capMods> </li> <li> <minSeverity>0.840</minSeverity> <label>extreme</label> <painOffset>0.15</painOffset> <lifeThreatening>true</lifeThreatening> <capMods> <li> <capacity>Consciousness</capacity> <offset>-0.30</offset> </li> <li> <capacity>Manipulation</capacity> <offset>-0.20</offset> </li> </capMods> </li> <li> <minSeverity>0.888</minSeverity> <label>extreme</label> <painOffset>0.18</painOffset> <lifeThreatening>true</lifeThreatening> <capMods> <li> <capacity>Consciousness</capacity> <setMax>0.50</setMax> </li> <li> <capacity>Manipulation</capacity> <offset>-0.30</offset> </li> </capMods> </li> <li> <minSeverity>0.936</minSeverity> <label>extreme</label> <painOffset>0.22</painOffset> <lifeThreatening>true</lifeThreatening> <capMods> <li> <capacity>Consciousness</capacity> <setMax>0.10</setMax> </li> <li> <capacity>Manipulation</capacity> <offset>-0.40</offset> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="MechanitesBase"> <defName>Boobitis</defName> <label>boobitis</label> <description>Boobitis is a highly contagious mechanite plague that causes permanent breast growth if left untreated. It was initialy created as a harmless glittertech "party drug" but has since mutated and spread to virtually every human colony.</description> <makesSickThought>false</makesSickThought> <stages> <li> <painOffset>0.1</painOffset> <label>subtle swelling</label> <statOffsets> <SexAbility>0.1</SexAbility> <Vulnerability>0.1</Vulnerability> </statOffsets> </li> <li> <minSeverity>0.5</minSeverity> <label>noticable swelling</label> <painOffset>0.2</painOffset> <statOffsets> <SexAbility>0.2</SexAbility> <Vulnerability>0.3</Vulnerability> </statOffsets> </li> <li> <minSeverity>0.9</minSeverity> <label>spectacular swelling</label> <painOffset>0.3</painOffset> <statOffsets> <SexAbility>0.3</SexAbility> <Vulnerability>0.5</Vulnerability> </statOffsets> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_STDs.xml
XML
mit
10,269
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>RJW_BabyState</defName> <hediffClass>rjw.Hediff_SimpleBaby</hediffClass> <label>child is growing</label> <description>A growing child.</description> <initialSeverity>0.1</initialSeverity> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <label>baby</label> <minSeverity>0.1</minSeverity> <capMods> <li> <capacity>Moving</capacity> <setMax>0</setMax> </li> <li> <capacity>Talking</capacity> <setMax>0</setMax> </li> </capMods> </li> <li> <label>toddler</label> <minSeverity>0.5</minSeverity> <capMods> <li> <capacity>Manipulation</capacity> <offset>-1.0</offset> </li> <li> <capacity>Talking</capacity> <offset>-0.5</offset> </li> <li> <capacity>Moving</capacity> <offset>-0.35</offset> </li> </capMods> </li> <li> <label>child</label> <minSeverity>0.75</minSeverity> </li> </stages> </HediffDef> <!-- This only exists separately from BabyState to get around a bug making children drop their weapons on savegame load.--> <HediffDef> <defName>RJW_NoManipulationFlag</defName> <hediffClass>HediffWithComps</hediffClass> <label>Too young to work</label> <description>Too young to work.</description> <initialSeverity>0.001</initialSeverity> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <!--<everVisible>false</everVisible>--> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.0</setMax> </li> </capMods> </li> </stages> </HediffDef> <!-- Use CnP's UnhappyBaby instead <HediffDef> <defName>RJW_UnhappyBaby</defName> <hediffClass>rjw.Hediff_SimpleUnhappyBaby</hediffClass> <label>unhappy baby</label> </HediffDef> --> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_SimpleBaby.xml
XML
mit
1,865
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef Name="rjw_parts_size_changer_base" Abstract="True"> <hediffClass>rjw.Hediff_PartsSizeChangerCE</hediffClass> <defaultLabelColor>(1, 0.41, 0.71)</defaultLabelColor> <description>Change part size to:</description> </HediffDef> <!-- For use in PC --> <!-- (broken) --> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size0</defName> <label>RJW part size set(PC)(broken):</label> <hediffClass>rjw.Hediff_PartsSizeChangerPC</hediffClass> <initialSeverity>0.01</initialSeverity> <scenarioCanAdd>true</scenarioCanAdd> <stages> <li> <label>Micro/Flat</label> <minSeverity>0.01</minSeverity> </li> <li> <label>Small/Thight</label> <minSeverity>0.05</minSeverity> </li> <li> <label>Average</label> <minSeverity>0.25</minSeverity> </li> <li> <label>Large/Loose</label> <minSeverity>0.70</minSeverity> </li> <li> <label>Huge/Gaping</label> <minSeverity>0.90</minSeverity> </li> <li> <label>Oversized</label> <minSeverity>1.01</minSeverity> </li> </stages> <comps> <li Class="HediffCompProperties_GetsPermanent"> <permanentLabel>RJW part size set</permanentLabel> </li> </comps> </HediffDef> <!-- For use in CE --> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size1</defName> <label>RJW part size set(CE): Micro/Flat</label> <initialSeverity>0.01</initialSeverity> </HediffDef> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size2</defName> <label>RJW part size set(CE): Small/Thight</label> <initialSeverity>0.05</initialSeverity> </HediffDef> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size3</defName> <label>RJW part size set(CE): Average</label> <initialSeverity>0.25</initialSeverity> </HediffDef> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size4</defName> <label>RJW part size set(CE): Large/Loose</label> <initialSeverity>0.70</initialSeverity> </HediffDef> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size5</defName> <label>RJW part size set(CE): Huge/Gaping</label> <initialSeverity>0.90</initialSeverity> </HediffDef> <HediffDef ParentName="rjw_parts_size_changer_base"> <defName>size6</defName> <label>RJW part size set(CE): Oversized</label> <initialSeverity>1.01</initialSeverity> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_SizeChanger.xml
XML
mit
2,448
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>Sterilized</defName> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(0.8, 0.8, 0.35)</defaultLabelColor> <description>Unable to reproduce.</description> <label>sterilized</label> <stages> <li> <capMods> <li> <capacity>RJW_Fertility</capacity> <setMax>0</setMax> </li> </capMods> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Sterilized.xml
XML
mit
453
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>Hediff_Submitting</defName> <label>Prostrating self</label> <hediffClass>rjw.Hediff_Submitting</hediffClass> <description>Submitting.</description> <defaultLabelColor>(1, 0.41, 0.81)</defaultLabelColor> <initialSeverity>1.0</initialSeverity> <minSeverity>1.0</minSeverity> <maxSeverity>1.0</maxSeverity> <scenarioCanAdd>false</scenarioCanAdd> <comps> <li Class="HediffCompProperties_Disappears"> <disappearsAfterTicks> <!--1 hour--> <min>2500</min> <!--2 hours--> <max>5000</max> </disappearsAfterTicks> </li> </comps> <stages> <li> <becomeVisible>true</becomeVisible> <capMods> <li> <capacity>Moving</capacity> <postFactor>0.0</postFactor> </li> </capMods> <statOffsets> <Vulnerability>0.95</Vulnerability> </statOffsets> </li> </stages> </HediffDef> <!-- prevents 10 job stacks error--> <HediffDef> <defName>Hediff_RapeEnemyCD</defName> <label>rape enemy cooldown</label> <description>"Who's next?"</description> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(1, 0.41, 0.81)</defaultLabelColor> <initialSeverity>1.0</initialSeverity> <minSeverity>1.0</minSeverity> <maxSeverity>1.0</maxSeverity> <scenarioCanAdd>false</scenarioCanAdd> <comps> <li Class="HediffCompProperties_Disappears"> <disappearsAfterTicks> <!--1 hour--> <min>2500</min> <max>2500</max> </disappearsAfterTicks> </li> </comps> <stages> <li> <becomeVisible>false</becomeVisible> </li> </stages> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Submitting.xml
XML
mit
1,658
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef Name="Sex_Change_Thoughts_Syndrome" Abstract="True"> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(1, 0.41, 0.71)</defaultLabelColor> <!--This will start from top severity and go down gradually, the code will change initial severity if needed for particular pawn--> <description>Your description could be here.</description> <initialSeverity>1.0</initialSeverity> <minSeverity>0.001</minSeverity> <maxSeverity>1.0</maxSeverity> <isBad>false</isBad> <tendable>false</tendable> <scenarioCanAdd>false</scenarioCanAdd> <comps> <li Class="HediffCompProperties_SeverityPerDay"> <severityPerDay>-0.01</severityPerDay> </li> <li Class="HediffCompProperties_Disappears"> <!--These are long but lowest stage is actually bonus mood.--> <!--The code will modify the severity so that some pawns are happy right away and others only get used to it before effect vanishes--> <disappearsAfterTicks> <!--60 days (1 year)--> <min>3600000</min> <!--1.5 years--> <max>4800000</max> </disappearsAfterTicks> </li> </comps> <stages> <li> <label>ignorance</label> <becomeVisible>false</becomeVisible> </li> <li> <label>acceptance</label> <minSeverity>0.01</minSeverity> <becomeVisible>false</becomeVisible> </li> <li> <label>saddness</label> <minSeverity>0.25</minSeverity> <becomeVisible>false</becomeVisible> </li> <li> <label>anger</label> <becomeVisible>false</becomeVisible> <minSeverity>0.4</minSeverity> </li> <li> <label>rejection</label> <minSeverity>0.7</minSeverity> <becomeVisible>false</becomeVisible> </li> </stages> </HediffDef> <!--THese are all the same, the flavor text is different--> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_male2trap</defName> <label>male2trap</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_male2female</defName> <label>male2female</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_male2futa</defName> <label>male2futa</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_female2trap</defName> <label>female2trap</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_female2male</defName> <label>female2male</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_female2futa</defName> <label>female2futa</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_futa2trap</defName> <label>futa2trap</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_futa2male</defName> <label>futa2male</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_futa2female</defName> <label>futa2female</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_trap2futa</defName> <label>trap2futa</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_trap2male</defName> <label>trap2male</label> </HediffDef> <HediffDef ParentName="Sex_Change_Thoughts_Syndrome"> <defName>hediff_trap2female</defName> <label>trap2female</label> </HediffDef> <!--hidden hediffs to track original sex--> <HediffDef Name="Sex_Change_Original_Sex" Abstract="True"> <hediffClass>HediffWithComps</hediffClass> <defaultLabelColor>(1, 0.41, 0.71)</defaultLabelColor> <description>Changed gender</description> <maxSeverity>1.0</maxSeverity> <isBad>false</isBad> <tendable>false</tendable> <scenarioCanAdd>false</scenarioCanAdd> <stages> <li> <becomeVisible>false</becomeVisible> </li> </stages> </HediffDef> <HediffDef ParentName="Sex_Change_Original_Sex"> <defName>hediff_was_boy</defName> <label>was_boy</label> </HediffDef> <HediffDef ParentName="Sex_Change_Original_Sex"> <defName>hediff_was_girl</defName> <label>was_girl</label> </HediffDef> <!--whatever this may mean:--> <HediffDef ParentName="Sex_Change_Original_Sex"> <defName>hediff_was_futa</defName> <label>was_futa</label> </HediffDef> <HediffDef ParentName="Sex_Change_Original_Sex"> <defName>hediff_was_trap</defName> <label>was_trap</label> </HediffDef> </Defs>
Tirem12/rjw
Defs/HediffDefs/Hediffs_Transgender.xml
XML
mit
4,508
<?xml version="1.0" encoding="utf-8" ?> <Defs> <IncidentDef> <defName>NymphJoins</defName> <label>nymph joins</label> <category>Misc</category> <targetTags> <li>Map_PlayerHome</li> </targetTags> <workerClass>rjw.IncidentWorker_NymphJoins</workerClass> <baseChance>0.67</baseChance> <minRefireDays>6</minRefireDays> </IncidentDef> <IncidentDef> <defName>NymphVisitor</defName> <label>nymph visitor</label> <category>Misc</category> <targetTags> <li>Map_PlayerHome</li> </targetTags> <workerClass>rjw.IncidentWorker_NymphVisitor</workerClass> <baseChance>0.67</baseChance> <minRefireDays>6</minRefireDays> </IncidentDef> <IncidentDef> <defName>NymphVisitorGroupEasy</defName> <label>nymph raid(easy)</label> <targetTags> <li>Map_PlayerHome</li> </targetTags> <workerClass>rjw.IncidentWorker_NymphVisitorGroupEasy</workerClass> <category>ThreatBig</category> <baseChance>0.1</baseChance> <minRefireDays>6</minRefireDays> <pointsScaleable>false</pointsScaleable> </IncidentDef> <IncidentDef> <defName>NymphVisitorGroupHard</defName> <label>nymph raid(hard)</label> <targetTags> <li>Map_PlayerHome</li> </targetTags> <workerClass>rjw.IncidentWorker_NymphVisitorGroupHard</workerClass> <category>ThreatBig</category> <baseChance>0.01</baseChance> <minRefireDays>6</minRefireDays> <pointsScaleable>false</pointsScaleable> </IncidentDef> </Defs>
Tirem12/rjw
Defs/IncidentDef/Incidents_Nymph.xml
XML
mit
1,432
<?xml version="1.0" encoding="utf-8" ?> <Defs> <IncidentDef ParentName="DiseaseIncident"> <defName>Disease_Boobitis</defName> <label>boobitis mechanites</label> <diseaseIncident>Boobitis</diseaseIncident> <diseasePartsToAffect> <li>Chest</li> </diseasePartsToAffect> <letterLabel>Disease (boobitis mechanites)</letterLabel> </IncidentDef> </Defs>
Tirem12/rjw
Defs/IncidentDef/Incidents_STD.xml
XML
mit
368
<?xml version="1.0" encoding="utf-8" ?> <Defs> <IncidentDef> <defName>TestInc</defName> <label>test inc</label> <category>Misc</category> <targetTags> <li>Map_PlayerHome</li> </targetTags> <workerClass>rjw.IncidentWorker_TestInc</workerClass> <letterLabel>Something Happened</letterLabel> <letterText>Something Happened</letterText> <letterDef>ThreatSmall</letterDef> <baseChance>0.0</baseChance> <minRefireDays>9999</minRefireDays> </IncidentDef> <IncidentDef> <defName>TestInc2</defName> <label>test inc2</label> <category>Misc</category> <targetTags> <li>Map_PlayerHome</li> </targetTags> <workerClass>rjw.IncidentWorker_TestInc2</workerClass> <letterLabel>Something Happened2</letterLabel> <letterText>Something Happened2</letterText> <letterDef>ThreatSmall</letterDef> <baseChance>0.0</baseChance> <minRefireDays>9999</minRefireDays> </IncidentDef> </Defs>
Tirem12/rjw
Defs/IncidentDef/Incidents_Testing.xml
XML
mit
917
<?xml version="1.0" encoding="utf-8" ?> <Defs> <InteractionDef> <defName>AnalBreeding</defName> <label>anal breeding</label> <workerClass>rjw.InteractionWorker_AnalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->Mounted [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was anally mounted by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>VaginalBreeding</defName> <label>vaginal breeding</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->Mounted [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was mounted by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>OralBreeding</defName> <label>oral breeding</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->Licked [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was licked by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>ForcedFellatioBreeding</defName> <label>oral breeding</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->Face fucked [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was face fucked.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <!-- This can only happen if the player disables the other types, which makes things go weird... --> <InteractionDef> <defName>ForcedOralBreeding</defName> <label>oral breeding</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->Forced oral sex from [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was forced into giving oral.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <!-- Another rare one, but needed to get the icons working right. --> <InteractionDef> <defName>FingeringBreeding</defName> <label>fingering</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->Fingered [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was fingered by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>RequestBreeding</defName> <label>request breeding</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->[RECIPIENT_nameDef] presented to [INITIATOR_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Presented to [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>RequestAnalBreeding</defName> <label>request breeding</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Commands/Breeding_Animal_off</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <logRulesInitiator> <rulesStrings> <li>r_logentry->[RECIPIENT_nameDef] presented to [INITIATOR_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Presented to [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> </Defs>
Tirem12/rjw
Defs/InteractionDef/Interactions_Breed.xml
XML
mit
4,754
<?xml version="1.0" encoding="utf-8" ?> <Defs> <InteractionDef> <defName>Rimming</defName> <label>rimming</label> <workerClass>rjw.InteractionWorker_AnalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Rimmed [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was rimmed.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Cunnilingus</defName> <label>cunnilingus</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <!-- these are only the first part the log, need to keep it short.--> <li>r_logentry->Gave cunnilingus.</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Received cunnilingus.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Fellatio</defName> <label>Fellatio</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Fellated [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was fellated.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> </Defs>
Tirem12/rjw
Defs/InteractionDef/Interactions_Oral.xml
XML
mit
1,859
<?xml version="1.0" encoding="utf-8" ?> <Defs> <InteractionDef> <defName>AnalRape</defName> <label>anal rape</label> <workerClass>rjw.InteractionWorker_AnalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>StoleSomeLovin</recipientThought> <initiatorXpGainSkill>Melee</initiatorXpGainSkill> <initiatorXpGainAmount>30</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry->Raped [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was raped by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>VaginalRape</defName> <label>vaginal rape</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>StoleSomeLovin</recipientThought> <initiatorXpGainSkill>Melee</initiatorXpGainSkill> <initiatorXpGainAmount>30</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry->Raped [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was raped by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>HandjobRape</defName> <label>forced handjob</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>StoleSomeLovin</recipientThought> <initiatorXpGainSkill>Melee</initiatorXpGainSkill> <initiatorXpGainAmount>30</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry->Forcibly jerked off [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was jerked off by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>FingeringRape</defName> <label>forced fingering</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>StoleSomeLovin</recipientThought> <initiatorXpGainSkill>Melee</initiatorXpGainSkill> <initiatorXpGainAmount>30</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry->Forcibly fingered [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was finger-raped by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>ViolateCorpse</defName> <label>necrophilia</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>StoleSomeLovin</recipientThought> <initiatorXpGainSkill>Melee</initiatorXpGainSkill> <initiatorXpGainAmount>30</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry->Violated [RECIPIENT_nameDef]'s corpse.</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was violated by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>MechImplant</defName> <label>mechanoid implanting</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <!--<recipientThought>StoleSomeLovin</recipientThought>--> <!--<initiatorXpGainSkill>Melee</initiatorXpGainSkill>--> <!--<initiatorXpGainAmount>30</initiatorXpGainAmount>--> <logRulesInitiator> <rulesStrings> <li>r_logentry->Assaulted [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was assaulted by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>OtherRape</defName> <label>rape</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>UI/Icons/noheart</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>StoleSomeLovin</recipientThought> <initiatorXpGainSkill>Melee</initiatorXpGainSkill> <initiatorXpGainAmount>30</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry->Raped [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was raped by [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> </Defs>
Tirem12/rjw
Defs/InteractionDef/Interactions_Rape.xml
XML
mit
4,986
<?xml version="1.0" encoding="utf-8" ?> <Defs> <InteractionDef> <defName>AnalSex</defName> <label>anal sex</label> <workerClass>rjw.InteractionWorker_AnalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Had anal sex with [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Had anal sex with [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>VaginalSex</defName> <label>vaginal sex</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Had sex with [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Had sex with [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>DoublePenetration</defName> <label>double-penetration</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Double-penetrated [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was double-penetrated.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Breastjob</defName> <label>breastjob</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Gave a breastjob to [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Received a breastjob.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Handjob</defName> <label>handjob</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Gave a Handjob.</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Received a Handjob.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Footjob</defName> <label>footjob</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Gave a footjob.</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Received a footjob.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Beakjob</defName> <label>beakjob</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Gave a beakjob.</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Received a beakjob.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Fingering</defName> <label>fingering</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Fingered [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was fingered.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Scissoring</defName> <label>scissoring</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Scissored with [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Scissored with [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>MutualMasturbation</defName> <label>mutual masturbation</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Engaged in mutual masturbation.</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Engaged in mutual masturbation.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Fisting</defName> <label>fisting</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->Fisted [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->Was fisted.</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <InteractionDef> <defName>Sixtynine</defName> <label>69ing</label> <workerClass>rjw.InteractionWorker_VaginalSexAttempt</workerClass> <symbol>Things/Mote/SpeechSymbols/Romance</symbol> <socialFightBaseChance>0.0</socialFightBaseChance> <recipientThought>MadeSomeLovin</recipientThought> <logRulesInitiator> <rulesStrings> <li>r_logentry->69'd with [RECIPIENT_nameDef].</li> </rulesStrings> </logRulesInitiator> <logRulesRecipient> <rulesStrings> <li>r_logentry->69'd with [INITIATOR_nameDef].</li> </rulesStrings> </logRulesRecipient> </InteractionDef> <!-- Experimenting with sex dialogue. This was easiest to add, but the same method could be used to add pillow talk, etc.--> <InteractionDef> <defName>AnimalSexChat</defName> <label>animal chat</label> <symbol>Things/Mote/SpeechSymbols/AnimalChat</symbol> <initiatorXpGainSkill>Animals</initiatorXpGainSkill> <initiatorXpGainAmount>40</initiatorXpGainAmount> <logRulesInitiator> <rulesStrings> <li>r_logentry(p=20)->[INITIATOR_nameDef] [zooact] [RECIPIENT_nameDef].</li> <li>r_logentry->[INITIATOR_nameDef] sat near [RECIPIENT_nameDef] and talked to [INITIATOR_objective]self about [TalkTopicSex].</li> <li>r_logentry->[INITIATOR_nameDef] sat near [RECIPIENT_nameDef] and talked to [INITIATOR_objective]self about [TalkTopicAny].</li> <li>r_logentry->[INITIATOR_nameDef] approached [RECIPIENT_nameDef] while whispering to [INITIATOR_objective]self about [TalkTopicSex].</li> <li>r_logentry->[INITIATOR_nameDef] approached [RECIPIENT_nameDef] while whispering to [INITIATOR_objective]self about [TalkTopicAny].</li> <li>r_logentry(p=2)->[INITIATOR_nameDef] came near [RECIPIENT_nameDef] while talking to [INITIATOR_objective]self about [TalkTopicSex].</li> <li>r_logentry->[INITIATOR_nameDef] came near [RECIPIENT_nameDef] while talking to [INITIATOR_objective]self about [TalkTopicAny].</li> <li>r_logentry->[INITIATOR_nameDef] tried to make [RECIPIENT_nameDef] sit still.</li> <li>r_logentry->[INITIATOR_nameDef] attempted to hold [RECIPIENT_nameDef] still.</li> <li>r_logentry->[INITIATOR_nameDef] slapped [RECIPIENT_nameDef] in a show of dominance.</li> <li>r_logentry->[INITIATOR_nameDef] gently stroked [RECIPIENT_nameDef]'s genitals.</li> <li>r_logentry->[INITIATOR_nameDef] grasped a vulnerable body part of [RECIPIENT_nameDef], demanding obedience.</li> <li>zooact->demanded obedience from</li> <li>zooact->made calming noises towards</li> <li>zooact->offered slow, friendly gestures to</li> <li>zooact->made shushing noises at</li> <li>zooact->made happy clicking noises at</li> <li>zooact->gestured gently and approached</li> <li>zooact->slowly approached</li> <li>zooact->gently touched</li> <li>zooact->gently caressed</li> <li>zooact->firmly stroked</li> <li>zooact->calmed and encouraged</li> <li>zooact->matched breathing with</li> <li>zooact->took a low stance while approaching</li> <li>zooact->showed no fear or anger to</li> <li>zooact->firmly yet softly touched</li> <li>zooact->showed a relaxed attitude towards</li> <li>zooact->showed [INITIATOR_possessive] genitals to</li> <li>zooact->presented [INITIATOR_possessive] genitals to</li> <li>zooact->whispered a story about [TalkTopicAny] to</li> <li>zooact->whispered a story about [TalkTopicSex] to</li> </rulesStrings> </logRulesInitiator> </InteractionDef> </Defs>
Tirem12/rjw
Defs/InteractionDef/Interactions_Sex.xml
XML
mit
10,077
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>GettinBred</defName> <driverClass>rjw.JobDriver_SexBaseRecieverRaped</driverClass> <reportString>gettin' bred.</reportString> <checkOverrideOnDamage>Never</checkOverrideOnDamage> <casualInterruptible>false</casualInterruptible> </JobDef> <JobDef> <defName>Breed</defName> <driverClass>rjw.JobDriver_Breeding</driverClass> <reportString>breeding</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> <JobDef> <defName>RJWMate</defName> <driverClass>rjw.JobDriver_Mating</driverClass> <reportString>mating</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> <JobDef> <defName>Bestiality</defName> <driverClass>rjw.JobDriver_BestialityForMale</driverClass> <reportString>lovin' animal</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> <JobDef> <defName>BestialityForFemale</defName> <driverClass>rjw.JobDriver_BestialityForFemale</driverClass> <reportString>lovin' animal</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_Bestiality.xml
XML
mit
1,140
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>StruggleInBondageGear</defName> <driverClass>rjw.JobDriver_StruggleInBondageGear</driverClass> <reportString>struggling</reportString> </JobDef> <JobDef> <defName>UnlockBondageGear</defName> <driverClass>rjw.JobDriver_UseItemOn</driverClass> <reportString>unlocking</reportString> </JobDef> <JobDef> <defName>GiveBondageGear</defName> <driverClass>rjw.JobDriver_UseItemOn</driverClass> <reportString>equipping</reportString> </JobDef> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_Bondage.xml
XML
mit
534
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>CleanSelf</defName> <driverClass>rjw.JobDriver_CleanSelf</driverClass> <reportString>cleaning self</reportString> <casualInterruptible>true</casualInterruptible> </JobDef> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_CleanSelf.xml
XML
mit
255
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>Masturbate_Bed</defName> <driverClass>rjw.JobDriver_Masturbate_Bed</driverClass> <reportString>masturbatin'.</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> <JobDef> <defName>Masturbate_Quick</defName> <driverClass>rjw.JobDriver_Masturbate_Quick</driverClass> <reportString>masturbatin'.</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_Masturbate.xml
XML
mit
482
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- <JobDef> <defName>MilkHuman</defName> <driverClass>rjw.JobDriver_MilkHuman</driverClass> <reportString>milking TargetA.</reportString> <allowOpportunisticPrefix>true</allowOpportunisticPrefix> </JobDef> --> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_Milk.xml
XML
mit
280
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>ViolateCorpse</defName> <driverClass>rjw.JobDriver_ViolateCorpse</driverClass> <reportString>violating corpse</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_Necro.xml
XML
mit
267
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>Quickie</defName> <driverClass>rjw.JobDriver_SexQuick</driverClass> <reportString>doing quickie with someone.</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> <JobDef> <defName>GettingQuickie</defName> <driverClass>rjw.JobDriver_SexBaseRecieverQuickie</driverClass> <reportString>lovin'.</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> </Defs>
Tirem12/rjw
Defs/JobDefs/Jobs_Quickie.xml
XML
mit
482