Commit d5608340 authored by Ian Craggs's avatar Ian Craggs

Ant build plus tests

parent c1efe23d
<project name="MQTT C Client" default="full">
<taskdef resource="net/sf/antcontrib/antlib.xml"/>
<property name="output.folder" value="build/output" />
<property name="build.level" value="${today}" />
<property name="release.version" value="1.0.0.2" />
<property name="libname" value="mqttv3c" />
<property name="libname.ssl" value="mqttv3cs" />
<property name="libname.async" value="mqttv3a" />
<property name="libname.async.ssl" value="mqttv3as" />
<target name="init">
<tstamp/>
<fileset id="sync.source.fileset" dir="src">
<include name="*.c"/>
<exclude name="MQTTAsync.c"/>
<exclude name="MQTTVersion.c"/>
</fileset>
<pathconvert refid="sync.source.fileset" property="sync.source.files" pathsep=" "/>
<fileset id="async.source.fileset" dir="src">
<include name="*.c"/>
<exclude name="MQTTClient.c"/>
<exclude name="MQTTVersion.c"/>
</fileset>
<pathconvert refid="async.source.fileset" property="async.source.files" pathsep=" "/>
</target>
<target name="version" depends="init" description="replace tags in the source with the right levels">
<replace file="src/MQTTClient.c" token="##MQTTCLIENT_BUILD_TAG##" value="${build.level}" />
<replace file="src/MQTTClient.c" token="##MQTTCLIENT_VERSION_TAG##" value="${release.version}" />
<replace file="src/MQTTAsync.c" token="##MQTTCLIENT_BUILD_TAG##" value="${build.level}" />
<replace file="src/MQTTAsync.c" token="##MQTTCLIENT_VERSION_TAG##" value="${release.version}" />
</target>
<target name="compile" depends="version">
<if>
<os family="unix" />
<then>
<property name="ccflags.so" value="-fPIC -Os -Wall" />
<property name="ldflags.so" value="-fvisibility=hidden -shared -Wl,-soname,lib${libname}.so" />
<mkdir dir="${output.folder}"/>
<!-- non-SSL, synchronous library -->
<property name="output.filename" value="${output.folder}/lib${libname}.so" />
<exec executable="gcc" failonerror="true">
<arg line="${ccflags.so} ${ldflags.so} -o ${output.filename} ${sync.source.files}"/>
</exec>
<exec executable="strip" failonerror="true">
<arg value="${output.filename}" />
</exec>
<!-- SSL, synchronous library -->
<property name="output.ssl.filename" value="${output.folder}/lib${libname.ssl}.so" />
<exec executable="gcc" failonerror="true">
<arg line="-DOPENSSL ${ccflags.so} ${ldflags.so} -o ${output.ssl.filename} ${sync.source.files}"/>
</exec>
<exec executable="strip" failonerror="true">
<arg value="${output.ssl.filename}" />
</exec>
<!-- non-SSL, asynchronous library -->
<property name="output.async.filename" value="${output.folder}/lib${libname.async}.so" />
<exec executable="gcc" failonerror="true">
<arg line="${ccflags.so} ${ldflags.so} -o ${output.async.filename} ${async.source.files}"/>
</exec>
<exec executable="strip" failonerror="true">
<arg value="${output.async.filename}" />
</exec>
<!-- SSL, asynchronous library -->
<property name="output.async.ssl.filename" value="${output.folder}/lib${libname.async.ssl}.so" />
<exec executable="gcc" failonerror="true">
<arg line="-DOPENSSL ${ccflags.so} ${ldflags.so} -o ${output.async.ssl.filename} ${sync.source.files}"/>
</exec>
<exec executable="strip" failonerror="true">
<arg value="${output.async.ssl.filename}" />
</exec>
<!-- MQTTVersion -->
<property name="output.async.ssl.filename" value="${output.folder}/lib${libname.async.ssl}.so" />
<exec executable="gcc" failonerror="true">
<arg line="-lpthread -ldl -o ${output.folder}/MQTTVersion src/MQTTVersion.c"/>
</exec>
<exec executable="strip" failonerror="true">
<arg value="${output.folder}/MQTTVersion" />
</exec>
<!-- Samples
<property name="output.async.ssl.filename" value="${output.folder}/lib${libname.async.ssl}.so" />
<foreach list="$">
<exec executable="gcc" failonerror="true">
<arg line="-lpthread -ldl -o ${output.folder}/MQTTVersion src/MQTTVersion.c"/>
</exec>
<exec executable="strip" failonerror="true">
<arg value="${output.folder}/MQTTVersion" />
</exec> -->
<!-- Build tests -->
<foreach target="onecompile" param="aFile" list="test1,test3"/>
<foreach target="asynccompile" param="aFile" list="test4,test5"/>
</then>
<elseif>
<os family="windows" />
<then>
</then>
</elseif>
</if>
</target>
<target name="onecompile" >
<exec executable="gcc" failonerror="true">
<arg line="-I src -lpthread -lmqttv3c -L${output.folder} -o ${output.folder}/${aFile} test/${aFile}.c"/>
</exec>
</target>
<target name="asynccompile" >
<exec executable="gcc" failonerror="true">
<arg line="-I src -lpthread -lmqttv3a -L${output.folder} -o ${output.folder}/${aFile} test/${aFile}.c"/>
</exec>
</target>
<target name="doc" >
<if>
<available file="${doxygen}"/>
<then>
<exec executable="${doxygen}" dir="${mqttclient_src}">
<arg value="${source.folder}/mqttv3c/doc/DoxyfileV3ClientAPI"/>
</exec>
<mkdir dir="${ship.folder}/doc/html"/>
<copy todir="${ship.folder}/doc/html">
<fileset dir="${mqttclient_src}/MQTTClient/html"/>
</copy>
<!-- <zip destfile="${output.folder}/doc/MQTTClient.zip">
<zipfileset dir="${mqttclient_src}/MQTTClient" />
</zip> -->
<exec executable="${doxygen}" dir="${mqttclient_src}">
<arg value="${source.folder}/mqttv3c/doc/DoxyfileV3AsyncAPI"/>
</exec>
<mkdir dir="${ship.folder}/doc/html/MQTTAsync"/>
<copy todir="${ship.folder}/doc/html/MQTTAsync">
<fileset dir="${mqttclient_src}/MQTTAsync"/>
</copy>
<!-- <zip destfile="${output.folder}/doc/MQTTAsync.zip">
<zipfileset dir="${mqttclient_src}/MQTTAsync" prefix="MQTTAsync/"/>
</zip> -->
<delete dir="${mqttclient_src}/MQTTClient" />
<delete dir="${mqttclient_src}/MQTTAsync" />
</then>
<else>
<echo message="doxygen is not available" />
</else>
</if>
</target>
<target name="copy">
<mkdir dir="${ship.folder}/include"/>
<echo message="Copying the headers for the c_client from the output tree" />
<copy overwrite="true" todir="${ship.folder}/include">
<fileset dir="${mqttclient_src}">
<include name="MQTTClient.h"/>
<include name="MQTTClientPersistence.h"/>
<include name="MQTTAsync.h"/>
</fileset>
</copy>
<echo message="Copying the source.zip file from the output tree" />
<copy overwrite="true" todir="${ship.folder}">
<fileset dir="${output.folder}">
<include name="source.zip"/>
</fileset>
</copy>
</target>
<!-- target name="full" depends="init, version, compile, doc, copy" -->
<target name="full" depends="init, version, compile" />
</project>
#define MY_ID "@(#) stmqcom/pub1.c, stmqcom, cs 1.85 10/08/24 07:36:24"
/*--------------------------------------------------------------------*/
/* [Platforms]UNIX NT[/Platforms] */
/* [Title]MQ Telemetry MQTT C client tests */
/* [/Title] */
/* [Testclasses]stcom1 stmqcom1[/Category] */
/* [Category]MQ Telemetry[/Category] */
/* */
/* Copyright IBM 2012 */
/* All rights reserved. */
/*--------------------------------------------------------------------*/
/**
* @file
* Tests for the MQ Telemetry MQTT C client
*/
/*
#if !defined(_RTSHEADER)
#include <rts.h>
#endif
*/
#include "MQTTClient.h"
#include <string.h>
#include <stdlib.h>
#if !defined(_WINDOWS)
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAXHOSTNAMELEN 256
#define EAGAIN WSAEWOULDBLOCK
#define EINTR WSAEINTR
#define EINPROGRESS WSAEINPROGRESS
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOTCONN WSAENOTCONN
#define ECONNRESET WSAECONNRESET
#endif
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
void usage()
{
printf("help!!\n");
exit(-1);
}
struct Options
{
char* connection; /**< connection to system under test. */
char** haconnections;
int hacount;
int verbose;
int test_no;
} options =
{
"m2m.eclipse.org:1883",
NULL,
0,
0,
0,
};
void getopts(int argc, char** argv)
{
int count = 1;
while (count < argc)
{
if (strcmp(argv[count], "--test_no") == 0)
{
if (++count < argc)
options.test_no = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--connection") == 0)
{
if (++count < argc)
options.connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--haconnections") == 0)
{
if (++count < argc)
{
char* tok = strtok(argv[count], " ");
options.hacount = 0;
options.haconnections = malloc(sizeof(char*) * 5);
while (tok)
{
options.haconnections[options.hacount] = malloc(strlen(tok) + 1);
strcpy(options.haconnections[options.hacount], tok);
options.hacount++;
tok = strtok(NULL, " ");
}
}
else
usage();
}
else if (strcmp(argv[count], "--verbose") == 0)
{
options.verbose = 1;
//TODO
printf("\nSetting verbose on\n");
}
count++;
}
}
#if 0
#include <logaX.h> /* For general log messages */
#define MyLog logaLine
#else
#define LOGA_DEBUG 0
#define LOGA_INFO 1
#include <stdarg.h>
#include <time.h>
#include <sys/timeb.h>
void MyLog(int LOGA_level, char* format, ...)
{
static char msg_buf[256];
va_list args;
struct timeb ts;
struct tm *timeinfo;
if (LOGA_level == LOGA_DEBUG && options.verbose == 0)
return;
ftime(&ts);
timeinfo = localtime(&ts.time);
strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
va_start(args, format);
vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf), format, args);
va_end(args);
printf("%s\n", msg_buf);
fflush(stdout);
}
#endif
#if defined(WIN32) || defined(_WINDOWS)
#define mqsleep(A) Sleep(1000*A)
#define START_TIME_TYPE DWORD
static DWORD start_time = 0;
START_TIME_TYPE start_clock(void)
{
return GetTickCount();
}
#elif defined(AIX)
#define mqsleep sleep
#define START_TIME_TYPE struct timespec
START_TIME_TYPE start_clock(void)
{
static struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
return start;
}
#else
#define mqsleep sleep
#define START_TIME_TYPE struct timeval
/* TODO - unused - remove? static struct timeval start_time; */
START_TIME_TYPE start_clock(void)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
return start_time;
}
#endif
#if defined(WIN32)
long elapsed(START_TIME_TYPE start_time)
{
return GetTickCount() - start_time;
}
#elif defined(AIX)
#define assert(a)
long elapsed(struct timespec start)
{
struct timespec now, res;
clock_gettime(CLOCK_REALTIME, &now);
ntimersub(now, start, res);
return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
}
#else
long elapsed(START_TIME_TYPE start_time)
{
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&now, &start_time, &res);
return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}
#endif
START_TIME_TYPE global_start_time;
#define assert(a, b, c, d) myassert(__FILE__, __LINE__, a, b, c, d)
#define assert1(a, b, c, d, e) myassert(__FILE__, __LINE__, a, b, c, d, e)
int tests = 0;
int failures = 0;
void myassert(char* filename, int lineno, char* description, int value, char* format, ...)
{
++tests;
if (!value)
{
va_list args;
++failures;
printf("Assertion failed, file %s, line %d, description: %s\n", filename, lineno, description);
va_start(args, format);
vprintf(format, args);
va_end(args);
}
else
MyLog(LOGA_DEBUG, "Assertion succeeded, file %s, line %d, description: %s", filename, lineno, description);
}
/*********************************************************************
Test1: single-threaded client
*********************************************************************/
void test1_sendAndReceive(MQTTClient* c, int qos, char* test_topic)
{
MQTTClient_deliveryToken dt;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_message* m = NULL;
char* topicName = NULL;
int topicLen;
int i = 0;
int iterations = 50;
int rc;
MyLog(LOGA_DEBUG, "%d messages at QoS %d", iterations, qos);
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = qos;
pubmsg.retained = 0;
for (i = 0; i< iterations; ++i)
{
if (i % 10 == 0)
rc = MQTTClient_publish(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
else
rc = MQTTClient_publishMessage(c, test_topic, &pubmsg, &dt);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
if (qos > 0)
{
rc = MQTTClient_waitForCompletion(c, dt, 1000L);
assert("Good rc from waitforCompletion", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
}
rc = MQTTClient_receive(c, &topicName, &topicLen, &m, 1000);
assert("Good rc from receive", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
if (topicName)
{
MyLog(LOGA_DEBUG, "Message received on topic %s is %.*s", topicName, m->payloadlen, (char*)(m->payload));
if (pubmsg.payloadlen != m->payloadlen ||
memcmp(m->payload, pubmsg.payload, m->payloadlen) != 0)
{
failures++;
MyLog(LOGA_INFO, "Error: wrong data - received lengths %d %d", pubmsg.payloadlen, m->payloadlen);
break;
}
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
}
else
printf("No message received within timeout period\n");
}
/* receive any outstanding messages */
MQTTClient_receive(c, &topicName, &topicLen, &m, 1000);
while (topicName)
{
printf("Message received on topic %s is %.*s.\n", topicName, m->payloadlen, (char*)(m->payload));
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
MQTTClient_receive(c, &topicName, &topicLen, &m, 1000);
}
}
int test1(struct Options options)
{
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test1";
failures = 0;
MyLog(LOGA_INFO, "Starting test 1 - single threaded client using receive");
rc = MQTTClient_create(&c, options.connection, "single_threaded_test",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTCLIENT_SUCCESS)
{
MQTTClient_destroy(&c);
goto exit;
}
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTClient_connect(c, &opts);
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
if (rc != MQTTCLIENT_SUCCESS)
goto exit;
rc = MQTTClient_subscribe(c, test_topic, subsqos);
assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
test1_sendAndReceive(c, 0, test_topic);
test1_sendAndReceive(c, 1, test_topic);
test1_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
rc = MQTTClient_unsubscribe(c, test_topic);
assert("Unsubscribe successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
rc = MQTTClient_disconnect(c, 0);
assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
/* Just to make sure we can connect again */
rc = MQTTClient_connect(c, &opts);
assert("Connect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
rc = MQTTClient_disconnect(c, 0);
assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
MQTTClient_destroy(&c);
exit:
MyLog(LOGA_INFO, "TEST1: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
/*********************************************************************
Test2: multi-threaded client using callbacks
*********************************************************************/
volatile int test2_arrivedcount = 0;
int test2_deliveryCompleted = 0;
MQTTClient_message test2_pubmsg = MQTTClient_message_initializer;
void test2_deliveryComplete(void* context, MQTTClient_deliveryToken dt)
{
++test2_deliveryCompleted;
}
int test2_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* m)
{
++test2_arrivedcount;
MyLog(LOGA_DEBUG, "Callback: %d message received on topic %s is %.*s.",
test2_arrivedcount, topicName, m->payloadlen, (char*)(m->payload));
if (test2_pubmsg.payloadlen != m->payloadlen ||
memcmp(m->payload, test2_pubmsg.payload, m->payloadlen) != 0)
{
failures++;
MyLog(LOGA_INFO, "Error: wrong data received lengths %d %d\n", test2_pubmsg.payloadlen, m->payloadlen);
}
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
return 1;
}
void test2_sendAndReceive(MQTTClient* c, int qos, char* test_topic)
{
MQTTClient_deliveryToken dt;
int i = 0;
int iterations = 50;
int rc = 0;
int wait_seconds = 0;
test2_deliveryCompleted = 0;
MyLog(LOGA_INFO, "%d messages at QoS %d", iterations, qos);
test2_pubmsg.payload = "a much longer message that we can shorten to the extent that we need to";
test2_pubmsg.payloadlen = 27;
test2_pubmsg.qos = qos;
test2_pubmsg.retained = 0;
for (i = 1; i <= iterations; ++i)
{
if (i % 10 == 0)
rc = MQTTClient_publish(c, test_topic, test2_pubmsg.payloadlen, test2_pubmsg.payload,
test2_pubmsg.qos, test2_pubmsg.retained, NULL);
else
rc = MQTTClient_publishMessage(c, test_topic, &test2_pubmsg, &dt);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
#if defined(WIN32)
Sleep(100);
#else
usleep(100000L);
#endif
wait_seconds = 10;
while ((test2_arrivedcount < i) && (wait_seconds-- > 0))
{
MyLog(LOGA_DEBUG, "Arrived %d count %d", test2_arrivedcount, i);
#if defined(WIN32)
Sleep(1000);
#else
usleep(1000000L);
#endif
}
assert("Message Arrived", wait_seconds > 0,
"Time out waiting for message %d\n", i );
}
if (qos > 0)
{
/* MQ Telemetry can send a message to a subscriber before the server has
completed the QoS 2 handshake with the publisher. For QoS 1 and 2,
allow time for the final delivery complete callback before checking
that all expected callbacks have been made */
wait_seconds = 10;
while ((test2_deliveryCompleted < iterations) && (wait_seconds-- > 0))
{
MyLog(LOGA_DEBUG, "Delivery Completed %d count %d", test2_deliveryCompleted, i);
#if defined(WIN32)
Sleep(1000);
#else
usleep(1000000L);
#endif
}
assert("All Deliveries Complete", wait_seconds > 0,
"Number of deliveryCompleted callbacks was %d\n",
test2_deliveryCompleted);
}
}
int test2(struct Options options)
{
char* testname = "test2";
int subsqos = 2;
/* TODO - usused - remove ? MQTTClient_deliveryToken* dt = NULL; */
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
int rc = 0;
char* test_topic = "C client test2";
failures = 0;
MyLog(LOGA_INFO, "Starting test 2 - multi-threaded client using callbacks");
MQTTClient_create(&c, options.connection, "multi_threaded_sample", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
rc = MQTTClient_setCallbacks(c, NULL, NULL, test2_messageArrived, test2_deliveryComplete);
assert("Good rc from setCallbacks", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTClient_connect(c, &opts);
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
if (rc != MQTTCLIENT_SUCCESS)
goto exit;
rc = MQTTClient_subscribe(c, test_topic, subsqos);
assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
test2_sendAndReceive(c, 0, test_topic);
test2_sendAndReceive(c, 1, test_topic);
test2_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping");
rc = MQTTClient_unsubscribe(c, test_topic);
assert("Unsubscribe successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
rc = MQTTClient_disconnect(c, 0);
assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
MQTTClient_destroy(&c);
exit:
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test 3: connack return codes
for AMQTDD, needs an amqtdd.cfg of:
allow_anonymous false
password_file passwords
and a passwords file of:
Admin:Admin
*********************************************************************/
int test3(struct Options options)
{
char* testname = "test3";
int rc;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
/* TODO - unused - remove? MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer; */
failures = 0;
MyLog(LOGA_INFO, "Starting test 3 - connack return codes");
/* clientid too long (RC = 2) */
rc = MQTTClient_create(&c, options.connection, "client_ID_too_long_for_MQTT_protocol_version_3",
MQTTCLIENT_PERSISTENCE_NONE, NULL);
assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
rc = MQTTClient_connect(c, &opts);
assert("identifier rejected", rc == 2, "rc was %d\n", rc);
MQTTClient_destroy(&c);
#if 0
/* broker unavailable (RC = 3) - TDD when allow_anonymous not set*/
rc = MQTTClient_create(&c, "127.0.0.1:1883", "The C Client", MQTTCLIENT_PERSISTENCE_NONE, NULL);
assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
rc = MQTTClient_connect(c, &opts);
assert("broker unavailable", rc == 3, "rc was %d\n", rc);
/* authentication failure (RC = 4) */
opts.username = "Admin";
opts.password = "fred";
rc = MQTTClient_connect(c, &opts);
assert("Bad user name or password", rc == 4, "rc was %d\n", rc);
#endif
#if defined(MICROBROKER)
/* authorization failure (RC = 5) */
opts.username = "Admin";
opts.password = "Admin";
opts.will = &wopts; /* "Admin" not authorized to publish to Will topic by default */
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
rc = MQTTClient_connect(c, &opts);
assert("Not authorized", rc == 5, "rc was %d\n", rc);
#endif
#if 0
/* successful connection (RC = 0) */
opts.username = "Admin";
opts.password = "Admin";
opts.will = NULL;
rc = MQTTClient_connect(c, &opts);
assert("successful connection", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
MQTTClient_disconnect(c, 0);
MQTTClient_destroy(&c);
#endif
/* TODO - unused - remove ? exit: */
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test 4: client persistence 1
*********************************************************************/
int test4_run(int qos)
{
char* testname = "test 4";
char* topic = "Persistence test 1";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_message* m = NULL;
char* topicName = NULL;
int topicLen;
MQTTClient_deliveryToken* tokens = NULL;
int mytoken = -99;
char buffer[100];
int count = 3;
int i, rc;
failures = 0;
MyLog(LOGA_INFO, "Starting test 4 - persistence, qos %d", qos);
MQTTClient_create(&c, options.connection, "xrctest1_test_4", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
opts.keepAliveInterval = 20;
opts.reliable = 0;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
MyLog(LOGA_DEBUG, "Cleanup by connecting clean session\n");
opts.cleansession = 1;
if ((rc = MQTTClient_connect(c, &opts)) != 0)
{
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
return -1;
}
opts.cleansession = 0;
MQTTClient_disconnect(c, 0);
MyLog(LOGA_DEBUG, "Connecting\n");
if ((rc = MQTTClient_connect(c, &opts)) != 0)
{
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
return -1;
}
/* subscribe so we can get messages back */
rc = MQTTClient_subscribe(c, topic, subsqos);
assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
/* send messages so that we can receive the same ones */
for (i = 0; i < count; ++i)
{
sprintf(buffer, "Message sequence no %d", i);
rc = MQTTClient_publish(c, topic, 10, buffer, qos, 0, NULL);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
}
/* disconnect immediately without receiving the incoming messages */
MQTTClient_disconnect(c, 0); /* now there should be "orphaned" publications */
rc = MQTTClient_getPendingDeliveryTokens(c, &tokens);
assert("getPendingDeliveryTokens rc == 0", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
assert("should get some tokens back", tokens != NULL, "tokens was %p", tokens);
if (tokens)
{
int i = 0;
while (tokens[i] != -1)
MyLog(LOGA_DEBUG, "Pending delivery token %d", tokens[i++]);
MQTTClient_free(tokens);
assert1("no of tokens should be count", i == count, "no of tokens %d count %d", i, count);
mytoken = tokens[0];
}
MQTTClient_destroy(&c); /* force re-reading persistence on create */
MQTTClient_create(&c, options.connection, "xrctest1_test_4", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
rc = MQTTClient_getPendingDeliveryTokens(c, &tokens);
assert("getPendingDeliveryTokens rc == 0", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
assert("should get some tokens back", tokens != NULL, "tokens was %p", tokens);
if (tokens)
{
int i = 0;
while (tokens[i] != -1)
MyLog(LOGA_DEBUG, "Pending delivery token %d", tokens[i++]);
MQTTClient_free(tokens);
assert1("no of tokens should be count", i == count, "no of tokens %d count %d", i, count);
}
MyLog(LOGA_DEBUG, "Reconnecting");
if (MQTTClient_connect(c, &opts) != 0)
{
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
return -1;
}
for (i = 0; i < count; ++i)
{
int dup = 0;
do
{
dup = 0;
MQTTClient_receive(c, &topicName, &topicLen, &m, 1000);
if (m && m->dup)
{
assert("No duplicates should be received for qos 2", qos == 1, "qos is %d", qos);
MyLog(LOGA_DEBUG, "Duplicate message id %d", m->msgid);
MQTTClient_freeMessage(&m);
MQTTClient_free(topicName);
dup = 1;
}
} while (dup == 1);
assert("should get a message", m != NULL, "m was %p", m);
if (m)
{
MyLog(LOGA_DEBUG, "Received message id %d", m->msgid);
assert("topicName is correct", strcmp(topicName, topic) == 0, "topicName is %s", topicName);
MQTTClient_freeMessage(&m);
MQTTClient_free(topicName);
}
}
MQTTClient_yield(); /* allow any unfinished protocol exchanges to finish */
rc = MQTTClient_getPendingDeliveryTokens(c, &tokens);
assert("getPendingDeliveryTokens rc == 0", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
assert("should get no tokens back", tokens == NULL, "tokens was %p", tokens);
MQTTClient_disconnect(c, 0);
MQTTClient_destroy(&c);
/* TODO - unused -remove? exit: */
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
int test4(struct Options options)
{
return test4_run(1) + test4_run(2);
}
/*********************************************************************
Test 5: disconnect with quiesce timeout should allow exchanges to complete
*********************************************************************/
int test5(struct Options options)
{
char* testname = "test 5";
/* TODO - unused -remove? char summaryname[50]; */
/* TODO - unused -remove? FILE *outfile = NULL; */
char* topic = "Persistence test 2";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
/* TODO - unused -remove? MQTTClient_message* m = NULL; */
/* TODO - unused -remove? char* topicName = NULL; */
MQTTClient_deliveryToken* tokens = NULL;
/* TODO - unused -remove? int mytoken = -99; */
char buffer[100];
int count = 5;
int i, rc;
failures = 0;
MyLog(LOGA_INFO, "Starting test 5 - disconnect with quiesce timeout should allow exchanges to complete");
MQTTClient_create(&c, options.connection, "xrctest1_test_5", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
opts.keepAliveInterval = 20;
opts.cleansession = 0;
opts.reliable = 0;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
MyLog(LOGA_DEBUG, "Connecting");
if ((rc = MQTTClient_connect(c, &opts)) != 0)
{
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
MQTTClient_destroy(&c);
goto exit;
}
rc = MQTTClient_subscribe(c, topic, subsqos);
assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
for (i = 0; i < count; ++i)
{
sprintf(buffer, "Message sequence no %d", i);
rc = MQTTClient_publish(c, topic, 10, buffer, 1, 0, NULL);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
}
MQTTClient_disconnect(c, 1000); /* now there should be no "orphaned" publications */
MyLog(LOGA_DEBUG, "Disconnected");
rc = MQTTClient_getPendingDeliveryTokens(c, &tokens);
assert("getPendingDeliveryTokens rc == 0", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
assert("should get no tokens back", tokens == NULL, "tokens was %p", tokens);
MQTTClient_destroy(&c);
exit:
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test 6: connectionLost and will message
*********************************************************************/
MQTTClient test6_c1, test6_c2;
volatile int test6_will_message_arrived = 0;
volatile int test6_connection_lost_called = 0;
void test6_connectionLost(void* context, char* cause)
{
MQTTClient c = (MQTTClient)context;
printf("%s -> Callback: connection lost\n", (c == test6_c1) ? "Client-1" : "Client-2");
test6_connection_lost_called = 1;
}
void test6_deliveryComplete(void* context, MQTTClient_deliveryToken token)
{
printf("Client-2 -> Callback: publish complete for token %d\n", token);
}
char* test6_will_topic = "C Test 2: will topic";
char* test6_will_message = "will message from Client-1";
int test6_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* m)
{
MQTTClient c = (MQTTClient)context;
printf("%s -> Callback: message received on topic '%s' is '%.*s'.\n",
(c == test6_c1) ? "Client-1" : "Client-2", topicName, m->payloadlen, (char*)(m->payload));
if (c == test6_c2 && strcmp(topicName, test6_will_topic) == 0 && memcmp(m->payload, test6_will_message, m->payloadlen) == 0)
test6_will_message_arrived = 1;
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
return 1;
}
int test6_socket_error(char* aString, int sock)
{
#if defined(WIN32)
int errno;
#endif
#if defined(WIN32)
errno = WSAGetLastError();
#endif
if (errno != EINTR && errno != EAGAIN && errno != EINPROGRESS && errno != EWOULDBLOCK)
{
if (strcmp(aString, "shutdown") != 0 || (errno != ENOTCONN && errno != ECONNRESET))
printf("Socket error %d in %s for socket %d", errno, aString, sock);
}
return errno;
}
#define SOCKET_ERROR -1
int test6_socket_close(int socket)
{
int rc;
#if defined(WIN32)
if (shutdown(socket, SD_BOTH) == SOCKET_ERROR)
test6_socket_error("shutdown", socket);
if ((rc = closesocket(socket)) == SOCKET_ERROR)
test6_socket_error("close", socket);
#else
if (shutdown(socket, SHUT_RDWR) == SOCKET_ERROR)
test6_socket_error("shutdown", socket);
if ((rc = close(socket)) == SOCKET_ERROR)
test6_socket_error("close", socket);
#endif
return rc;
}
typedef struct
{
char* clientID; /**< the string id of the client */
char* username; /**< MQTT v3.1 user name */
char* password; /**< MQTT v3.1 password */
unsigned int cleansession : 1; /**< MQTT clean session flag */
unsigned int connected : 1; /**< whether it is currently connected */
unsigned int good : 1; /**< if we have an error on the socket we turn this off */
unsigned int ping_outstanding : 1;
unsigned int connect_state : 2;
int socket;
int msgID;
int keepAliveInterval;
int retryInterval;
int maxInflightMessages;
time_t lastContact;
void* will;
void* inboundMsgs;
void* outboundMsgs; /**< in flight */
void* messageQueue;
void* phandle; /* the persistence handle */
MQTTClient_persistence* persistence; /* a persistence implementation */
int connectOptionsVersion;
} Clients;
typedef struct
{
char* serverURI;
Clients* c;
MQTTClient_connectionLost* cl;
MQTTClient_messageArrived* ma;
MQTTClient_deliveryComplete* dc;
void* context;
int connect_sem;
int rc; /* getsockopt return code in connect */
int connack_sem;
int suback_sem;
int unsuback_sem;
void* pack;
} MQTTClients;
int test6(struct Options options)
{
char* testname = "test6";
/* TODO - unused -remove? char summaryname[50]; */
/* TODO - unused -remove? FILE *outfile = NULL; */
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
/* TODO - unused -remove? MQTTClient_connectOptions opts2 = MQTTClient_connectOptions_initializer; */
int rc;
/* TODO - unused -remove? MQTTClient_message pubmsg = MQTTClient_message_initializer; */
/* TODO - unused -remove? MQTTClient_message* m = NULL; */
/* TODO - unused -remove? int count = 0; */
/* TODO - unused -remove? char* mqttsas_topic = "MQTTSAS topic"; */
failures = 0;
MyLog(LOGA_INFO, "Starting test 6 - connectionLost and will messages");
opts.keepAliveInterval = 10;
opts.cleansession = 1;
opts.will = &wopts;
opts.will->message = test6_will_message;
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = test6_will_topic;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
/* Client-1 with Will options */
/* connect to 1884 which is the protocol tracer and which allows the connection to be broken on command */
rc = MQTTClient_create(&test6_c1, options.connection, "Client_1", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTCLIENT_SUCCESS)
goto exit;
rc = MQTTClient_setCallbacks(test6_c1, (void*)test6_c1, test6_connectionLost, test6_messageArrived, test6_deliveryComplete);
assert("good rc from setCallbacks", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTCLIENT_SUCCESS)
goto exit;
/* Connect to the broker */
rc = MQTTClient_connect(test6_c1, &opts);
assert("good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTCLIENT_SUCCESS)
goto exit;
#if 1
rc = MQTTClient_disconnect(test6_c1, 100L);
assert("Good rc from disconnect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
#else
/* Client - 2 (multi-threaded) */
rc = MQTTClient_create(&test6_c2, "127.0.0.1:1883", "Client_2", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
/* Set the callback functions for the client */
rc = MQTTClient_setCallbacks(test6_c2, (void*)test6_c2, test6_connectionLost, test6_messageArrived, test6_deliveryComplete);
assert("good rc from setCallbacks", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
/* Connect to the broker */
opts2.keepAliveInterval = 20;
opts2.cleansession = 1;
MyLog(LOGA_INFO, "Connecting Client_2 ...");
rc = MQTTClient_connect(test6_c2, &opts2);
assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
rc = MQTTClient_subscribe(test6_c2, test6_will_topic, 2);
assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
/* now send the command which will break the connection and cause the will message to be sent */
rc = MQTTClient_publish(test6_c1, mqttsas_topic, strlen("TERMINATE"), "TERMINATE", 0, 0, NULL);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc);
/* test6_socket_close(((MQTTClients*)test6_c1)->c->socket); */
MyLog(LOGA_INFO, "Waiting to receive the will message");
count = 0;
while (test6_will_message_arrived != 1 && test6_connection_lost_called != 1 && ++count < 40)
#if defined(WIN32)
Sleep(1000L);
#else
sleep(1);
#endif
assert("will message arrived", test6_will_message_arrived == 1,
"will_message_arrived was %d\n", test6_will_message_arrived);
assert("connection lost called", test6_connection_lost_called == 1,
"connection_lost_called %d\n", test6_connection_lost_called);
rc = MQTTClient_unsubscribe(test6_c2, test6_will_topic);
assert("Good rc from unsubscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
rc = MQTTClient_isConnected(test6_c1);
assert("Client-2 still connected", rc == 1, "isconnected is %d", rc);
#endif
rc = MQTTClient_isConnected(test6_c1);
assert("Client-1 not connected", rc == 0, "isconnected is %d", rc);
/* rc = MQTTClient_disconnect(test6_c2, 100L); */
/* assert("Good rc from disconnect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc); */
MQTTClient_destroy(&test6_c1);
/* MQTTClient_destroy(&test6_c2); */
exit:
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.\n",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
int main(int argc, char** argv)
{
int rc = 0;
int (*tests[])() = {NULL, test1, test2, test3, test4, test5, test6};
getopts(argc, argv);
if (options.test_no == 0)
{ /* run all the tests */
for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
rc += tests[options.test_no](options); /* return number of failures. 0 = test succeeded */
}
else
rc = tests[options.test_no](options); /* run just the selected test */
if (failures == 0)
MyLog(LOGA_INFO, "verdict pass");
else
MyLog(LOGA_INFO, "verdict fail");
return rc;
}
#define MY_ID "@(#) stmqcom/pub1.c, stmqcom, cs 1.85 10/08/24 07:36:24"
/*--------------------------------------------------------------------*/
/* [Platforms]UNIX NT[/Platforms] */
/* [Title]MQ Telemetry MQTT C client SSL tests */
/* [/Title] */
/* [Testclasses]stcom1 stmqcom1[/Category] */
/* [Category]MQ Telemetry[/Category] */
/* */
/* Copyright IBM 2012 */
/* All rights reserved. */
/*--------------------------------------------------------------------*/
/**
* @file
* SSL tests for the MQ Telemetry MQTT C client
*/
#include "MQTTClient.h"
#include <string.h>
#include <stdlib.h>
#if !defined(_WINDOWS)
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAXHOSTNAMELEN 256
#define EAGAIN WSAEWOULDBLOCK
#define EINTR WSAEINTR
#define EINPROGRESS WSAEINPROGRESS
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOTCONN WSAENOTCONN
#define ECONNRESET WSAECONNRESET
#define snprintf _snprintf
#endif
#if defined(IOS)
char skeytmp[1024];
char ckeytmp[1024];
char persistenceStore[1024];
#else
char* persistenceStore = NULL;
#endif
#if 0
#include <logaX.h> /* For general log messages */
#define MyLog logaLine
#else
#define LOGA_DEBUG 0
#define LOGA_INFO 1
#include <stdarg.h>
#include <time.h>
#include <sys/timeb.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
void usage()
{
printf("Options:\n");
printf("\t--test_no <test_no> - Run test number <test_no>\n");
printf("\t--connection <mqtt URL> - Connect to <mqtt URL> for tests\n");
printf("\t--haconnections \"<mqtt URLs>\" - Use \"<mqtt URLs>\" as the list of servers for HA tests (space separated)\n");
printf("\t--client_key <key_file> - Use <key_file> as the client certificate for SSL authentication\n");
printf("\t--client_key_pass <password> - Use <password> to access the private key in the client certificate\n");
printf("\t--server_key <key_file> - Use <key_file> as the trusted certificate for server\n");
printf("\t--verbose - Enable verbose output \n");
printf("\tserver connection URLs should be in the form; (tcp|ssl)://hostname:port\n");
printf("\t--help - This help output\n");
exit(-1);
}
struct Options
{
char* connection; /**< connection to system under test. */
char** haconnections; /**< connection to system under test. */
int hacount;
char* client_key_file;
char* client_key_pass;
char* server_key_file;
int verbose;
int test_no;
} options =
{
"ssl://localhost:8883",
NULL,
0,
NULL,
NULL,
NULL,
0,
0,
};
void getopts(int argc, char** argv)
{
int count = 1;
while (count < argc)
{
if (strcmp(argv[count], "--help") == 0)
{
usage();
}
else if (strcmp(argv[count], "--test_no") == 0)
{
if (++count < argc)
options.test_no = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--connection") == 0)
{
if (++count < argc)
options.connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--haconnections") == 0)
{
if (++count < argc)
{
char* tok = strtok(argv[count], " ");
options.hacount = 0;
options.haconnections = malloc(sizeof(char*) * 5);
while (tok)
{
options.haconnections[options.hacount] = malloc(strlen(tok) + 1);
strcpy(options.haconnections[options.hacount], tok);
options.hacount++;
tok = strtok(NULL, " ");
}
}
else
usage();
}
else if (strcmp(argv[count], "--client_key") == 0)
{
if (++count < argc)
{
#if defined(IOS)
strcat(ckeytmp, getenv("HOME"));
strcat(ckeytmp, argv[count]);
options.client_key_file = ckeytmp;
#else
options.client_key_file = argv[count];
#endif
}
else
usage();
}
else if (strcmp(argv[count], "--client_key_pass") == 0)
{
if (++count < argc)
options.client_key_pass = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--server_key") == 0)
{
if (++count < argc)
{
#if defined(IOS)
strcat(skeytmp, getenv("HOME"));
strcat(skeytmp, argv[count]);
options.server_key_file = skeytmp;
#else
options.server_key_file = argv[count];
#endif
}
else
usage();
}
else if (strcmp(argv[count], "--verbose") == 0)
{
options.verbose = 1;
//TODO
printf("\nSetting verbose on\n");
}
count++;
}
#if defined(IOS)
strcpy(persistenceStore, getenv("HOME"));
strcat(persistenceStore, "/Library/Caches");
#endif
}
void MyLog(int LOGA_level, char* format, ...)
{
static char msg_buf[256];
va_list args;
struct timeb ts;
struct tm *timeinfo;
if (LOGA_level == LOGA_DEBUG && options.verbose == 0)
return;
ftime(&ts);
timeinfo = localtime(&ts.time);
strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
va_start(args, format);
vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf), format, args);
va_end(args);
printf("%s\n", msg_buf);
fflush(stdout);
}
#endif
#if defined(WIN32) || defined(_WINDOWS)
#define mqsleep(A) Sleep(1000*A)
#define START_TIME_TYPE DWORD
static DWORD start_time = 0;
START_TIME_TYPE start_clock(void)
{
return GetTickCount();
}
#elif defined(AIX)
#define mqsleep sleep
#define START_TIME_TYPE struct timespec
START_TIME_TYPE start_clock(void)
{
static struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
return start;
}
#else
#define mqsleep sleep
#define START_TIME_TYPE struct timeval
/* TODO - unused - remove? static struct timeval start_time; */
START_TIME_TYPE start_clock(void)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
return start_time;
}
#endif
#if defined(WIN32)
long elapsed(START_TIME_TYPE start_time)
{
return GetTickCount() - start_time;
}
#elif defined(AIX)
#define assert(a)
long elapsed(struct timespec start)
{
struct timespec now, res;
clock_gettime(CLOCK_REALTIME, &now);
ntimersub(now, start, res);
return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
}
#else
long elapsed(START_TIME_TYPE start_time)
{
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&now, &start_time, &res);
return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}
#endif
START_TIME_TYPE global_start_time;
#define assert(a, b, c, d) myassert(__FILE__, __LINE__, a, b, c, d)
#define assert1(a, b, c, d, e) myassert(__FILE__, __LINE__, a, b, c, d, e)
int tests = 0;
int failures = 0;
int myassert(char* filename, int lineno, char* description, int value, char* format, ...)
{
++tests;
if (!value)
{
va_list args;
++failures;
printf("Assertion failed, file %s, line %d, description: %s\n", filename, lineno, description);
va_start(args, format);
vprintf(format, args);
va_end(args);
}
else
MyLog(LOGA_DEBUG, "Assertion succeeded, file %s, line %d, description: %s", filename, lineno, description);
return value;
}
/*********************************************************************
Test: single-threaded client
*********************************************************************/
void singleThread_sendAndReceive(MQTTClient* c, int qos, char* test_topic)
{
MQTTClient_deliveryToken dt;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_message* m = NULL;
char* topicName = NULL;
int topicLen;
int i = 0;
int iterations = 50;
int rc;
MyLog(LOGA_DEBUG, "%d messages at QoS %d", iterations, qos);
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = qos;
pubmsg.retained = 0;
for (i = 0; i< iterations; ++i)
{
if (i % 10 == 0)
rc = MQTTClient_publish(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
else
rc = MQTTClient_publishMessage(c, test_topic, &pubmsg, &dt);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
if (qos > 0)
{
rc = MQTTClient_waitForCompletion(c, dt, 10000L);
assert("Good rc from waitforCompletion", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
}
rc = MQTTClient_receive(c, &topicName, &topicLen, &m, 10000);
assert("Good rc from receive", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
if (topicName)
{
MyLog(LOGA_DEBUG, "Message received on topic %s is %.*s", topicName, m->payloadlen, (char*)(m->payload));
if (pubmsg.payloadlen != m->payloadlen ||
memcmp(m->payload, pubmsg.payload, m->payloadlen) != 0)
{
failures++;
MyLog(LOGA_INFO, "Error: wrong data - received lengths %d %d", pubmsg.payloadlen, m->payloadlen);
break;
}
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
}
else
printf("No message received within timeout period\n");
}
/* receive any outstanding messages */
MQTTClient_receive(c, &topicName, &topicLen, &m, 1000);
while (topicName)
{
printf("Message received on topic %s is %.*s.\n", topicName, m->payloadlen, (char*)(m->payload));
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
MQTTClient_receive(c, &topicName, &topicLen, &m, 1000);
}
}
/*********************************************************************
Test: multi-threaded client using callbacks
*********************************************************************/
volatile int multiThread_arrivedcount = 0;
int multiThread_deliveryCompleted = 0;
MQTTClient_message multiThread_pubmsg = MQTTClient_message_initializer;
void multiThread_deliveryComplete(void* context, MQTTClient_deliveryToken dt)
{
++multiThread_deliveryCompleted;
}
int multiThread_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* m)
{
++multiThread_arrivedcount;
MyLog(LOGA_DEBUG, "Callback: %d message received on topic %s is %.*s.",
multiThread_arrivedcount, topicName, m->payloadlen, (char*)(m->payload));
if (multiThread_pubmsg.payloadlen != m->payloadlen ||
memcmp(m->payload, multiThread_pubmsg.payload, m->payloadlen) != 0)
{
failures++;
MyLog(LOGA_INFO, "Error: wrong data received lengths %d %d\n", multiThread_pubmsg.payloadlen, m->payloadlen);
}
MQTTClient_free(topicName);
MQTTClient_freeMessage(&m);
return 1;
}
void multiThread_sendAndReceive(MQTTClient* c, int qos, char* test_topic)
{
MQTTClient_deliveryToken dt;
int i = 0;
int iterations = 50;
int rc = 0;
int wait_seconds = 0;
multiThread_deliveryCompleted = 0;
multiThread_arrivedcount = 0;
MyLog(LOGA_DEBUG, "%d messages at QoS %d", iterations, qos);
multiThread_pubmsg.payload = "a much longer message that we can shorten to the extent that we need to";
multiThread_pubmsg.payloadlen = 27;
multiThread_pubmsg.qos = qos;
multiThread_pubmsg.retained = 0;
for (i = 1; i <= iterations; ++i)
{
if (i % 10 == 0)
rc = MQTTClient_publish(c, test_topic, multiThread_pubmsg.payloadlen, multiThread_pubmsg.payload,
multiThread_pubmsg.qos, multiThread_pubmsg.retained, NULL);
else
rc = MQTTClient_publishMessage(c, test_topic, &multiThread_pubmsg, &dt);
assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
#if defined(WIN32)
Sleep(100);
#else
usleep(100000L);
#endif
wait_seconds = 10;
while ((multiThread_arrivedcount < i) && (wait_seconds-- > 0))
{
MyLog(LOGA_DEBUG, "Arrived %d count %d", multiThread_arrivedcount, i);
#if defined(WIN32)
Sleep(1000);
#else
usleep(1000000L);
#endif
}
assert("Message Arrived", wait_seconds > 0,
"Time out waiting for message %d\n", i );
}
if (qos > 0)
{
/* MQ Telemetry can send a message to a subscriber before the server has
completed the QoS 2 handshake with the publisher. For QoS 1 and 2,
allow time for the final delivery complete callback before checking
that all expected callbacks have been made */
wait_seconds = 10;
while ((multiThread_deliveryCompleted < iterations) && (wait_seconds-- > 0))
{
MyLog(LOGA_DEBUG, "Delivery Completed %d count %d", multiThread_deliveryCompleted, i);
#if defined(WIN32)
Sleep(1000);
#else
usleep(1000000L);
#endif
}
assert("All Deliveries Complete", wait_seconds > 0,
"Number of deliveryCompleted callbacks was %d\n",
multiThread_deliveryCompleted);
}
}
/*********************************************************************
Test1: SSL connection to non SSL MQTT server
*********************************************************************/
int test1(struct Options options)
{
char* testname = "test1";
char* test_topic = "C client SSL test1";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 1 - connection to nonSSL MQTT server");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test1", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d \n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
opts.ssl->enableServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_FAILURE, "rc was %d ", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2a: Mutual SSL Authentication - Certificates in place on client and server - single threaded
*********************************************************************/
int test2a_s(struct Options options)
{
char* testname = "test2a_s";
char* test_topic = "C client test2a_s";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 2a_s - Mutual SSL authentication - single threaded client using receive");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test2a_s", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
singleThread_sendAndReceive(c, 0, test_topic);
singleThread_sendAndReceive(c, 1, test_topic);
singleThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
/* Just to make sure we can connect again */
if (!(assert("Connect successful", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2a: Mutual SSL Authentication - Certificates in place on client and server - multi threaded
*********************************************************************/
int test2a_m(struct Options options)
{
char* testname = "test2a_m";
char* test_topic = "C client test2a_m";
int subsqos = 2;
/* TODO - usused - remove ? MQTTClient_deliveryToken* dt = NULL; */
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 2a_m - Mutual SSL authentication - multi-threaded client using callbacks");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test2a_m", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
if (!(assert("Good rc from setCallbacks", (rc = MQTTClient_setCallbacks(c, NULL, NULL, multiThread_messageArrived, multiThread_deliveryComplete)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
multiThread_sendAndReceive(c, 0, test_topic);
multiThread_sendAndReceive(c, 1, test_topic);
multiThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2b: Mutual SSL Authentication - Server does not have Client cert
*********************************************************************/
int test2b(struct Options options)
{
char* testname = "test2b";
char* test_topic = "C client test2b";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 2b - connection to SSL MQTT server with clientauth=req but server does not have client cert");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test2b", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_FAILURE, "rc was %d\n", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2c: Mutual SSL Authentication - Client does not have Server cert
*********************************************************************/
int test2c(struct Options options)
{
char* testname = "test2c";
char* test_topic = "C client test2c";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 2c - connection to SSL MQTT server, server auth enabled but unknown cert");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test2c", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_FAILURE, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test3a: Server Authentication - server certificate in client trust store - single threaded
*********************************************************************/
int test3a_s(struct Options options)
{
char* testname = "test3a_s";
char* test_topic = "C client test3a_s";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 3a_s - Server authentication - single threaded client using receive");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test3a_s", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
singleThread_sendAndReceive(c, 0, test_topic);
singleThread_sendAndReceive(c, 1, test_topic);
singleThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
/* Just to make sure we can connect again */
if (!(assert("Connect successful", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test3a: Server Authentication - server certificate in client trust store - multi threaded
*********************************************************************/
int test3a_m(struct Options options)
{
char* testname = "test3a_m";
char* test_topic = "C client test3a_m";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 3a_m - Server authentication - multi-threaded client using callbacks");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test3a_m", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
if (!(assert("Good rc from setCallbacks", (rc = MQTTClient_setCallbacks(c, NULL, NULL, multiThread_messageArrived, multiThread_deliveryComplete)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
multiThread_sendAndReceive(c, 0, test_topic);
multiThread_sendAndReceive(c, 1, test_topic);
multiThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test3b: Server Authentication - Client does not have server cert
*********************************************************************/
int test3b(struct Options options)
{
char* testname = "test3b";
char* test_topic = "C client test3b";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 3b - connection to SSL MQTT server with clientauth=opt but client does not have server cert");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test3b", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_FAILURE, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test4_s: Accept invalid server certificates - single threaded
*********************************************************************/
int test4_s(struct Options options)
{
char* testname = "test4_s";
char* test_topic = "C client test4_s";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 4_s - accept invalid server certificates - single threaded");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test4_s", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
opts.ssl->enableServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
singleThread_sendAndReceive(c, 0, test_topic);
singleThread_sendAndReceive(c, 1, test_topic);
singleThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
/* Just to make sure we can connect again */
if (!(assert("Connect successful", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test4_m: Accept invalid server certificates - multi threaded
*********************************************************************/
int test4_m(struct Options options)
{
char* testname = "test4_m";
char* test_topic = "C client test4_m";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 4_m - accept invalid server certificates - multi-threaded");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test4_m", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "TLSv1.2";
opts.ssl->enableServerCertAuth = 0;
if (!(assert("Good rc from setCallbacks", (rc = MQTTClient_setCallbacks(c, NULL, NULL, multiThread_messageArrived, multiThread_deliveryComplete)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
multiThread_sendAndReceive(c, 0, test_topic);
multiThread_sendAndReceive(c, 1, test_topic);
multiThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test5a: Anonymous ciphers - server auth disabled
*********************************************************************/
int test5a(struct Options options)
{
char* testname = "test5a";
char* test_topic = "C client SSL test5a";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 5a - Anonymous ciphers - server authentication disabled");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test5a", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
opts.ssl->enabledCipherSuites = "aNULL";
opts.ssl->enableServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
singleThread_sendAndReceive(c, 0, test_topic);
singleThread_sendAndReceive(c, 1, test_topic);
singleThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
/* Just to make sure we can connect again */
if (!(assert("Connect successful", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test5b: Anonymous ciphers - server auth enabled
*********************************************************************/
int test5b(struct Options options)
{
char* testname = "test5b";
char* test_topic = "C client SSL test5b";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 5b - Anonymous ciphers - server authentication enabled");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test5b", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
opts.ssl->enabledCipherSuites = "aNULL";
opts.ssl->enableServerCertAuth = 1;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
singleThread_sendAndReceive(c, 0, test_topic);
singleThread_sendAndReceive(c, 1, test_topic);
singleThread_sendAndReceive(c, 2, test_topic);
MyLog(LOGA_DEBUG, "Stopping\n");
if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
/* Just to make sure we can connect again */
if (!(assert("Connect successful", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test5c: Anonymous ciphers - client not using anonymous ciphers
*********************************************************************/
int test5c(struct Options options)
{
char* testname = "test5c";
char* test_topic = "C client SSL test5c";
int subsqos = 2;
MQTTClient c;
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
int rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 5c - Anonymous ciphers - client not using anonymous cipher");
if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test5c", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
opts.ssl->enableServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_FAILURE, "rc was %d", rc)))
goto exit;
exit:
MQTTClient_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
typedef struct
{
char* clientID; /**< the string id of the client */
char* username; /**< MQTT v3.1 user name */
char* password; /**< MQTT v3.1 password */
unsigned int cleansession : 1; /**< MQTT clean session flag */
unsigned int connected : 1; /**< whether it is currently connected */
unsigned int good : 1; /**< if we have an error on the socket we turn this off */
unsigned int ping_outstanding : 1;
unsigned int connect_state : 2;
int socket;
int msgID;
int keepAliveInterval;
int retryInterval;
int maxInflightMessages;
time_t lastContact;
void* will;
void* inboundMsgs;
void* outboundMsgs; /**< in flight */
void* messageQueue;
void* phandle; /* the persistence handle */
MQTTClient_persistence* persistence; /* a persistence implementation */
int connectOptionsVersion;
} Clients;
typedef struct
{
char* serverURI;
Clients* c;
MQTTClient_connectionLost* cl;
MQTTClient_messageArrived* ma;
MQTTClient_deliveryComplete* dc;
void* context;
int connect_sem;
int rc; /* getsockopt return code in connect */
int connack_sem;
int suback_sem;
int unsuback_sem;
void* pack;
} MQTTClients;
int main(int argc, char** argv)
{
int* numtests = &tests;
int rc = 0;
int (*tests[])() = {NULL, test1, test2a_s, test2a_m, test2b, test2c, test3a_s, test3a_m, test3b, test4_s, test4_m, test5a, test5b, test5c};
getopts(argc, argv);
if (options.test_no == 0)
{ /* run all the tests */
for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
rc += tests[options.test_no](options); /* return number of failures. 0 = test succeeded */
}
else
rc = tests[options.test_no](options); /* run just the selected test */
MyLog(LOGA_INFO, "Total tests run: %d", *numtests);
if (rc == 0)
MyLog(LOGA_INFO, "verdict pass");
else
MyLog(LOGA_INFO, "verdict fail");
return rc;
}
/*--------------------------------------------------------------------*/
/* [Platforms]UNIX NT[/Platforms] */
/* [Title]MQ Telemetry MQTT C client tests */
/* [/Title] */
/* [Testclasses]stcom1 stmqcom1[/Category] */
/* [Category]MQ Telemetry[/Category] */
/* */
/* Copyright IBM 2012 */
/* All rights reserved. */
/*--------------------------------------------------------------------*/
/**
* @file
* Tests for the MQ Telemetry MQTT C client
*/
/*
#if !defined(_RTSHEADER)
#include <rts.h>
#endif
*/
#include "MQTTAsync.h"
#include <string.h>
#include <stdlib.h>
#if !defined(_WINDOWS)
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAXHOSTNAMELEN 256
#define EAGAIN WSAEWOULDBLOCK
#define EINTR WSAEINTR
#define EINPROGRESS WSAEINPROGRESS
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOTCONN WSAENOTCONN
#define ECONNRESET WSAECONNRESET
#endif
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
void usage()
{
printf("help!!\n");
exit(-1);
}
struct Options
{
char* connection; /**< connection to system under test. */
char** haconnections;
int hacount;
int verbose;
int test_no;
int size; /**< size of big message */
} options =
{
"tcp://localhost:1883",
NULL,
0,
0,
-1,
5000000,
};
void getopts(int argc, char** argv)
{
int count = 1;
while (count < argc)
{
if (strcmp(argv[count], "--test_no") == 0)
{
if (++count < argc)
options.test_no = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--size") == 0)
{
if (++count < argc)
options.size = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--connection") == 0)
{
if (++count < argc)
options.connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--haconnections") == 0)
{
if (++count < argc)
{
char* tok = strtok(argv[count], " ");
options.hacount = 0;
options.haconnections = malloc(sizeof(char*) * 5);
while (tok)
{
options.haconnections[options.hacount] = malloc(strlen(tok) + 1);
strcpy(options.haconnections[options.hacount], tok);
options.hacount++;
tok = strtok(NULL, " ");
}
}
else
usage();
}
else if (strcmp(argv[count], "--verbose") == 0)
options.verbose = 1;
count++;
}
}
#if 0
#include <logaX.h> /* For general log messages */
#define MyLog logaLine
#else
#define LOGA_DEBUG 0
#define LOGA_INFO 1
#include <stdarg.h>
#include <time.h>
#include <sys/timeb.h>
void MyLog(int LOGA_level, char* format, ...)
{
static char msg_buf[256];
va_list args;
struct timeb ts;
struct tm *timeinfo;
if (LOGA_level == LOGA_DEBUG && options.verbose == 0)
return;
ftime(&ts);
timeinfo = localtime(&ts.time);
strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
va_start(args, format);
vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf), format, args);
va_end(args);
printf("%s\n", msg_buf);
fflush(stdout);
}
#endif
#if defined(WIN32) || defined(_WINDOWS)
#define mqsleep(A) Sleep(1000*A)
#define START_TIME_TYPE DWORD
static DWORD start_time = 0;
START_TIME_TYPE start_clock(void)
{
return GetTickCount();
}
#elif defined(AIX)
#define mqsleep sleep
#define START_TIME_TYPE struct timespec
START_TIME_TYPE start_clock(void)
{
static struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
return start;
}
#else
#define mqsleep sleep
#define START_TIME_TYPE struct timeval
/* TODO - unused - remove? static struct timeval start_time; */
START_TIME_TYPE start_clock(void)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
return start_time;
}
#endif
#if defined(WIN32)
long elapsed(START_TIME_TYPE start_time)
{
return GetTickCount() - start_time;
}
#elif defined(AIX)
#define assert(a)
long elapsed(struct timespec start)
{
struct timespec now, res;
clock_gettime(CLOCK_REALTIME, &now);
ntimersub(now, start, res);
return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
}
#else
long elapsed(START_TIME_TYPE start_time)
{
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&now, &start_time, &res);
return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}
#endif
START_TIME_TYPE global_start_time;
#define assert(a, b, c, d) myassert(__FILE__, __LINE__, a, b, c, d)
#define assert1(a, b, c, d, e) myassert(__FILE__, __LINE__, a, b, c, d, e)
int tests = 0;
int failures = 0;
void myassert(char* filename, int lineno, char* description, int value, char* format, ...)
{
++tests;
if (!value)
{
va_list args;
++failures;
printf("Assertion failed, file %s, line %d, description: %s\n", filename, lineno, description);
va_start(args, format);
vprintf(format, args);
va_end(args);
}
else
MyLog(LOGA_DEBUG, "Assertion succeeded, file %s, line %d, description: %s", filename, lineno, description);
}
volatile int test_finished = 0;
char* test_topic = "async test topic";
void test1_onDisconnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In onDisconnect callback %p", c);
test_finished = 1;
}
void test1_onUnsubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In onUnsubscribe onSuccess callback %p", c);
opts.onSuccess = test1_onDisconnect;
opts.context = c;
rc = MQTTAsync_disconnect(c, &opts);
assert("Disconnect successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
int test1_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
MQTTAsync c = (MQTTAsync)context;
static int message_count = 0;
int rc;
MyLog(LOGA_DEBUG, "In messageArrived callback %p", c);
if (++message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = test1_onUnsubscribe;
opts.context = c;
rc = MQTTAsync_unsubscribe(c, test_topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test1_onSubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback %p granted qos %d", c, response->alt.qos);
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
}
void test1_onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p", context);
opts.onSuccess = test1_onSubscribe;
opts.context = c;
rc = MQTTAsync_subscribe(c, test_topic, 2, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
test_finished = 1;
}
/*********************************************************************
Test1: Basic connect, subscribe send and receive.
*********************************************************************/
int test1(struct Options options)
{
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test1";
failures = 0;
MyLog(LOGA_INFO, "Starting test 1 - asynchronous connect");
rc = MQTTAsync_create(&c, options.connection, "async_test",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
MQTTAsync_destroy(&c);
goto exit;
}
rc = MQTTAsync_setCallbacks(c, c, NULL, test1_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
opts.onSuccess = test1_onConnect;
opts.onFailure = NULL;
opts.context = c;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
rc = 0;
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
goto exit;
while (!test_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&c);
exit:
MyLog(LOGA_INFO, "TEST1: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
int test2_onFailure_called = 0;
void test2_onFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In connect onFailure callback, context %p", context);
test2_onFailure_called++;
test_finished = 1;
}
void test2_onConnect(void* context, MQTTAsync_successData* response)
{
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p\n", context);
assert("Connect should not succeed", 0, "connect success callback was called", 0);
test_finished = 1;
}
/*********************************************************************
Test2: connect timeout
*********************************************************************/
int test2(struct Options options)
{
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test2";
test_finished = 0;
MyLog(LOGA_INFO, "Starting test 2 - connect timeout");
rc = MQTTAsync_create(&c, "tcp://9.20.96.160:66", "connect timeout",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
MQTTAsync_destroy(&c);
goto exit;
}
rc = MQTTAsync_setCallbacks(c, c, NULL, test1_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.connectTimeout = 5;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
opts.onSuccess = test2_onConnect;
opts.onFailure = test2_onFailure;
opts.context = c;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
rc = 0;
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
goto exit;
while (!test_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&c);
exit:
assert("Connect onFailure should be called once", test2_onFailure_called == 1,
"connect onFailure was called %d times", test2_onFailure_called);
MyLog(LOGA_INFO, "TEST2: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
typedef struct
{
MQTTAsync c;
int index;
char clientid[24];
char test_topic[100];
int message_count;
} client_data;
void test3_onDisconnect(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MyLog(LOGA_DEBUG, "In onDisconnect callback for client \"%s\"", cd->clientid);
test_finished++;
}
void test3_onPublish(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MyLog(LOGA_DEBUG, "In QoS 0 onPublish callback for client \"%s\"", cd->clientid);
}
void test3_onUnsubscribe(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In onUnsubscribe onSuccess callback \"%s\"", cd->clientid);
opts.onSuccess = test3_onDisconnect;
opts.context = cd;
rc = MQTTAsync_disconnect(cd->c, &opts);
assert("Disconnect successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
int test3_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
client_data* cd = (client_data*)context;
int rc;
MyLog(LOGA_DEBUG, "In messageArrived callback \"%s\" message count ", cd->clientid);
if (++cd->message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 25;
pubmsg.qos = 1;
pubmsg.retained = 0;
rc = MQTTAsync_sendMessage(cd->c, cd->test_topic, &pubmsg, &opts);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
else if (cd->message_count == 2)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = "a QoS 0 message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 29;
pubmsg.qos = 0;
pubmsg.retained = 0;
opts.context = cd;
opts.onSuccess = test3_onPublish;
rc = MQTTAsync_sendMessage(cd->c, cd->test_topic, &pubmsg, &opts);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = test3_onUnsubscribe;
opts.context = cd;
rc = MQTTAsync_unsubscribe(cd->c, cd->test_topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test3_onSubscribe(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback \"%s\"", cd->clientid);
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(cd->c, cd->test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
void test3_onConnect(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, \"%s\"", cd->clientid);
opts.onSuccess = test3_onSubscribe;
opts.context = cd;
rc = MQTTAsync_subscribe(cd->c, cd->test_topic, 2, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
test_finished++;
}
void test3_onFailure(void* context, MQTTAsync_failureData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
assert("Should have connected", 0, "failed to connect", NULL);
MyLog(LOGA_DEBUG, "In connect onFailure callback, \"%s\" rc %d\n", cd->clientid, response->code);
if (response->message)
MyLog(LOGA_DEBUG, "In connect onFailure callback, \"%s\"\n", response->message);
test_finished++;
}
/*********************************************************************
Test3: More than one client object - simultaneous working.
*********************************************************************/
int test3(struct Options options)
{
#define TEST3_CLIENTS 10
int num_clients = TEST3_CLIENTS;
int subsqos = 2;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
int i;
client_data clientdata[TEST3_CLIENTS];
test_finished = 0;
MyLog(LOGA_INFO, "Starting test 3 - multiple connections");
for (i = 0; i < num_clients; ++i)
{
sprintf(clientdata[i].clientid, "async_test3_num_%d", i);
sprintf(clientdata[i].test_topic, "async test3 topic num %d", i);
clientdata[i].index = i;
clientdata[i].message_count = 0;
rc = MQTTAsync_create(&(clientdata[i].c), options.connection, clientdata[i].clientid,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
rc = MQTTAsync_setCallbacks(clientdata[i].c, &clientdata[i], NULL, test3_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.onSuccess = test3_onConnect;
opts.onFailure = test3_onFailure;
opts.context = &clientdata[i];
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(clientdata[i].c, &opts);
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
while (test_finished < num_clients)
{
MyLog(LOGA_DEBUG, "num_clients %d test_finished %d\n", num_clients, test_finished);
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
}
MyLog(LOGA_DEBUG, "TEST3: destroying clients");
for (i = 0; i < num_clients; ++i)
MQTTAsync_destroy(&clientdata[i].c);
exit:
MyLog(LOGA_INFO, "TEST3: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
void* test4_payload = NULL;
int test4_payloadlen = 0;
void test4_onPublish(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In publish onSuccess callback, context %p", context);
}
int test4_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
MQTTAsync c = (MQTTAsync)context;
static int message_count = 0;
int rc, i;
MyLog(LOGA_DEBUG, "In messageArrived callback %p", c);
assert("Message size correct", message->payloadlen == test4_payloadlen,
"message size was %d", message->payloadlen);
for (i = 0; i < options.size; ++i)
{
if (((char*)test4_payload)[i] != ((char*)message->payload)[i])
{
assert("Message contents correct", ((char*)test4_payload)[i] != ((char*)message->payload)[i],
"message content was %c", ((char*)message->payload)[i]);
break;
}
}
if (++message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = test4_payload;
pubmsg.payloadlen = test4_payloadlen;
pubmsg.qos = 1;
pubmsg.retained = 0;
opts.onSuccess = test4_onPublish;
opts.context = c;
rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts);
}
else if (message_count == 2)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = test4_payload;
pubmsg.payloadlen = test4_payloadlen;
pubmsg.qos = 0;
pubmsg.retained = 0;
opts.onSuccess = test4_onPublish;
opts.context = c;
rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = test1_onUnsubscribe;
opts.context = c;
rc = MQTTAsync_unsubscribe(c, test_topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test4_onSubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc, i;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback %p", c);
pubmsg.payload = test4_payload = malloc(options.size);
pubmsg.payloadlen = test4_payloadlen = options.size;
srand(33);
for (i = 0; i < options.size; ++i)
((char*)pubmsg.payload)[i] = rand() % 256;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
}
void test4_onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p", context);
opts.onSuccess = test4_onSubscribe;
opts.context = c;
rc = MQTTAsync_subscribe(c, test_topic, 2, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
test_finished = 1;
}
/*********************************************************************
Test4: Send and receive big messages
*********************************************************************/
int test4(struct Options options)
{
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test4";
test_finished = failures = 0;
MyLog(LOGA_INFO, "Starting test 4 - big messages");
rc = MQTTAsync_create(&c, options.connection, "async_test_4",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
MQTTAsync_destroy(&c);
goto exit;
}
rc = MQTTAsync_setCallbacks(c, c, NULL, test4_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
opts.onSuccess = test4_onConnect;
opts.onFailure = NULL;
opts.context = c;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
rc = 0;
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
goto exit;
while (!test_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(1000L);
#endif
MQTTAsync_destroy(&c);
exit:
MyLog(LOGA_INFO, "TEST4: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
void trace_callback(enum MQTTASYNC_TRACE_LEVELS level, char* message)
{
printf("Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
int rc = 0;
int (*tests[])() = {NULL, test1, test2, test3, test4}; /* indexed starting from 1 */
char** info;
getopts(argc, argv);
MQTTAsync_setTraceCallback(trace_callback);
info = MQTTAsync_getVersionInfo();
while (*info)
printf("Version info \"%s\"\n", *info++);
if (options.test_no == -1)
{ /* run all the tests */
for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
{
failures = 0;
MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
rc += tests[options.test_no](options); /* return number of failures. 0 = test succeeded */
}
}
else
{
MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
rc = tests[options.test_no](options); /* run just the selected test */
}
if (failures == 0)
MyLog(LOGA_INFO, "verdict pass");
else
MyLog(LOGA_INFO, "verdict fail");
return rc;
}
#define MY_ID "@(#) stmqcom/xrctest5.c, stmqcom, cs 1.85 12/11/29 07:36:24"
/*--------------------------------------------------------------------*/
/* [Platforms]UNIX NT[/Platforms] */
/* [Title]MQ Telemetry MQTT Asynchronous C client SSL tests */
/* [/Title] */
/* [Testclasses]stcom1 stmqcom1[/Category] */
/* [Category]MQ Telemetry[/Category] */
/* */
/* Copyright IBM 2012 */
/* All rights reserved. */
/*--------------------------------------------------------------------*/
/**
* @file
* SSL tests for the MQ Telemetry Asynchronous MQTT C client
*/
#if !defined(_WINDOWS)
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAXHOSTNAMELEN 256
#define EAGAIN WSAEWOULDBLOCK
#define EINTR WSAEINTR
#define EINPROGRESS WSAEINPROGRESS
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOTCONN WSAENOTCONN
#define ECONNRESET WSAECONNRESET
#define snprintf _snprintf
#endif
#include "MQTTAsync.h"
#include <string.h>
#include <stdlib.h>
#if defined(IOS)
char skeytmp[1024];
char ckeytmp[1024];
char persistenceStore[1024];
#else
char* persistenceStore = NULL;
#endif
#if 0
#include <logaX.h> /* For general log messages */
#define MyLog logaLine
#else
#define LOGA_DEBUG 0
#define LOGA_INFO 1
#include <stdarg.h>
#include <time.h>
#include <sys/timeb.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
void usage()
{
printf("Options:\n");
printf("\t--test_no <test_no> - Run test number <test_no>\n");
printf("\t--server <mqtt URL> - Connect to <mqtt URL> for tests\n");
printf("\t--haserver <mqtt URL> - Use <mqtt URL> as the secondary server for HA tests\n");
printf("\t--client_key <key_file> - Use <key_file> as the client certificate for SSL authentication\n");
printf("\t--client_key_pass <password> - Use <password> to access the private key in the client certificate\n");
printf("\t--server_key <key_file> - Use <key_file> as the trusted certificate for server\n");
printf("\t--verbose - Enable verbose output \n");
printf("\tserver connection URLs should be in the form; (tcp|ssl)://hostname:port\n");
printf("\t--help - This help output\n");
exit(-1);
}
struct Options
{
char* connection; /**< connection to system under test. */
char** haconnections;
int hacount;
char* client_key_file;
char* client_key_pass;
char* server_key_file;
int verbose;
int test_no;
int size;
} options =
{
"ssl://localhost:8883",
NULL,
0,
NULL,
NULL,
NULL,
0,
0,
5000000
};
typedef struct
{
MQTTAsync client;
char clientid[24];
char topic[100];
int maxmsgs;
int rcvdmsgs[3];
int sentmsgs[3];
int testFinished;
int subscribed;
} AsyncTestClient;
#define AsyncTestClient_initializer {NULL, "\0", "\0", 0, {0, 0, 0}, {0, 0, 0}, 0, 0}
void getopts(int argc, char** argv)
{
int count = 1;
while (count < argc)
{
if (strcmp(argv[count], "--help") == 0)
{
usage();
}
else if (strcmp(argv[count], "--test_no") == 0)
{
if (++count < argc)
options.test_no = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--connection") == 0)
{
if (++count < argc)
options.connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--haconnections") == 0)
{
if (++count < argc)
{
char* tok = strtok(argv[count], " ");
options.hacount = 0;
options.haconnections = malloc(sizeof(char*) * 5);
while (tok)
{
options.haconnections[options.hacount] = malloc(strlen(tok) + 1);
strcpy(options.haconnections[options.hacount], tok);
options.hacount++;
tok = strtok(NULL, " ");
}
}
else
usage();
}
else if (strcmp(argv[count], "--client_key") == 0)
{
if (++count < argc)
{
#if defined(IOS)
strcat(ckeytmp, getenv("HOME"));
strcat(ckeytmp, argv[count]);
options.client_key_file = ckeytmp;
#else
options.client_key_file = argv[count];
#endif
}
else
usage();
}
else if (strcmp(argv[count], "--client_key_pass") == 0)
{
if (++count < argc)
options.client_key_pass = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--server_key") == 0)
{
if (++count < argc)
{
#if defined(IOS)
strcat(skeytmp, getenv("HOME"));
strcat(skeytmp, argv[count]);
options.server_key_file = skeytmp;
#else
options.server_key_file = argv[count];
#endif
}
else
usage();
}
else if (strcmp(argv[count], "--verbose") == 0)
{
options.verbose = 1;
//TODO
printf("\nSetting verbose on\n");
}
count++;
}
#if defined(IOS)
strcpy(persistenceStore, getenv("HOME"));
strcat(persistenceStore, "/Library/Caches");
#endif
}
void MyLog(int LOGA_level, char* format, ...)
{
static char msg_buf[256];
va_list args;
struct timeb ts;
struct tm *timeinfo;
if (LOGA_level == LOGA_DEBUG && options.verbose == 0)
return;
ftime(&ts);
timeinfo = localtime(&ts.time);
strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
va_start(args, format);
vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf),
format, args);
va_end(args);
printf("%s\n", msg_buf);
fflush(stdout);
}
#endif
#if defined(WIN32) || defined(_WINDOWS)
#define mqsleep(A) Sleep(1000*A)
#define START_TIME_TYPE DWORD
static DWORD start_time = 0;
START_TIME_TYPE start_clock(void)
{
return GetTickCount();
}
#elif defined(AIX)
#define mqsleep sleep
#define START_TIME_TYPE struct timespec
START_TIME_TYPE start_clock(void)
{
static struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
return start;
}
#else
#define mqsleep sleep
#define START_TIME_TYPE struct timeval
/* TODO - unused - remove? static struct timeval start_time; */
START_TIME_TYPE start_clock(void)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
return start_time;
}
#endif
#if defined(WIN32)
long elapsed(START_TIME_TYPE start_time)
{
return GetTickCount() - start_time;
}
#elif defined(AIX)
#define assert(a)
long elapsed(struct timespec start)
{
struct timespec now, res;
clock_gettime(CLOCK_REALTIME, &now);
ntimersub(now, start, res);
return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
}
#else
long elapsed(START_TIME_TYPE start_time)
{
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&now, &start_time, &res);
return (res.tv_sec) * 1000 + (res.tv_usec) / 1000;
}
#endif
START_TIME_TYPE global_start_time;
#define assert(a, b, c, d) myassert(__FILE__, __LINE__, a, b, c, d)
#define assert1(a, b, c, d, e) myassert(__FILE__, __LINE__, a, b, c, d, e)
#define MAXMSGS 30;
int tests = 0;
int failures = 0;
int myassert(char* filename, int lineno, char* description, int value,
char* format, ...)
{
++tests;
if (!value)
{
va_list args;
++failures;
printf("Assertion failed, file %s, line %d, description: %s", filename, lineno, description);
va_start(args, format);
vprintf(format, args);
va_end(args);
}
else
MyLog(LOGA_DEBUG,
"Assertion succeeded, file %s, line %d, description: %s",
filename, lineno, description);
return value;
}
/*********************************************************************
Async Callbacks - generic callbacks for send/receive tests
*********************************************************************/
void asyncTestOnDisconnect(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In asyncTestOnDisconnect callback, %s", tc->clientid);
tc->testFinished = 1;
}
void asyncTestOnDisconnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In asyncTestOnDisconnectFailure callback, %s", tc->clientid);
failures++;
tc->testFinished = 1;
}
void asyncTestOnSend(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
//int qos = response->alt.pub.message.qos;
MyLog(LOGA_DEBUG, "In asyncTestOnSend callback, %s", tc->clientid);
}
void asyncTestOnSendFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In asyncTestOnSendFailure callback, %s", tc->clientid);
tc->testFinished = 1;
failures++;
}
void asyncTestOnSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In asyncTestOnSubscribeFailure callback, %s",
tc->clientid);
assert("There should be no failures in this test. ", 0, "asyncTestOnSubscribeFailure callback was called\n", 0);
tc->testFinished = 1;
failures++;
}
void asyncTestOnUnsubscribe(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In asyncTestOnUnsubscribe callback, %s", tc->clientid);
opts.onSuccess = asyncTestOnDisconnect;
opts.onFailure = asyncTestOnDisconnectFailure;
opts.context = tc;
MQTTAsync_disconnect(tc->client, &opts);
}
void asyncTestOnUnsubscribeFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In asyncTestOnUnsubscribeFailure callback, %s", tc->clientid);
assert("There should be no failures in this test. ", 0, "asyncTestOnUnsubscribeFailure callback was called\n", 0);
tc->testFinished = 1;
failures++;
}
void asyncTestOnSubscribe(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
int rc, i;
MyLog(LOGA_DEBUG, "In asyncTestOnSubscribe callback, %s", tc->clientid);
tc->subscribed = 1;
for (i = 0; i < 3; i++)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload
= "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = i;
pubmsg.retained = 0;
opts.onSuccess = asyncTestOnSend;
opts.onFailure = asyncTestOnSendFailure;
opts.context = tc;
rc = MQTTAsync_send(tc->client, tc->topic, pubmsg.payloadlen,
pubmsg.payload, pubmsg.qos, pubmsg.retained, &opts);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
tc->sentmsgs[i]++;
MyLog(LOGA_DEBUG, "Maxmsgs %d", tc->maxmsgs);
}
}
int asyncTestMessageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
{
int rc;
AsyncTestClient* tc = (AsyncTestClient*) context;
tc->rcvdmsgs[m->qos]++;
//printf("Received messages: %d\n", tc->rcvdmsgs[m->qos]);
MyLog(
LOGA_DEBUG,
"In asyncTestMessageArrived callback, %s total to exit %d, total received %d,%d,%d",
tc->clientid, (tc->maxmsgs * 3), tc->rcvdmsgs[0], tc->rcvdmsgs[1],
tc->rcvdmsgs[2]);
if (tc->sentmsgs[m->qos] < tc->maxmsgs)
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
opts.onSuccess = asyncTestOnSend;
opts.onFailure = asyncTestOnSendFailure;
opts.context = tc;
pubmsg.payload
= "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = m->qos;
pubmsg.retained = 0;
rc = MQTTAsync_send(tc->client, tc->topic, pubmsg.payloadlen,
pubmsg.payload, pubmsg.qos, pubmsg.retained, &opts);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d messages sent %d,%d,%d", rc);
MyLog(LOGA_DEBUG, "Messages sent %d,%d,%d", tc->sentmsgs[0],
tc->sentmsgs[1], tc->sentmsgs[2]);
tc->sentmsgs[m->qos]++;
}
if ((tc->rcvdmsgs[0] + tc->rcvdmsgs[1] + tc->rcvdmsgs[2]) == (tc->maxmsgs
* 3))
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MyLog(LOGA_DEBUG, "Ready to unsubscribe");
opts.onSuccess = asyncTestOnUnsubscribe;
opts.onFailure = asyncTestOnUnsubscribeFailure;
opts.context = tc;
rc = MQTTAsync_unsubscribe(tc->client, tc->topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MyLog(LOGA_DEBUG, "Leaving asyncTestMessageArrived callback");
MQTTAsync_freeMessage(&m);
MQTTAsync_free(topicName);
return 1;
}
void asyncTestOnDeliveryComplete(void* context, MQTTAsync_token token)
{
}
void asyncTestOnConnect(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int subsqos = 2;
int rc;
MyLog(LOGA_DEBUG, "In asyncTestOnConnect callback, %s", tc->clientid);
opts.onSuccess = asyncTestOnSubscribe;
opts.onFailure = asyncTestOnSubscribeFailure;
opts.context = tc;
rc = MQTTAsync_subscribe(tc->client, tc->topic, subsqos, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
/*********************************************************************
Test1: SSL connection to non SSL MQTT server
*********************************************************************/
int test1Finished = 0;
void test1OnFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In connect onFailure callback, context %p", context);
test1Finished = 1;
}
void test1OnConnect(void* context, MQTTAsync_successData* response)
{
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p\n", context);
assert("Connect should not succeed", 0, "connect success callback was called", 0);
test1Finished = 1;
failures++;
}
int test1(struct Options options)
{
char* testname = "test1";
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
char* test_topic = "C client SSL test1";
int count = 0;
test1Finished = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 1 - connection to nonSSL MQTT server");
if (!(assert ("Good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test1", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = test1OnConnect;
opts.onFailure = test1OnFailure;
opts.context = c;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
opts.ssl->enableServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
/* wait for success or failure callback */
while (!test1Finished && ++count < 10000)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2a: Mutual SSL Authentication - Certificates in place on client and server
*********************************************************************/
void test2aOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test2aOnConnectFailure callback, %s",
client->clientid);
assert("There should be no failures in this test. ", 0, "test2aOnConnectFailure callback was called\n", 0);
client->testFinished = 1;
failures++;
}
void test2aOnPublishFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test2aOnPublishFailure callback, %s",
client->clientid);
assert("There should be no failures in this test. ", 0, "test2aOnPublishFailure callback was called\n", 0);
client->testFinished = 1;
failures++;
}
int test2a(struct Options options)
{
char* testname = "test2a";
AsyncTestClient tc = AsyncTestClient_initializer;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int i, rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 2a - Mutual SSL authentication");
if (!(assert("Good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test2a", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
tc.client = c;
sprintf(tc.clientid, "%s", testname);
sprintf(tc.topic, "C client SSL test2a");
tc.maxmsgs = MAXMSGS;
//tc.rcvdmsgs = 0;
tc.subscribed = 0;
tc.testFinished = 0;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = asyncTestOnConnect;
opts.onFailure = test2aOnConnectFailure;
opts.context = &tc;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL)
opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL)
opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
if (!(assert("Good rc from setCallbacks", (rc = MQTTAsync_setCallbacks(c, &tc, NULL, asyncTestMessageArrived, asyncTestOnDeliveryComplete)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!tc.testFinished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MyLog(LOGA_DEBUG, "Stopping");
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2b: Mutual SSL Authentication - Server does not have Client cert
*********************************************************************/
int test2bFinished;
void test2bOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In test2bOnConnectFailure callback, context %p", context);
assert("This test should call test2bOnConnectFailure. ", 1, "test2bOnConnectFailure callback was called\n", 1);
test2bFinished = 1;
}
void test2bOnConnect(void* context, MQTTAsync_successData* response)
{
MyLog(LOGA_DEBUG, "In test2bOnConnectFailure callback, context %p", context);
assert("This connect should not succeed. ", 0, "test2bOnConnect callback was called\n", 0);
failures++;
test2bFinished = 1;
}
int test2b(struct Options options)
{
char* testname = "test2b";
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
int count = 0;
test2bFinished = 0;
failures = 0;
MyLog(
LOGA_INFO,
"Starting test 2b - connection to SSL MQTT server with clientauth=req but server does not have client cert");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test2b", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = test2bOnConnect;
opts.onFailure = test2bOnConnectFailure;
opts.context = c;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL)
opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL)
opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!test2bFinished && ++count < 10000)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test2c: Mutual SSL Authentication - Client does not have Server cert
*********************************************************************/
int test2cFinished;
void test2cOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In test2cOnConnectFailure callback, context %p", context);
assert("This test should call test2cOnConnectFailure. ", 1, "test2cOnConnectFailure callback was called\n", 0);
test2cFinished = 1;
}
void test2cOnConnect(void* context, MQTTAsync_successData* response)
{
MyLog(LOGA_DEBUG, "In test2cOnConnectFailure callback, context %p", context);
assert("This connect should not succeed. ", 0, "test2cOnConnect callback was called\n", 0);
failures++;
test2cFinished = 1;
}
int test2c(struct Options options)
{
char* testname = "test2c";
char* test_topic = "C client test2c";
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int rc, count = 0;
test2cFinished = 0;
failures = 0;
MyLog(
LOGA_INFO,
"Starting test 2c - connection to SSL MQTT server, server auth enabled but unknown cert");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test2c", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = test2cOnConnect;
opts.onFailure = test2cOnConnectFailure;
opts.context = c;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL)
opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!test2cFinished && ++count < 10000)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test3a: Server Authentication - server certificate in client trust store
*********************************************************************/
void test3aOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test3aOnConnectFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test3aOnConnectFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
int test3a(struct Options options)
{
char* testname = "test3a";
int subsqos = 2;
/* TODO - usused - remove ? MQTTAsync_deliveryToken* dt = NULL; */
AsyncTestClient tc =
AsyncTestClient_initializer;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int i, rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 3a - Server authentication");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test3a", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
tc.client = c;
sprintf(tc.clientid, "%s", testname);
sprintf(tc.topic, "C client SSL test3a");
tc.maxmsgs = MAXMSGS;
//tc.rcvdmsgs = 0;
tc.subscribed = 0;
tc.testFinished = 0;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = asyncTestOnConnect;
opts.onFailure = test3aOnConnectFailure;
opts.context = &tc;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL)
opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
if (!(assert("Good rc from setCallbacks", (rc = MQTTAsync_setCallbacks(c, &tc, NULL, asyncTestMessageArrived, asyncTestOnDeliveryComplete)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!tc.testFinished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MyLog(LOGA_DEBUG, "Stopping");
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.", (failures
== 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test3b: Server Authentication - Client does not have server cert
*********************************************************************/
int test3bFinished;
void test3bOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In test3bOnConnectFailure callback, context %p", context);
assert("This test should call test3bOnConnectFailure. ", 1, "test3bOnConnectFailure callback was called\n", 1);
test3bFinished = 1;
}
void test3bOnConnect(void* context, MQTTAsync_successData* response)
{
MyLog(LOGA_DEBUG, "In test3bOnConnectFailure callback, context %p", context);
assert("This connect should not succeed. ", 0, "test3bOnConnect callback was called\n", 0);
failures++;
test3bFinished = 1;
}
int test3b(struct Options options)
{
char* testname = "test3b";
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int count, rc = 0;
test3bFinished = 0;
failures = 0;
MyLog( LOGA_INFO, "Starting test 3b - connection to SSL MQTT server with clientauth=opt but client does not have server cert");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test3b", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = test3bOnConnect;
opts.onFailure = test3bOnConnectFailure;
opts.context = c;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!test3bFinished && ++count < 10000)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test4: Accept invalid server certificates
*********************************************************************/
void test4OnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test4OnConnectFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test4OnConnectFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
void test4OnPublishFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test4OnPublishFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test4OnPublishFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
int test4(struct Options options)
{
char* testname = "test4";
int subsqos = 2;
/* TODO - usused - remove ? MQTTAsync_deliveryToken* dt = NULL; */
AsyncTestClient tc = AsyncTestClient_initializer;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int i, rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 4 - accept invalid server certificates");
if (!(assert("Good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test4", MQTTCLIENT_PERSISTENCE_NONE, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
tc.client = c;
sprintf(tc.clientid, "%s", testname);
sprintf(tc.topic, "C client SSL test4");
tc.maxmsgs = MAXMSGS;
//tc.rcvdmsgs = 0;
tc.subscribed = 0;
tc.testFinished = 0;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = asyncTestOnConnect;
opts.onFailure = test4OnConnectFailure;
opts.context = &tc;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
opts.ssl->enableServerCertAuth = 0;
if (!(assert("Good rc from setCallbacks", (rc = MQTTAsync_setCallbacks(c, &tc, NULL, asyncTestMessageArrived, asyncTestOnDeliveryComplete)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!tc.testFinished)
{
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
}
MyLog(LOGA_DEBUG, "Stopping");
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test5a: Anonymous ciphers - server auth disabled
*********************************************************************/
void test5aOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test5aOnConnectFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test5aOnConnectFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
void test5aOnPublishFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test5aOnPublishFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test5aOnPublishFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
int test5a(struct Options options)
{
char* testname = "test5a";
AsyncTestClient tc = AsyncTestClient_initializer;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int i, rc = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 5a - Anonymous ciphers - server authentication disabled");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test5a", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
tc.client = c;
sprintf(tc.clientid, "%s", testname);
sprintf(tc.topic, "C client SSL test5a");
tc.maxmsgs = MAXMSGS;
//tc.rcvdmsgs = 0;
tc.subscribed = 0;
tc.testFinished = 0;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = asyncTestOnConnect;
opts.onFailure = test5aOnConnectFailure;
opts.context = &tc;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
opts.ssl->enabledCipherSuites = "aNULL";
opts.ssl->enableServerCertAuth = 0;
if (!(assert("Good rc from setCallbacks", (rc = MQTTAsync_setCallbacks(c, &tc, NULL, asyncTestMessageArrived, asyncTestOnDeliveryComplete)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!tc.testFinished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MyLog(LOGA_DEBUG, "Stopping");
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test5b: Anonymous ciphers - server auth enabled
/********************************************************************/
void test5bOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test5bOnConnectFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test5bOnConnectFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
void test5bOnPublishFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test5bOnPublishFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test5bOnPublishFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
int test5b(struct Options options)
{
char* testname = "test5b";
AsyncTestClient tc =
AsyncTestClient_initializer;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int i, rc = 0;
failures = 0;
MyLog(LOGA_INFO,
"Starting SSL test 5b - Anonymous ciphers - server authentication enabled");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test5b", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
tc.client = c;
sprintf(tc.clientid, "%s", testname);
sprintf(tc.topic, "C client SSL test5b");
tc.maxmsgs = MAXMSGS;
//tc.rcvdmsgs = 0;
tc.subscribed = 0;
tc.testFinished = 0;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = asyncTestOnConnect;
opts.onFailure = test5bOnConnectFailure;
opts.context = &tc;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
opts.ssl->enabledCipherSuites = "aNULL";
opts.ssl->enableServerCertAuth = 1;
rc = MQTTAsync_setCallbacks(c, &tc, NULL, asyncTestMessageArrived, asyncTestOnDeliveryComplete);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
{
failures++;
goto exit;
}
while (!tc.testFinished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MyLog(LOGA_DEBUG, "Stopping");
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test5c: Anonymous ciphers - client not using anonymous ciphers
*********************************************************************/
int test5cFinished;
void test5cOnConnectFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In test5cOnConnectFailure callback, context %p", context);
assert("This test should call test5cOnConnectFailure. ", 1, "test5cOnConnectFailure callback was called\n", 1);
test5cFinished = 1;
}
void test5cOnConnect(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test5cOnConnectFailure callback, context %p", context);
assert("This connect should not succeed. ", 0, "test5cOnConnect callback was called\n", 0);
failures++;
test5cFinished = 1;
}
int test5c(struct Options options)
{
char* testname = "test5c";
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
int count = 0;
test5cFinished = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting SSL test 5c - Anonymous ciphers - client not using anonymous cipher");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "test5c", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = test5cOnConnect;
opts.onFailure = test5cOnConnectFailure;
opts.context = c;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
//opts.ssl->trustStore = /*file of certificates trusted by client*/
//opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
opts.ssl->enableServerCertAuth = 0;
MyLog(LOGA_DEBUG, "Connecting");
assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
failures++;
goto exit;
}
while (!test5cFinished && ++count < 10000)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test6: More than one client object - simultaneous working.
*********************************************************************/
void test6OnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test6OnConnectFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test6OnConnectFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
void test6OnPublishFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test6OnPublishFailure callback, context %p", context);
assert("There should be no failures in this test. ", 0, "test6OnPublishFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
int test6(struct Options options)
{
#define NUM_CLIENTS 10
char* testname = "test6";
const int num_clients = NUM_CLIENTS;
int subsqos = 2;
AsyncTestClient tc[NUM_CLIENTS];
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
int i;
int test6finished = 0;
failures = 0;
MyLog(LOGA_INFO, "Starting test 6 - multiple connections");
for (i = 0; i < num_clients; ++i)
{
tc[i].maxmsgs = MAXMSGS;
tc[i].rcvdmsgs[0] = 0;
tc[i].rcvdmsgs[1] = 0;
tc[i].rcvdmsgs[2] = 0;
tc[i].sentmsgs[0] = 0;
tc[i].sentmsgs[1] = 0;
tc[i].sentmsgs[2] = 0;
tc[i].testFinished = 0;
sprintf(tc[i].clientid, "sslasync_test6_num_%d", i);
sprintf(tc[i].topic, "sslasync test6 topic num %d", i);
if (!(assert("good rc from create", (rc = MQTTAsync_create(&(tc[i].client), options.connection, tc[i].clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
if (!(assert("Good rc from setCallbacks", (rc = MQTTAsync_setCallbacks(tc[i].client, &tc[i], NULL, asyncTestMessageArrived, NULL)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = asyncTestOnConnect;
opts.onFailure = test6OnConnectFailure;
opts.context = &tc[i];
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL)
opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL)
opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
MyLog(LOGA_DEBUG, "Connecting");
assert("Good rc from connect", (rc = MQTTAsync_connect(tc[i].client, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
while (test6finished < num_clients)
{
MyLog(LOGA_DEBUG, "num_clients %d test_finished %d\n", num_clients,
test6finished);
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
for (i = 0; i < num_clients; ++i)
{
if (tc[i].testFinished)
{
test6finished++;
tc[i].testFinished = 0;
}
}
}
exit:
MyLog(LOGA_DEBUG, "test6: destroying clients");
for (i = 0; i < num_clients; ++i)
MQTTAsync_destroy(&tc[i].client);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
/*********************************************************************
Test7: Send and receive big messages
*********************************************************************/
void* test7_payload = NULL;
int test7_payloadlen = 0;
void test7OnConnectFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test7OnConnectFailure callback, %s", client->clientid);
assert("There should be no failures in this test. ", 0, "test7OnConnectFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
void test7OnPublishFailure(void* context, MQTTAsync_failureData* response)
{
AsyncTestClient* client = (AsyncTestClient*) context;
MyLog(LOGA_DEBUG, "In test7OnPublishFailure callback, %s", client->clientid);
assert("There should be no failures in this test. ", 0, "test7OnPublishFailure callback was called\n", 0);
failures++;
client->testFinished = 1;
}
int test7MessageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
static int message_count = 0;
int rc, i;
MyLog(LOGA_DEBUG, "In messageArrived callback %p", tc);
assert("Message size correct", message->payloadlen == test7_payloadlen,
"message size was %d", message->payloadlen);
for (i = 0; i < options.size; ++i)
{
if (((char*) test7_payload)[i] != ((char*) message->payload)[i])
{
assert("Message contents correct", ((char*)test7_payload)[i] != ((char*)message->payload)[i],
"message content was %c", ((char*)message->payload)[i]);
failures++;
break;
}
}
if (++message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = test7_payload;
pubmsg.payloadlen = test7_payloadlen;
pubmsg.qos = 1;
pubmsg.retained = 0;
opts.onSuccess = NULL;
opts.onFailure = test7OnPublishFailure;
opts.context = tc;
rc = MQTTAsync_sendMessage(tc->client, tc->topic, &pubmsg, &opts);
}
else if (message_count == 2)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = test7_payload;
pubmsg.payloadlen = test7_payloadlen;
pubmsg.qos = 0;
pubmsg.retained = 0;
opts.onSuccess = NULL;
opts.onFailure = test7OnPublishFailure;
opts.context = tc;
rc = MQTTAsync_sendMessage(tc->client, tc->topic, &pubmsg, &opts);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = asyncTestOnUnsubscribe;
opts.context = tc;
rc = MQTTAsync_unsubscribe(tc->client, tc->topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
message_count = 0;
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test7OnSubscribe(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc, i;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback %p", tc);
pubmsg.payload = test7_payload = malloc(options.size);
pubmsg.payloadlen = test7_payloadlen = options.size;
srand(33);
for (i = 0; i < options.size; ++i)
((char*) pubmsg.payload)[i] = rand() % 256;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(tc->client, tc->topic, pubmsg.payloadlen, pubmsg.payload,
pubmsg.qos, pubmsg.retained, NULL);
}
void test7OnConnect(void* context, MQTTAsync_successData* response)
{
AsyncTestClient* tc = (AsyncTestClient*) context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p", context);
opts.onSuccess = test7OnSubscribe;
opts.context = tc;
if (!(assert("Good rc from subscribe", (rc = MQTTAsync_subscribe(tc->client, tc->topic, 2, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
tc->testFinished = 1;
}
int test7(struct Options options)
{
char* testname = "test7";
int subsqos = 2;
AsyncTestClient tc =
AsyncTestClient_initializer;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
char* test_topic = "C client test7";
int test_finished;
failures = 0;
MyLog(LOGA_INFO, "Starting test 7 - big messages");
if (!(assert("good rc from create", (rc = MQTTAsync_create(&c, options.connection, "async_test_7", MQTTCLIENT_PERSISTENCE_NONE, NULL)) == MQTTASYNC_SUCCESS, "rc was %d\n", rc)))
goto exit;
if (!(assert("Good rc from setCallbacks", (rc = MQTTAsync_setCallbacks(c, &tc, NULL, test7MessageArrived, NULL)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
tc.client = c;
sprintf(tc.clientid, "%s", testname);
sprintf(tc.topic, "C client SSL test7");
tc.maxmsgs = MAXMSGS;
//tc.rcvdmsgs = 0;
tc.subscribed = 0;
tc.testFinished = 0;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.onSuccess = test7OnConnect;
opts.onFailure = test7OnConnectFailure;
opts.context = &tc;
if (options.haconnections != NULL)
{
opts.serverURIs = options.haconnections;
opts.serverURIcount = options.hacount;
}
opts.ssl = &sslopts;
if (options.server_key_file != NULL)
opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
opts.ssl->keyStore = options.client_key_file; /*file of certificate for client to present to server*/
if (options.client_key_pass != NULL)
opts.ssl->privateKeyPassword = options.client_key_pass;
//opts.ssl->enabledCipherSuites = "DEFAULT";
//opts.ssl->enabledServerCertAuth = 1;
MyLog(LOGA_DEBUG, "Connecting");
if (!(assert("Good rc from connect", (rc = MQTTAsync_connect(c, &opts)) == MQTTASYNC_SUCCESS, "rc was %d", rc)))
goto exit;
while (!tc.testFinished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&c);
MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", testname, tests, failures);
return failures;
}
void handleTrace(enum MQTTASYNC_TRACE_LEVELS level, char* message)
{
//printf("Trace: %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
int* numtests = &tests;
int rc = 0;
int i;
int (*tests[])() =
{ NULL, test1, test2a, test2b, test2c, test3a, test3b, test4, test5a,
test5b, test5c, test6, test7 };
char** versionInfo = MQTTAsync_getVersionInfo();
for (i = 0; versionInfo[i] != NULL; i++)
{
printf("%s\n", versionInfo[i]);
}
MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_PROTOCOL);
MQTTAsync_setTraceCallback(handleTrace);
getopts(argc, argv);
if (options.test_no == 0)
{ /* run all the tests */
for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
rc += tests[options.test_no](options); /* return number of failures. 0 = test succeeded */
}
else
rc = tests[options.test_no](options); /* run just the selected test */
MyLog(LOGA_INFO, "Total tests run: %d", *numtests);
if (rc == 0)
MyLog(LOGA_INFO, "verdict pass");
else
MyLog(LOGA_INFO, "verdict fail");
return rc;
}
#define MY_ID "@(#) stmqcom/pub1.c, stmqcom, cs 1.85 10/08/24 07:36:24"
/*--------------------------------------------------------------------*/
/* [Platforms]UNIX NT[/Platforms] */
/* [Title]MQTT restart/recovery application for Async C client */
/* [/Title] */
/* [Testclasses]stcom1 stmqcom1[/Category] */
/* [Category]MQDrivers[/Category] */
/* */
/* Copyright IBM 2011, 2013 */
/* All rights reserved. */
/*--------------------------------------------------------------------*/
/**
* @file
* Async C client program for the MQTT v3 restart/recovery test suite.
*/
/*
#if !defined(_RTSHEADER)
#include <rts.h>
#endif
*/
#include "MQTTAsync.h"
#include <string.h>
#include <stdlib.h>
#if !defined(_WINDOWS)
#include <sys/time.h>
#include <unistd.h>
#include <signal.h>
#else
#include <winsock2.h>
#endif
void usage()
{
printf("help!!\n");
exit(-1);
}
static char pub_topic[200];
static char sub_topic[200];
struct
{
char* connection; /**< connection to system under test. */
char** connections; /**< HA connection list */
int connection_count;
char* control_connection; /**< MQTT control connection, for test sync */
char* topic;
char* control_topic;
char* clientid;
int slot_no;
int qos;
int retained;
char* username;
char* password;
int verbose;
int persistence;
} opts =
{
"tcp://localhost:1885",
NULL,
0,
"tcp://localhost:7777",
"XR9TT3",
"XR9TT3/control",
"C_broken_client",
1,
2,
0,
NULL,
NULL,
0,
0,
};
void getopts(int argc, char** argv)
{
int count = 1;
while (count < argc)
{
if (strcmp(argv[count], "--qos") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "0") == 0)
opts.qos = 0;
else if (strcmp(argv[count], "1") == 0)
opts.qos = 1;
else if (strcmp(argv[count], "2") == 0)
opts.qos = 2;
else
usage();
}
else
usage();
}
else if (strcmp(argv[count], "--slot_no") == 0)
{
if (++count < argc)
opts.slot_no = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--connection") == 0)
{
if (++count < argc)
opts.connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--connections") == 0)
{
if (++count < argc)
{
opts.connection_count = 0;
opts.connections = malloc(sizeof(char*) * 5);
char* tok = strtok(argv[count], " ");
while (tok)
{
opts.connections[opts.connection_count] = malloc(strlen(tok)+1);
strcpy(opts.connections[opts.connection_count], tok);
opts.connection_count++;
tok = strtok(NULL, " ");
}
}
else
usage();
}
else if (strcmp(argv[count], "--control_connection") == 0)
{
if (++count < argc)
opts.control_connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--clientid") == 0)
{
if (++count < argc)
opts.clientid = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--username") == 0)
{
if (++count < argc)
opts.username = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--password") == 0)
{
if (++count < argc)
opts.password = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--persistent") == 0)
opts.persistence = 1;
else if (strcmp(argv[count], "--verbose") == 0)
opts.verbose = 1;
count++;
}
}
#if 0
#include <logaX.h> /* For general log messages */
#define MyLog logaLine
#else
#define LOGA_DEBUG 0
#define LOGA_ALWAYS 1
#define LOGA_INFO 2
#include <stdarg.h>
#include <time.h>
#include <sys/timeb.h>
void MyLog(int log_level, char* format, ...)
{
static char msg_buf[256];
va_list args;
struct timeb ts;
struct tm *timeinfo;
if (log_level == LOGA_DEBUG && opts.verbose == 0)
return;
ftime(&ts);
timeinfo = localtime(&ts.time);
strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
sprintf(&msg_buf[strlen(msg_buf)], "%s ", opts.clientid);
va_start(args, format);
vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf), format, args);
va_end(args);
printf("%s\n", msg_buf);
fflush(stdout);
}
#endif
#if defined(WIN32) || defined(_WINDOWS)
#define mqsleep(A) Sleep(1000*A)
#define START_TIME_TYPE DWORD
static DWORD start_time = 0;
START_TIME_TYPE start_clock(void)
{
return GetTickCount();
}
#elif defined(AIX)
#define mqsleep sleep
#define START_TIME_TYPE struct timespec
START_TIME_TYPE start_clock(void)
{
static struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
return start;
}
#else
#define mqsleep sleep
#define START_TIME_TYPE struct timeval
static struct timeval start_time;
START_TIME_TYPE start_clock(void)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
return start_time;
}
#endif
#if defined(WIN32)
long elapsed(START_TIME_TYPE start_time)
{
return GetTickCount() - start_time;
}
#elif defined(AIX)
#define assert(a)
long elapsed(struct timespec start)
{
struct timespec now, res;
clock_gettime(CLOCK_REALTIME, &now);
ntimersub(now, start, res);
return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
}
#else
long elapsed(START_TIME_TYPE start_time)
{
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&now, &start_time, &res);
return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}
#endif
MQTTAsync control_client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync client;
int arrivedCount = 0;
int expectedCount = 0;
int measuring = 0;
long roundtrip_time = 0L;
int errors = 0;
int stopping = 0;
int connection_lost = 0; /* for use with the persistence option */
int recreated = 0;
int client_cleaned = 0;
char* wait_message = NULL;
char* wait_message2 = NULL;
int control_found = 0;
long last_completion_time = -1;
int test_count = 1000;
void control_connectionLost(void* context, char* cause)
{
MyLog(LOGA_ALWAYS, "Control connection lost - stopping");
stopping = 1;
}
/**-----------------------------------------------------------------------------
* Callback which receives messages from the control connection
* @param context
* @param topicName the name of the topic on which the message is received
* @param topicLen the length of the topic name (in case of embedded nulls)
* @param m pointer to the message received
* @return boolean
*/
int control_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
{
MyLog(LOGA_DEBUG, "Control message arrived: %.*s %s",
m->payloadlen, m->payload, wait_message);
if (strcmp(m->payload, "stop") == 0)
stopping = 1;
else if (wait_message != NULL && strncmp(wait_message, m->payload,
strlen(wait_message)) == 0)
{
control_found = 1;
wait_message = NULL;
}
else if (wait_message2 != NULL && strncmp(wait_message2, m->payload,
strlen(wait_message2)) == 0)
{
control_found = 2;
wait_message2 = NULL;
}
MQTTAsync_free(topicName);
MQTTAsync_freeMessage(&m);
return 1;
}
/* wait for a specific message on the control topic. */
int control_wait(char* message)
{
int count = 0;
char buf[120];
control_found = 0;
wait_message = message;
sprintf(buf, "waiting for: %s", message);
control_send(buf);
while (control_found == 0 && stopping == 0)
{
if (++count == 300)
{
stopping = 1;
MyLog(LOGA_ALWAYS, "Failed to receive message %s, stopping ", message);
return 0; /* time out and tell the caller the message was not found */
}
mqsleep(1);
}
return control_found;
}
/* wait for a specific message on the control topic. */
int control_which(char* message1, char* message2)
{
int count = 0;
control_found = 0;
wait_message = message1;
wait_message2 = message2;
while (control_found == 0)
{
if (++count == 300)
return 0; /* time out and tell the caller the message was not found */
mqsleep(1);
}
return control_found;
}
int control_send(char* message)
{
char buf[156];
int rc = 0;
MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
sprintf(buf, "%s: %s", opts.clientid, message);
rc = MQTTAsync_send(control_client, pub_topic, strlen(buf),
buf, 1, 0, &ropts);
MyLog(LOGA_DEBUG, "Control message sent: %s", buf);
return rc;
}
START_TIME_TYPE global_start_time;
int messageArrived(void* context, char* topicName, int topicLen,
MQTTAsync_message* m)
{
int seqno = -1;
char* token = NULL;
token = strtok(m->payload, " ");
token = strtok(NULL, " ");
token = strtok(NULL, " ");
if (token)
seqno = atoi(token);
if (m->qos != opts.qos)
{
MyLog(LOGA_ALWAYS, "Error, expecting QoS %d but got %d", opts.qos,
m->qos);
errors++;
} else if (seqno != arrivedCount + 1)
{
if (m->qos == 2 || (m->qos == 1 && seqno > arrivedCount + 1))
{
if (seqno == -1)
MyLog(LOGA_ALWAYS,
"Error, expecting sequence number %d but got message id %d, payload was %.*s",
arrivedCount + 1, m->msgid, m->payloadlen, m->payload);
else
MyLog(LOGA_ALWAYS,
"Error, expecting sequence number %d but got %d message id %d",
arrivedCount + 1, seqno, m->msgid);
errors++;
}
}
arrivedCount++;
MQTTAsync_free(topicName);
MQTTAsync_freeMessage(&m);
if (measuring && arrivedCount == test_count)
roundtrip_time = elapsed(global_start_time);
return 1;
}
void client_onReconnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_ALWAYS, "Successfully reconnected");
}
void client_onReconnectFailure(void* context, MQTTAsync_failureData* response)
{
MQTTAsync c = (MQTTAsync)context;
int rc;
MyLog(LOGA_ALWAYS, "Failed to reconnect with return code %d", (response) ? response->code : -9999);
conn_opts.context = context;
conn_opts.keepAliveInterval = 10;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.cleansession = 0;
conn_opts.onSuccess = client_onReconnect;
conn_opts.onFailure = client_onReconnectFailure;
rc = MQTTAsync_connect(c, &conn_opts);
if (rc != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "Failed to start reconnect with return code %d", rc);
stopping = 1;
}
}
void connectionLost(void* context, char* cause)
{
MQTTAsync c = (MQTTAsync)context;
int rc = 0;
MyLog(LOGA_ALWAYS, "Connection lost when %d messages arrived out of %d expected",
arrivedCount, expectedCount);
//dotrace = 1;
if (opts.persistence)
connection_lost = 1;
else
{
conn_opts.context = context;
conn_opts.keepAliveInterval = 10;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.cleansession = 0;
conn_opts.onSuccess = client_onReconnect;
conn_opts.onFailure = client_onReconnectFailure;
if (opts.connections)
{
conn_opts.serverURIcount = opts.connection_count;
conn_opts.serverURIs = opts.connections;
}
else
{
conn_opts.serverURIcount = 0;
conn_opts.serverURIs = NULL;
}
printf("reconnecting to first serverURI %s\n", conn_opts.serverURIs[0]);
rc = MQTTAsync_connect(context, &conn_opts);
if (rc != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "Failed to start reconnect with return code %d", rc);
stopping = 1;
}
}
}
int recreateReconnect()
{
int rc;
if (recreated == 0)
{
MyLog(LOGA_ALWAYS, "Recreating client");
MQTTAsync_destroy(&client); /* destroy the client object so that we force persistence to be read on recreate */
rc = MQTTAsync_create(&client, opts.connection, opts.clientid, MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
if (rc != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "MQTTAsync_create failed, rc %d", rc);
goto exit;
}
if ((rc = MQTTAsync_setCallbacks(client, client, connectionLost,
messageArrived, NULL)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "MQTTAsync_setCallbacks failed, rc %d", rc);
goto exit;
}
recreated = 1;
}
MyLog(LOGA_ALWAYS, "Reconnecting client");
conn_opts.keepAliveInterval = 10;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.cleansession = 0;
conn_opts.context = client;
conn_opts.onSuccess = client_onReconnect;
conn_opts.onFailure = client_onReconnectFailure;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
MyLog(LOGA_ALWAYS, "MQTTAsync_connect failed, rc %d", rc);
else
connection_lost = 0;
exit:
return rc;
}
int success(int count)
{
int rc = 1;
if (errors)
{
MyLog(LOGA_ALWAYS, "Workload test failed because the callback had errors");
rc = 0;
}
if (arrivedCount != count)
{
if (opts.qos == 2 || (opts.qos == 1 && arrivedCount < count))
{
MyLog(LOGA_ALWAYS,
"Workload test failed because the wrong number of messages"
" was received: %d whereas %d were expected",
arrivedCount, count);
rc = 0;
}
}
if (rc == 1)
control_send("verdict: pass");
else
control_send("verdict: fail");
return rc;
}
int waitForCompletion(START_TIME_TYPE start_time)
{
int lastreport = 0;
int wait_count = 0;
int limit = 120;
mqsleep(1);
while (arrivedCount < expectedCount)
{
if (arrivedCount > lastreport)
{
MyLog(LOGA_ALWAYS, "%d messages arrived out of %d expected, in %d seconds",
arrivedCount, expectedCount, elapsed(start_time) / 1000);
lastreport = arrivedCount;
}
mqsleep(1);
if (opts.persistence && connection_lost)
recreateReconnect();
if (++wait_count > limit || stopping)
break;
}
last_completion_time = elapsed(start_time) / 1000;
MyLog(LOGA_ALWAYS, "Extra wait to see if any duplicates arrive");
mqsleep(10); /* check if any duplicate messages arrive */
MyLog(LOGA_ALWAYS, "%d messages arrived out of %d expected, in %d seconds",
arrivedCount, expectedCount, elapsed(start_time) / 1000);
return success(expectedCount);
}
int messagesSent = 0;
void messageSent(void* context, MQTTAsync_successData* response)
{
messagesSent++;
}
void one_iteration()
{
int interval = 0;
int i = 0;
int seqno = 0;
int rc = 0;
START_TIME_TYPE start_time;
int last_expected_count = expectedCount;
int test_interval = 30;
if (control_wait("start_measuring") == 0)
goto exit;
connection_lost = 0;
recreated = 0;
/* find the time for evaluation_count round-trip messages */
MyLog(LOGA_INFO, "Evaluating how many messages needed");
expectedCount = arrivedCount = 0;
measuring = 1;
global_start_time = start_clock();
for (i = 1; i <= test_count; ++i)
{
char payload[128];
sprintf(payload, "message number %d", i);
rc = MQTTAsync_send(client, opts.topic, strlen(payload)+1, payload,
opts.qos, opts.retained, NULL);
while (rc != MQTTASYNC_SUCCESS)
{
if (opts.persistence && (connection_lost || rc == MQTTASYNC_DISCONNECTED))
recreateReconnect();
if (stopping)
goto exit;
mqsleep(1);
rc = MQTTAsync_send(client, opts.topic, strlen(payload)+1, payload,
opts.qos, opts.retained, NULL);
}
}
MyLog(LOGA_INFO, "Messages sent... waiting for echoes");
while (arrivedCount < test_count)
{
if (stopping)
goto exit;
mqsleep(1);
printf("arrivedCount %d\n", arrivedCount);
}
measuring = 0;
/* Now set a target of 30 seconds total round trip */
if (last_completion_time == -1)
{
MyLog(LOGA_ALWAYS, "Round trip time for %d messages is %d ms", test_count, roundtrip_time);
expectedCount = 1000 * test_count * test_interval / roundtrip_time / 2;
}
else
{
MyLog(LOGA_ALWAYS, "Last time, %d messages took %d s.", last_expected_count, last_completion_time);
expectedCount = last_expected_count * test_interval / last_completion_time;
}
MyLog(LOGA_ALWAYS, "Therefore %d messages needed for 30 seconds", expectedCount);
if (control_wait("start_test") == 0) /* now synchronize the test interval */
goto exit;
MyLog(LOGA_ALWAYS, "Starting 30 second test run with %d messages", expectedCount);
arrivedCount = 0;
messagesSent = 0;
start_time = start_clock();
while (seqno < expectedCount)
{
MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
char payload[128];
ropts.onSuccess = messageSent;
seqno++;
sprintf(payload, "message number %d", seqno);
rc = MQTTAsync_send(client, opts.topic, strlen(payload)+1, payload,
opts.qos, opts.retained, &ropts);
while (rc != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_DEBUG, "Rc %d from publish with payload %s, retrying", rc, payload);
if (opts.persistence && (connection_lost || rc == MQTTASYNC_DISCONNECTED))
recreateReconnect();
if (stopping)
goto exit;
mqsleep(1);
rc = MQTTAsync_send(client, opts.topic, strlen(payload)+1, payload,
opts.qos, opts.retained, &ropts);
}
//MyLog(LOGA_DEBUG, "Successful publish with payload %s", payload);
while (seqno - messagesSent > 2000)
mqsleep(1);
}
MyLog(LOGA_ALWAYS, "%d messages sent in %d seconds", expectedCount, elapsed(start_time) / 1000);
waitForCompletion(start_time);
control_wait("test finished");
exit:
; /* dummy statement for target of exit */
}
static int client_subscribed = 0;
void client_onSubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In client subscribe onSuccess callback %p granted qos %d", c, response->alt.qos);
client_subscribed = 1;
}
void client_onFailure(void* context, MQTTAsync_failureData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In failure callback");
client_subscribed = -1;
}
void client_onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
int rc;
sprintf(sub_topic, "%s/send", opts.control_topic);
sprintf(pub_topic, "%s/receive", opts.control_topic);
ropts.context = context;
ropts.onSuccess = client_onSubscribe;
ropts.onFailure = client_onFailure;
ropts.context = c;
if ((rc = MQTTAsync_subscribe(c, opts.topic, opts.qos, &ropts)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "client MQTTAsync_subscribe failed, rc %d", rc);
client_subscribed = -1;
}
}
void client_onCleanedDisconnected(void* context, MQTTAsync_successData* response)
{
client_cleaned = 1;
}
void client_onCleaned(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_disconnectOptions dopts = MQTTAsync_disconnectOptions_initializer;
int rc;
dopts.context = context;
dopts.onSuccess = client_onCleanedDisconnected;
dopts.onFailure = client_onFailure;
dopts.context = c;
if ((rc = MQTTAsync_disconnect(c, &dopts)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "client MQTTAsync_disconnect failed, rc %d", rc);
stopping = 1;
}
}
int sendAndReceive(void)
{
int rc = 0;
int persistence = MQTTCLIENT_PERSISTENCE_NONE;
MyLog(LOGA_ALWAYS, "v3 async C client topic workload using QoS %d", opts.qos);
MyLog(LOGA_DEBUG, "Connecting to %s", opts.connection);
if (opts.persistence)
persistence = MQTTCLIENT_PERSISTENCE_DEFAULT;
rc = MQTTAsync_create(&client, opts.connection, opts.clientid, persistence, NULL);
if (rc != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "MQTTAsync_create failed, rc %d", rc);
rc = 99;
goto exit;
}
if ((rc = MQTTAsync_setCallbacks(client, client, connectionLost,
messageArrived, NULL)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "MQTTAsync_setCallbacks failed, rc %d", rc);
rc = 99;
goto destroy_exit;
}
/* wait to know that the controlling process is running before connecting to the SUT */
control_wait("who is ready?");
/* connect cleansession, and then disconnect, to clean up */
conn_opts.keepAliveInterval = 10;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.cleansession = 1;
conn_opts.context = client;
conn_opts.onSuccess = client_onCleaned;
conn_opts.onFailure = client_onFailure;
if (opts.connections)
{
conn_opts.serverURIcount = opts.connection_count;
conn_opts.serverURIs = opts.connections;
}
else
{
conn_opts.serverURIcount = 0;
conn_opts.serverURIs = NULL;
}
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "MQTTAsync_connect failed, rc %d", rc);
rc = 99;
goto destroy_exit;
}
while (client_cleaned == 0)
mqsleep(1);
MyLog(LOGA_ALWAYS, "Client state cleaned up");
conn_opts.cleansession = 0;
conn_opts.context = client;
conn_opts.onSuccess = client_onConnect;
conn_opts.onFailure = client_onFailure;
conn_opts.retryInterval = 1;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "MQTTAsync_connect failed, rc %d", rc);
rc = 99;
goto destroy_exit;
}
/* wait until subscribed */
while (client_subscribed == 0)
mqsleep(1);
if (client_subscribed != 1)
goto disconnect_exit;
while (1)
{
control_send("Ready");
if (control_which("who is ready?", "continue") == 2)
break;
control_send("Ready");
}
while (!stopping)
{
one_iteration(client);
}
disconnect_exit:
MQTTAsync_disconnect(client, 0);
destroy_exit:
MQTTAsync_destroy(&client);
exit:
return rc;
}
static int control_subscribed = 0;
void control_onSubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In control subscribe onSuccess callback %p granted qos %d", c, response->alt.qos);
control_subscribed = 1;
}
void control_onFailure(void* context, MQTTAsync_failureData* response)
{
MQTTAsync c = (MQTTAsync)context;
control_subscribed = -1;
}
void control_onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
int rc;
sprintf(sub_topic, "%s/send", opts.control_topic);
sprintf(pub_topic, "%s/receive", opts.control_topic);
ropts.onSuccess = control_onSubscribe;
ropts.onFailure = control_onFailure;
ropts.context = c;
if ((rc = MQTTAsync_subscribe(c, sub_topic, 2, &ropts)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "control MQTTAsync_subscribe failed, rc %d", rc);
control_subscribed = -1;
}
}
void trace_callback(enum MQTTASYNC_TRACE_LEVELS level, char* message)
{
if (level == MQTTASYNC_TRACE_ERROR || strstr(message, "Connect") || strstr(message, "failed"))
printf("Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
MQTTAsync_connectOptions control_conn_opts = MQTTAsync_connectOptions_initializer;
int rc = 0;
static char topic_buf[200];
static char clientid[40];
#if !defined(WIN32)
signal(SIGPIPE, SIG_IGN);
#endif
MQTTAsync_nameValue* info = MQTTAsync_getVersionInfo();
while (info->name)
{
MyLog(LOGA_ALWAYS, "%s: %s\n", info->name, info->value);
info++;
}
getopts(argc, argv);
sprintf(topic_buf, "%s_%d", opts.topic, opts.slot_no);
opts.topic = topic_buf;
sprintf(clientid, "%s_%d", opts.clientid, opts.slot_no);
opts.clientid = clientid;
MyLog(LOGA_ALWAYS, "Starting with clientid %s", opts.clientid);
//MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_MAXIMUM);
MQTTAsync_setTraceCallback(trace_callback);
rc = MQTTAsync_create(&control_client, opts.control_connection,
opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (rc != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "control MQTTAsync_create failed, rc %d", rc);
rc = 99;
goto exit;
}
if ((rc = MQTTAsync_setCallbacks(control_client, control_client, control_connectionLost,
control_messageArrived, NULL)) != MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "control MQTTAsync_setCallbacks failed, rc %d", rc);
rc = 99;
goto destroy_exit;
}
control_subscribed = 0;
control_conn_opts.context = control_client;
control_conn_opts.keepAliveInterval = 10;
control_conn_opts.onSuccess = control_onConnect;
control_conn_opts.onFailure = control_onFailure;
if ((rc = MQTTAsync_connect(control_client, &control_conn_opts))
!= MQTTASYNC_SUCCESS)
{
MyLog(LOGA_ALWAYS, "control MQTTAsync_connect failed, rc %d", rc);
rc = 99;
goto destroy_exit;
}
while (control_subscribed == 0)
mqsleep(1);
if (control_subscribed != 1)
goto destroy_exit;
sendAndReceive();
exit:
MQTTAsync_disconnect(control_client, 0);
destroy_exit:
MQTTAsync_destroy(&control_client);
return 0;
}
/*--------------------------------------------------------------------*/
/* [Platforms]UNIX NT[/Platforms] */
/* [Title]MQ Telemetry MQTT Async C client tests - HA and connect */
/* failures */
/* [/Title] */
/* [Testclasses]stcom1 stmqcom1[/Category] */
/* [Category]MQ Telemetry[/Category] */
/* */
/* Copyright IBM 2013 */
/* All rights reserved. */
/*--------------------------------------------------------------------*/
/**
* @file
* Tests for the MQ Telemetry MQTT Async C client
*/
/*
#if !defined(_RTSHEADER)
#include <rts.h>
#endif
*/
#include "MQTTAsync.h"
#include <string.h>
#include <stdlib.h>
#if !defined(_WINDOWS)
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAXHOSTNAMELEN 256
#define EAGAIN WSAEWOULDBLOCK
#define EINTR WSAEINTR
#define EINPROGRESS WSAEINPROGRESS
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOTCONN WSAENOTCONN
#define ECONNRESET WSAECONNRESET
#endif
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
void usage()
{
printf("help!!\n");
exit(-1);
}
struct Options
{
char* connection; /**< connection to system under test. */
int verbose;
int test_no;
int size; /**< size of big message */
} options =
{
"tcp://localhost:1883",
0,
-1,
5000000,
};
void getopts(int argc, char** argv)
{
int count = 1;
while (count < argc)
{
if (strcmp(argv[count], "--test_no") == 0)
{
if (++count < argc)
options.test_no = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--size") == 0)
{
if (++count < argc)
options.size = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--connection") == 0)
{
if (++count < argc)
options.connection = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--verbose") == 0)
options.verbose = 1;
count++;
}
}
#if 0
#include <logaX.h> /* For general log messages */
#define MyLog logaLine
#else
#define LOGA_DEBUG 0
#define LOGA_INFO 1
#include <stdarg.h>
#include <time.h>
#include <sys/timeb.h>
void MyLog(int LOGA_level, char* format, ...)
{
static char msg_buf[256];
va_list args;
struct timeb ts;
struct tm *timeinfo;
if (LOGA_level == LOGA_DEBUG && options.verbose == 0)
return;
ftime(&ts);
timeinfo = localtime(&ts.time);
strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
va_start(args, format);
vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf), format, args);
va_end(args);
printf("%s\n", msg_buf);
fflush(stdout);
}
#endif
#if defined(WIN32) || defined(_WINDOWS)
#define mqsleep(A) Sleep(1000*A)
#define START_TIME_TYPE DWORD
static DWORD start_time = 0;
START_TIME_TYPE start_clock(void)
{
return GetTickCount();
}
#elif defined(AIX)
#define mqsleep sleep
#define START_TIME_TYPE struct timespec
START_TIME_TYPE start_clock(void)
{
static struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
return start;
}
#else
#define mqsleep sleep
#define START_TIME_TYPE struct timeval
/* TODO - unused - remove? static struct timeval start_time; */
START_TIME_TYPE start_clock(void)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
return start_time;
}
#endif
#if defined(WIN32)
long elapsed(START_TIME_TYPE start_time)
{
return GetTickCount() - start_time;
}
#elif defined(AIX)
#define assert(a)
long elapsed(struct timespec start)
{
struct timespec now, res;
clock_gettime(CLOCK_REALTIME, &now);
ntimersub(now, start, res);
return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
}
#else
long elapsed(START_TIME_TYPE start_time)
{
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&now, &start_time, &res);
return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}
#endif
START_TIME_TYPE global_start_time;
#define assert(a, b, c, d) myassert(__FILE__, __LINE__, a, b, c, d)
#define assert1(a, b, c, d, e) myassert(__FILE__, __LINE__, a, b, c, d, e)
int tests = 0;
int failures = 0;
void myassert(char* filename, int lineno, char* description, int value, char* format, ...)
{
++tests;
if (!value)
{
va_list args;
++failures;
printf("Assertion failed, file %s, line %d, description: %s\n", filename, lineno, description);
va_start(args, format);
vprintf(format, args);
va_end(args);
}
else
MyLog(LOGA_DEBUG, "Assertion succeeded, file %s, line %d, description: %s", filename, lineno, description);
}
volatile int test_finished = 0;
char* test_topic = "async test topic";
void test1_onDisconnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In onDisconnect callback %p", c);
test_finished = 1;
}
void test1_onUnsubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In onUnsubscribe onSuccess callback %p", c);
opts.onSuccess = test1_onDisconnect;
opts.context = c;
rc = MQTTAsync_disconnect(c, &opts);
assert("Disconnect successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
int test1_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
MQTTAsync c = (MQTTAsync)context;
static int message_count = 0;
int rc;
MyLog(LOGA_DEBUG, "In messageArrived callback %p", c);
if (++message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = test1_onUnsubscribe;
opts.context = c;
rc = MQTTAsync_unsubscribe(c, test_topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test1_onSubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback %p granted qos %d", c, response->alt.qos);
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
}
void test1_onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p", context);
opts.onSuccess = test1_onSubscribe;
opts.context = c;
rc = MQTTAsync_subscribe(c, test_topic, 2, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
test_finished = 1;
}
void test1_onConnectFailure(void* context, MQTTAsync_failureData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onFailure callback, context %p", context);
test_finished = 1;
}
/*********************************************************************
Test1: Basic connect, subscribe send and receive.
*********************************************************************/
int test1(struct Options options)
{
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test1";
char* serverURIs[2] = {"tcp://localhost:1882", options.connection};
failures = 0;
MyLog(LOGA_INFO, "Starting test 1 - asynchronous connect");
rc = MQTTAsync_create(&c, options.connection, "async_test",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
MQTTAsync_destroy(&c);
goto exit;
}
rc = MQTTAsync_setCallbacks(c, c, NULL, test1_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
opts.onSuccess = test1_onConnect;
opts.onFailure = test1_onConnectFailure;
opts.context = c;
opts.serverURIcount = 2;
opts.serverURIs = serverURIs;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
rc = 0;
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
goto exit;
while (!test_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&c);
exit:
MyLog(LOGA_INFO, "TEST1: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
int test2_onFailure_called = 0;
void test2_onFailure(void* context, MQTTAsync_failureData* response)
{
MyLog(LOGA_DEBUG, "In connect onFailure callback, context %p", context);
test2_onFailure_called++;
test_finished = 1;
}
void test2_onConnect(void* context, MQTTAsync_successData* response)
{
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p\n", context);
assert("Connect should not succeed", 0, "connect success callback was called", 0);
test_finished = 1;
}
/*********************************************************************
Test2: connect timeout
*********************************************************************/
int test2(struct Options options)
{
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test2";
test_finished = 0;
MyLog(LOGA_INFO, "Starting test 2 - connect timeout");
rc = MQTTAsync_create(&c, "tcp://9.20.96.160:66", "connect timeout",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
MQTTAsync_destroy(&c);
goto exit;
}
rc = MQTTAsync_setCallbacks(c, c, NULL, test1_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.connectTimeout = 5;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
opts.onSuccess = test2_onConnect;
opts.onFailure = test2_onFailure;
opts.context = c;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
rc = 0;
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
goto exit;
while (!test_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&c);
exit:
assert("Connect onFailure should be called once", test2_onFailure_called == 1,
"connect onFailure was called %d times", test2_onFailure_called);
MyLog(LOGA_INFO, "TEST2: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
typedef struct
{
MQTTAsync c;
int index;
char clientid[24];
char test_topic[100];
int message_count;
} client_data;
void test3_onDisconnect(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MyLog(LOGA_DEBUG, "In onDisconnect callback for client \"%s\"", cd->clientid);
test_finished++;
}
void test3_onPublish(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MyLog(LOGA_DEBUG, "In QoS 0 onPublish callback for client \"%s\"", cd->clientid);
}
void test3_onUnsubscribe(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In onUnsubscribe onSuccess callback \"%s\"", cd->clientid);
opts.onSuccess = test3_onDisconnect;
opts.context = cd;
rc = MQTTAsync_disconnect(cd->c, &opts);
assert("Disconnect successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
int test3_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
client_data* cd = (client_data*)context;
int rc;
MyLog(LOGA_DEBUG, "In messageArrived callback \"%s\" message count ", cd->clientid);
if (++cd->message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 25;
pubmsg.qos = 1;
pubmsg.retained = 0;
rc = MQTTAsync_sendMessage(cd->c, cd->test_topic, &pubmsg, &opts);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
else if (cd->message_count == 2)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = "a QoS 0 message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 29;
pubmsg.qos = 0;
pubmsg.retained = 0;
opts.context = cd;
opts.onSuccess = test3_onPublish;
rc = MQTTAsync_sendMessage(cd->c, cd->test_topic, &pubmsg, &opts);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = test3_onUnsubscribe;
opts.context = cd;
rc = MQTTAsync_unsubscribe(cd->c, cd->test_topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test3_onSubscribe(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback \"%s\"", cd->clientid);
pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11";
pubmsg.payloadlen = 11;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(cd->c, cd->test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
assert("Good rc from publish", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
void test3_onConnect(void* context, MQTTAsync_successData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, \"%s\"", cd->clientid);
opts.onSuccess = test3_onSubscribe;
opts.context = cd;
rc = MQTTAsync_subscribe(cd->c, cd->test_topic, 2, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
test_finished++;
}
void test3_onFailure(void* context, MQTTAsync_failureData* response)
{
client_data* cd = (client_data*)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
assert("Should have connected", 0, "failed to connect", NULL);
MyLog(LOGA_DEBUG, "In connect onFailure callback, \"%s\" rc %d\n", cd->clientid, response->code);
if (response->message)
MyLog(LOGA_DEBUG, "In connect onFailure callback, \"%s\"\n", response->message);
test_finished++;
}
/*********************************************************************
Test3: More than one client object - simultaneous working.
*********************************************************************/
int test3(struct Options options)
{
#define TEST3_CLIENTS 10
int num_clients = TEST3_CLIENTS;
int subsqos = 2;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
int i;
client_data clientdata[TEST3_CLIENTS];
test_finished = 0;
MyLog(LOGA_INFO, "Starting test 3 - multiple connections");
for (i = 0; i < num_clients; ++i)
{
sprintf(clientdata[i].clientid, "async_test3_num_%d", i);
sprintf(clientdata[i].test_topic, "async test3 topic num %d", i);
clientdata[i].index = i;
clientdata[i].message_count = 0;
rc = MQTTAsync_create(&(clientdata[i].c), options.connection, clientdata[i].clientid,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
rc = MQTTAsync_setCallbacks(clientdata[i].c, &clientdata[i], NULL, test3_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.onSuccess = test3_onConnect;
opts.onFailure = test3_onFailure;
opts.context = &clientdata[i];
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(clientdata[i].c, &opts);
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
while (test_finished < num_clients)
{
MyLog(LOGA_DEBUG, "num_clients %d test_finished %d\n", num_clients, test_finished);
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
}
MyLog(LOGA_DEBUG, "TEST3: destroying clients");
for (i = 0; i < num_clients; ++i)
MQTTAsync_destroy(&clientdata[i].c);
exit:
MyLog(LOGA_INFO, "TEST3: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
void* test4_payload = NULL;
int test4_payloadlen = 0;
void test4_onPublish(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MyLog(LOGA_DEBUG, "In publish onSuccess callback, context %p", context);
}
int test4_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
MQTTAsync c = (MQTTAsync)context;
static int message_count = 0;
int rc, i;
MyLog(LOGA_DEBUG, "In messageArrived callback %p", c);
assert("Message size correct", message->payloadlen == test4_payloadlen,
"message size was %d", message->payloadlen);
for (i = 0; i < options.size; ++i)
{
if (((char*)test4_payload)[i] != ((char*)message->payload)[i])
{
assert("Message contents correct", ((char*)test4_payload)[i] != ((char*)message->payload)[i],
"message content was %c", ((char*)message->payload)[i]);
break;
}
}
if (++message_count == 1)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = test4_payload;
pubmsg.payloadlen = test4_payloadlen;
pubmsg.qos = 1;
pubmsg.retained = 0;
opts.onSuccess = test4_onPublish;
opts.context = c;
rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts);
}
else if (message_count == 2)
{
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
pubmsg.payload = test4_payload;
pubmsg.payloadlen = test4_payloadlen;
pubmsg.qos = 0;
pubmsg.retained = 0;
opts.onSuccess = test4_onPublish;
opts.context = c;
rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts);
}
else
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = test1_onUnsubscribe;
opts.context = c;
rc = MQTTAsync_unsubscribe(c, test_topic, &opts);
assert("Unsubscribe successful", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
}
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void test4_onSubscribe(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc, i;
MyLog(LOGA_DEBUG, "In subscribe onSuccess callback %p", c);
pubmsg.payload = test4_payload = malloc(options.size);
pubmsg.payloadlen = test4_payloadlen = options.size;
srand(33);
for (i = 0; i < options.size; ++i)
((char*)pubmsg.payload)[i] = rand() % 256;
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTAsync_send(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL);
}
void test4_onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync c = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
MyLog(LOGA_DEBUG, "In connect onSuccess callback, context %p", context);
opts.onSuccess = test4_onSubscribe;
opts.context = c;
rc = MQTTAsync_subscribe(c, test_topic, 2, &opts);
assert("Good rc from subscribe", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
test_finished = 1;
}
/*********************************************************************
Test4: Send and receive big messages
*********************************************************************/
int test4(struct Options options)
{
int subsqos = 2;
MQTTAsync c;
MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer;
int rc = 0;
char* test_topic = "C client test4";
test_finished = failures = 0;
MyLog(LOGA_INFO, "Starting test 4 - big messages");
rc = MQTTAsync_create(&c, options.connection, "async_test_4",
MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);
assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc);
if (rc != MQTTASYNC_SUCCESS)
{
MQTTAsync_destroy(&c);
goto exit;
}
rc = MQTTAsync_setCallbacks(c, c, NULL, test4_messageArrived, NULL);
assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
opts.keepAliveInterval = 20;
opts.cleansession = 1;
opts.username = "testuser";
opts.password = "testpassword";
opts.will = &wopts;
opts.will->message = "will message";
opts.will->qos = 1;
opts.will->retained = 0;
opts.will->topicName = "will topic";
opts.will = NULL;
opts.onSuccess = test4_onConnect;
opts.onFailure = NULL;
opts.context = c;
MyLog(LOGA_DEBUG, "Connecting");
rc = MQTTAsync_connect(c, &opts);
rc = 0;
assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc);
if (rc != MQTTASYNC_SUCCESS)
goto exit;
while (!test_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(1000L);
#endif
MQTTAsync_destroy(&c);
exit:
MyLog(LOGA_INFO, "TEST4: test %s. %d tests run, %d failures.",
(failures == 0) ? "passed" : "failed", tests, failures);
return failures;
}
void trace_callback(enum MQTTASYNC_TRACE_LEVELS level, char* message)
{
if (strstr(message, "onnect") && !strstr(message, "isconnect"))
printf("Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
int rc = 0;
int (*tests[])() = {NULL, test1, test2, test3, test4}; /* indexed starting from 1 */
MQTTAsync_nameValue* info;
getopts(argc, argv);
MQTTAsync_setTraceCallback(trace_callback);
info = MQTTAsync_getVersionInfo();
while (info->name)
{
MyLog(LOGA_INFO, "%s: %s", info->name, info->value);
info++;
}
if (options.test_no == -1)
{ /* run all the tests */
for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
{
failures = 0;
//MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
rc += tests[options.test_no](options); /* return number of failures. 0 = test succeeded */
}
}
else
{
//MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
rc = tests[options.test_no](options); /* run just the selected test */
}
if (failures == 0)
MyLog(LOGA_INFO, "verdict pass");
else
MyLog(LOGA_INFO, "verdict fail");
return rc;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment