• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*******************************************************************************
2  * Copyright (c) 2014 IBM Corp.
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * and Eclipse Distribution License v1.0 which accompany this distribution.
7  *
8  * The Eclipse Public License is available at
9  *    http://www.eclipse.org/legal/epl-v10.html
10  * and the Eclipse Distribution License is available at
11  *   http://www.eclipse.org/org/documents/edl-v10.php.
12  *
13  * Contributors:
14  *    Ian Craggs - initial API and implementation and/or initial documentation
15  *******************************************************************************/
16 
17 
18 #include <string.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include "MQTTPacket.h"
22 
23 #if !defined(_WINDOWS)
24 #include <sys/time.h>
25 #include <sys/socket.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #else
29 #include <winsock2.h>
30 #include <ws2tcpip.h>
31 #define MAXHOSTNAMELEN 256
32 #define EAGAIN WSAEWOULDBLOCK
33 #define EINTR WSAEINTR
34 #define EINPROGRESS WSAEINPROGRESS
35 #define EWOULDBLOCK WSAEWOULDBLOCK
36 #define ENOTCONN WSAENOTCONN
37 #define ECONNRESET WSAECONNRESET
38 #endif
39 
40 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
41 
42 struct Options {
43     char* connection;         /**< connection to system under test. */
44     char** haconnections;
45     int hacount;
46     int verbose;
47     int test_no;
48 } options = {
49     "tcp://m2m.eclipse.org:1883",
50     NULL,
51     0,
52     0,
53     0,
54 };
55 
usage(void)56 void usage(void)
57 {
58 }
59 
getopts(int argc,char ** argv)60 void getopts(int argc, char** argv)
61 {
62     int count = 1;
63 
64     while (count < argc) {
65         if (strcmp(argv[count], "--test_no") == 0) {
66             if (++count < argc) {
67                 options.test_no = atoi(argv[count]);
68             } else {
69                 usage();
70             }
71         } else if (strcmp(argv[count], "--connection") == 0) {
72             if (++count < argc) {
73                 options.connection = argv[count];
74                 printf("\nSetting connection to %s\n", options.connection);
75             } else {
76                 usage();
77             }
78         } else if (strcmp(argv[count], "--haconnections") == 0) {
79             if (++count < argc) {
80                 char* tok = strtok(argv[count], " ");
81                 options.hacount = 0;
82                 options.haconnections = malloc(sizeof(char*) * 5);
83                 while (tok) {
84                     options.haconnections[options.hacount] = malloc(strlen(tok) + 1);
85                     strcpy(options.haconnections[options.hacount], tok);
86                     options.hacount++;
87                     tok = strtok(NULL, " ");
88                 }
89             } else {
90                 usage();
91             }
92         } else if (strcmp(argv[count], "--verbose") == 0) {
93             options.verbose = 1;
94             printf("\nSetting verbose on\n");
95         }
96         count++;
97     }
98 }
99 
100 #define LOGA_DEBUG 0
101 #define LOGA_INFO 1
102 #include <stdarg.h>
103 #include <time.h>
104 #include <sys/timeb.h>
MyLog(int LOGA_level,char * format,...)105 void MyLog(int LOGA_level, char* format, ...)
106 {
107     static char msg_buf[256];
108     va_list args;
109     struct timeb ts;
110 
111     struct tm *timeinfo;
112 
113     if (LOGA_level == LOGA_DEBUG && options.verbose == 0) {
114         return;
115     }
116 
117     ftime(&ts);
118     timeinfo = localtime(&ts.time);
119     strftime(msg_buf, 80, "%Y%m%d %H%M%S", timeinfo);
120 
121     sprintf(&msg_buf[strlen(msg_buf)], ".%.3hu ", ts.millitm);
122 
123     va_start(args, format);
124     vsnprintf(&msg_buf[strlen(msg_buf)], sizeof(msg_buf) - strlen(msg_buf), format, args);
125     va_end(args);
126 
127     printf("%s\n", msg_buf);
128     fflush(stdout);
129 }
130 
131 
132 #if defined(WIN32) || defined(_WINDOWS)
133 #define mqsleep(A) Sleep(1000*A)
134 #define START_TIME_TYPE DWORD
135 static DWORD start_time = 0;
start_clock(void)136 START_TIME_TYPE start_clock(void)
137 {
138     return GetTickCount();
139 }
140 #elif defined(AIX)
141 #define mqsleep sleep
142 #define START_TIME_TYPE struct timespec
start_clock(void)143 START_TIME_TYPE start_clock(void)
144 {
145     static struct timespec start;
146     clock_gettime(CLOCK_REALTIME, &start);
147     return start;
148 }
149 #else
150 #define mqsleep sleep
151 #define START_TIME_TYPE struct timeval
152 /* Todo - unused - remove? static struct timeval start_time; */
start_clock(void)153 START_TIME_TYPE start_clock(void)
154 {
155     struct timeval start_time;
156     gettimeofday(&start_time, NULL);
157     return start_time;
158 }
159 #endif
160 
161 
162 #if defined(WIN32)
elapsed(START_TIME_TYPE start_time)163 long elapsed(START_TIME_TYPE start_time)
164 {
165     return GetTickCount() - start_time;
166 }
167 #elif defined(AIX)
168 #define assert(a)
elapsed(struct timespec start)169 long elapsed(struct timespec start)
170 {
171     struct timespec now, res;
172 
173     clock_gettime(CLOCK_REALTIME, &now);
174     ntimersub(now, start, res);
175     return (res.tv_sec)*1000L + (res.tv_nsec)/1000000L;
176 }
177 #else
elapsed(START_TIME_TYPE start_time)178 long elapsed(START_TIME_TYPE start_time)
179 {
180     struct timeval now, res;
181 
182     gettimeofday(&now, NULL);
183     timersub(&now, &start_time, &res);
184     return (res.tv_sec)*1000 + (res.tv_usec)/1000;
185 }
186 #endif
187 
188 #define assert(a, b, c, d) myassert(__FILE__, __LINE__, a, b, c, d)
189 #define assert1(a, b, c, d, e) myassert(__FILE__, __LINE__, a, b, c, d, e)
190 
191 int tests = 0;
192 int failures = 0;
193 FILE* xml;
194 START_TIME_TYPE global_start_time;
195 char output[3000];
196 char* cur_output = output;
197 
198 
write_test_result(void)199 void write_test_result(void)
200 {
201     long duration = elapsed(global_start_time);
202 
203     fprintf(xml, " time=\"%ld.%.3ld\" >\n", duration / 1000, duration % 1000);
204     if (cur_output != output) {
205         fprintf(xml, "%s", output);
206         cur_output = output;
207     }
208     fprintf(xml, "</testcase>\n");
209 }
210 
211 
myassert(char * filename,int lineno,char * description,int value,char * format,...)212 void myassert(char* filename, int lineno, char* description, int value, char* format, ...)
213 {
214     ++tests;
215     if (!value) {
216         va_list args;
217 
218         ++failures;
219         printf("Assertion failed, file %s, line %d, description: %s\n", filename, lineno, description);
220 
221         va_start(args, format);
222         vprintf(format, args);
223         va_end(args);
224 
225         cur_output += sprintf(cur_output, "<failure type=\"%s\">file %s, line %d </failure>\n",
226             description, filename, lineno);
227     } else {
228         MyLog(LOGA_DEBUG, "Assertion succeeded, file %s, line %d, description: %s", filename, lineno, description);
229     }
230 }
231 
232 #define min(a, b) (((a) < (b)) ? (a) : (b))
233 
checkMQTTStrings(MQTTString a,MQTTString b)234 int checkMQTTStrings(MQTTString a, MQTTString b)
235 {
236     if (!a.lenstring.data) {
237         a.lenstring.data = a.cstring;
238         if (a.cstring)
239             a.lenstring.len = strlen(a.cstring);
240     }
241     if (!b.lenstring.data) {
242         b.lenstring.data = b.cstring;
243         if (b.cstring)
244             b.lenstring.len = strlen(b.cstring);
245     }
246     return memcmp(a.lenstring.data, b.lenstring.data, min(a.lenstring.len, b.lenstring.len)) == 0;
247 }
248 
249 
checkConnectPackets(MQTTPacket_connectData * before,MQTTPacket_connectData * after)250 int checkConnectPackets(MQTTPacket_connectData* before, MQTTPacket_connectData* after)
251 {
252     int rc = 0;
253     int start_failures = failures;
254 
255     assert("struct_ids should be the same",
256             memcmp(before->struct_id, after->struct_id, 4) == 0, "struct_ids were different %.4s\n", after->struct_id);
257 
258     assert("struct_versions should be the same",
259             before->struct_version == after->struct_version, "struct_versions were different\n", rc);
260 
261     assert("MQTT versions should be the same",
262             before->MQTTVersion == after->MQTTVersion, "MQTT versions were different\n", rc);
263 
264     assert("ClientIDs should be the same",
265             checkMQTTStrings(before->clientID, after->clientID), "ClientIDs were different\n", rc);
266 
267     assert("keepAliveIntervals should be the same",
268             before->keepAliveInterval == after->keepAliveInterval,
269                 "keepAliveIntervals were different %d\n", after->keepAliveInterval);
270 
271     assert("cleansessions should be the same",
272             before->cleansession == after->cleansession, "cleansessions were different\n", rc);
273 
274     assert("willFlags should be the same",
275         before->willFlag == after->willFlag, "willFlags were different\n", rc);
276 
277     if (before->willFlag) {
278         assert("will struct_ids should be the same",
279                 memcmp(before->will.struct_id, after->will.struct_id, 4) == 0,
280                     "will struct_ids were different %.4s\n", after->struct_id);
281 
282         assert("will struct_versions should be the same",
283                 before->will.struct_version == after->will.struct_version, "will struct_versions were different\n", rc);
284 
285         assert("topic names should be the same",
286                 checkMQTTStrings(before->will.topicName, after->will.topicName), "topic names were different\n", rc);
287 
288         assert("messages should be the same",
289                 checkMQTTStrings(before->will.message, after->will.message), "messages were different\n", rc);
290 
291         assert("retained flags should be the same",
292                     before->will.retained == after->will.retained, "retained flags were different\n", rc);
293 
294         assert("will qos should be the same",
295                     before->will.qos == after->will.qos, "will qos were different\n", rc);
296     }
297 
298     assert("usernames should be the same",
299             checkMQTTStrings(before->clientID, after->clientID), "usernames were different\n", rc);
300     assert("passwords should be the same",
301             checkMQTTStrings(before->password, after->password), "passwords were different\n", rc);
302     return failures == start_failures;
303 }
304 
test1(struct Options options)305 int test1(struct Options options)
306 {
307     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
308     MQTTPacket_connectData data_after = MQTTPacket_connectData_initializer;
309     int rc = 0;
310     unsigned char buf[100];
311     int buflen = sizeof(buf);
312 
313     fprintf(xml, "<testcase classname=\"test1\" name=\"de/serialization\"");
314     global_start_time = start_clock();
315     failures = 0;
316     MyLog(LOGA_INFO, "Starting test 1 - serialization of connect and back");
317 
318     data.clientID.cstring = "me";
319 
320     data.keepAliveInterval = 20;
321     data.cleansession = 1;
322     data.username.cstring = "testuser";
323     data.password.cstring = "testpassword";
324 
325     data.willFlag = 1;
326     data.will.message.cstring = "will message";
327     data.will.qos = 1;
328     data.will.retained = 0;
329     data.will.topicName.cstring = "will topic";
330 
331     rc = MQTTSerialize_connect(buf, buflen, &data);
332     assert("good rc from serialize connect", rc > 0, "rc was %d\n", rc);
333 
334     rc = MQTTDeserialize_connect(&data_after, buf, buflen);
335     assert("good rc from deserialize connect", rc == 1, "rc was %d\n", rc);
336 
337     /* data after should be the same as data before */
338     rc = checkConnectPackets(&data, &data_after);
339     assert("packets should be the same",  rc == 1, "packets were different\n", rc);
340 
341 /* exit: */
342     MyLog(LOGA_INFO, "TEST1: test %s. %d tests run, %d failures.",
343         (failures == 0) ? "passed" : "failed", tests, failures);
344     write_test_result();
345     return failures;
346 }
347 
348 
test2(struct Options options)349 int test2(struct Options options)
350 {
351     int rc = 0;
352     unsigned char buf[100];
353     int buflen = sizeof(buf);
354 
355     unsigned char dup = 0;
356     int qos = 2;
357     unsigned char retained = 0;
358     unsigned short msgid = 23;
359     MQTTString topicString = MQTTString_initializer;
360     unsigned char *payload = (unsigned char*)"kkhkhkjkj jkjjk jk jk ";
361     int payloadlen = strlen((char*)payload);
362 
363     unsigned char dup2 = 1;
364     int qos2 = 1;
365     unsigned char retained2 = 1;
366     unsigned short msgid2 = 3243;
367     MQTTString topicString2 = MQTTString_initializer;
368     unsigned char *payload2 = NULL;
369     int payloadlen2 = 0;
370 
371     fprintf(xml, "<testcase classname=\"test1\" name=\"de/serialization\"");
372     global_start_time = start_clock();
373     failures = 0;
374     MyLog(LOGA_INFO, "Starting test 2 - serialization of publish and back");
375 
376     topicString.cstring = "mytopic";
377     rc = MQTTSerialize_publish(buf, buflen, dup, qos, retained, msgid, topicString,
378         payload, payloadlen);
379     assert("good rc from serialize publish", rc > 0, "rc was %d\n", rc);
380 
381     rc = MQTTDeserialize_publish(&dup2, &qos2, &retained2, &msgid2, &topicString2,
382         &payload2, &payloadlen2, buf, buflen);
383     assert("good rc from deserialize publish", rc == 1, "rc was %d\n", rc);
384 
385     /* data after should be the same as data before */
386     assert("dups should be the same", dup == dup2, "dups were different %d\n", dup2);
387     assert("qoss should be the same", qos == qos2, "qoss were different %d\n", qos2);
388     assert("retaineds should be the same", retained == retained2, "retaineds were different %d\n", retained2);
389     assert("msgids should be the same", msgid == msgid2, "msgids were different %d\n", msgid2);
390 
391     assert("topics should be the same",
392         checkMQTTStrings(topicString, topicString2), "topics were different %s\n", ""); // topicString2);
393 
394     assert("payload lengths should be the same",
395         payloadlen == payloadlen2, "payload lengths were different %d\n", payloadlen2);
396 
397     assert("payloads should be the same",
398         memcmp(payload, payload2, payloadlen) == 0, "payloads were different %s\n", "");
399 
400     /* exit: */
401     MyLog(LOGA_INFO, "TEST2: test %s. %d tests run, %d failures.",
402         (failures == 0) ? "passed" : "failed", tests, failures);
403     write_test_result();
404     return failures;
405 }
406 
test3(struct Options options)407 int test3(struct Options options)
408 {
409     int i = 0;
410     int rc = 0;
411     unsigned char buf[100];
412     int buflen = sizeof(buf);
413 #define TOPIC_COUNT 2
414 
415     unsigned char dup = 0;
416     unsigned short msgid = 23;
417     int count = TOPIC_COUNT;
418     MQTTString topicStrings[TOPIC_COUNT] = { MQTTString_initializer, MQTTString_initializer };
419     int req_qoss[TOPIC_COUNT] = {2, 1};
420 
421     unsigned char dup2 = 1;
422     unsigned short msgid2 = 2223;
423     int count2 = 0;
424     MQTTString topicStrings2[TOPIC_COUNT] = { MQTTString_initializer, MQTTString_initializer };
425     int req_qoss2[TOPIC_COUNT] = {0, 0};
426 
427     fprintf(xml, "<testcase classname=\"test1\" name=\"de/serialization\"");
428     global_start_time = start_clock();
429     failures = 0;
430     MyLog(LOGA_INFO, "Starting test 2 - serialization of subscribe and back");
431 
432     topicStrings[0].cstring = "mytopic";
433     topicStrings[1].cstring = "mytopic2";
434     rc = MQTTSerialize_subscribe(buf, buflen, dup, msgid, count, topicStrings, req_qoss);
435     assert("good rc from serialize subscribe", rc > 0, "rc was %d\n", rc);
436 
437     rc = MQTTDeserialize_subscribe(&dup2, &msgid2, 2, &count2, topicStrings2, req_qoss2, buf, buflen);
438     assert("good rc from deserialize subscribe", rc == 1, "rc was %d\n", rc);
439 
440     /* data after should be the same as data before */
441     assert("dups should be the same", dup == dup2, "dups were different %d\n", dup2);
442     assert("msgids should be the same", msgid == msgid2, "msgids were different %d\n", msgid2);
443 
444     assert("count should be the same", count == count2, "counts were different %d\n", count2);
445 
446     for (i = 0; i < count2; ++i) {
447         assert("topics should be the same",
448             checkMQTTStrings(topicStrings[i], topicStrings2[i]), "topics were different %s\n", "");
449 
450         assert("qoss should be the same", req_qoss[i] == req_qoss2[i], "qoss were different %d\n", req_qoss2[i]);
451     }
452 
453     /* exit: */
454     MyLog(LOGA_INFO, "TEST3: test %s. %d tests run, %d failures.",
455         (failures == 0) ? "passed" : "failed", tests, failures);
456     write_test_result();
457     return failures;
458 }
459 
460 
test4(struct Options options)461 int test4(struct Options options)
462 {
463     int i = 0;
464     int rc = 0;
465     unsigned char buf[100];
466     int buflen = sizeof(buf);
467 #define TOPIC_COUNT 2
468 
469     int msgid = 23;
470     int count = TOPIC_COUNT;
471     int granted_qoss[TOPIC_COUNT] = {2, 1};
472 
473     unsigned short msgid2 = 2223;
474     int count2 = 0;
475     int granted_qoss2[TOPIC_COUNT] = {0, 0};
476 
477     fprintf(xml, "<testcase classname=\"test1\" name=\"de/serialization\"");
478     global_start_time = start_clock();
479     failures = 0;
480     MyLog(LOGA_INFO, "Starting test 4 - serialization of suback and back");
481 
482     rc = MQTTSerialize_suback(buf, buflen, msgid, count, granted_qoss);
483     assert("good rc from serialize suback", rc > 0, "rc was %d\n", rc);
484 
485     rc = MQTTDeserialize_suback(&msgid2, 2, &count2, granted_qoss2, buf, buflen);
486     assert("good rc from deserialize suback", rc == 1, "rc was %d\n", rc);
487 
488     /* data after should be the same as data before */
489     assert("msgids should be the same", msgid == msgid2, "msgids were different %d\n", msgid2);
490 
491     assert("count should be the same", count == count2, "counts were different %d\n", count2);
492 
493     for (i = 0; i < count2; ++i) {
494         assert("qoss should be the same", granted_qoss[i] == granted_qoss2[i],
495             "qoss were different %d\n", granted_qoss2[i]);
496     }
497 
498 /* exit: */
499     MyLog(LOGA_INFO, "TEST4: test %s. %d tests run, %d failures.",
500         (failures == 0) ? "passed" : "failed", tests, failures);
501     write_test_result();
502     return failures;
503 }
504 
505 
test5(struct Options options)506 int test5(struct Options options)
507 {
508     int i = 0;
509     int rc = 0;
510     unsigned char buf[100];
511     int buflen = sizeof(buf);
512 #define TOPIC_COUNT 2
513 
514     unsigned char dup = 0;
515     unsigned short msgid = 23;
516     int count = TOPIC_COUNT;
517     MQTTString topicStrings[TOPIC_COUNT] = { MQTTString_initializer, MQTTString_initializer };
518 
519     unsigned char dup2 = 1;
520     unsigned short msgid2 = 2223;
521     int count2 = 0;
522     MQTTString topicStrings2[TOPIC_COUNT] = { MQTTString_initializer, MQTTString_initializer };
523 
524     fprintf(xml, "<testcase classname=\"test1\" name=\"de/serialization\"");
525     global_start_time = start_clock();
526     failures = 0;
527     MyLog(LOGA_INFO, "Starting test 2 - serialization of unsubscribe and back");
528 
529     topicStrings[0].cstring = "mytopic";
530     topicStrings[1].cstring = "mytopic2";
531     rc = MQTTSerialize_unsubscribe(buf, buflen, dup, msgid, count, topicStrings);
532     assert("good rc from serialize unsubscribe", rc > 0, "rc was %d\n", rc);
533 
534     rc = MQTTDeserialize_unsubscribe(&dup2, &msgid2, 2, &count2, topicStrings2, buf, buflen);
535     assert("good rc from deserialize unsubscribe", rc == 1, "rc was %d\n", rc);
536 
537     /* data after should be the same as data before */
538     assert("dups should be the same", dup == dup2, "dups were different %d\n", dup2);
539     assert("msgids should be the same", msgid == msgid2, "msgids were different %d\n", msgid2);
540 
541     assert("count should be the same", count == count2, "counts were different %d\n", count2);
542 
543     for (i = 0; i < count2; ++i)
544         assert("topics should be the same",
545             checkMQTTStrings(topicStrings[i], topicStrings2[i]), "topics were different %s\n", "");
546 
547 /* exit: */
548     MyLog(LOGA_INFO, "TEST5: test %s. %d tests run, %d failures.",
549         (failures == 0) ? "passed" : "failed", tests, failures);
550     write_test_result();
551     return failures;
552 }
553 
test6(struct Options options)554 int test6(struct Options options)
555 {
556     int rc = 0;
557     unsigned char buf[100];
558     int buflen = sizeof(buf);
559 
560     unsigned char sessionPresent = 1;
561     unsigned char connack_rc = 77;
562 
563     unsigned char sessionPresent2 = 0;
564     unsigned char connack_rc2 = 0;
565 
566     fprintf(xml, "<testcase classname=\"test1\" name=\"de/serialization\"");
567     global_start_time = start_clock();
568     failures = 0;
569     MyLog(LOGA_INFO, "Starting test 2 - serialization of connack and back");
570 
571     rc = MQTTSerialize_connack(buf, buflen, connack_rc, sessionPresent);
572     assert("good rc from serialize connack", rc > 0, "rc was %d\n", rc);
573 
574     rc = MQTTDeserialize_connack(&sessionPresent2, &connack_rc2, buf, buflen);
575     assert("good rc from deserialize connack", rc == 1, "rc was %d\n", rc);
576 
577     /* data after should be the same as data before */
578     assert("connack rcs should be the same", connack_rc == connack_rc2, "connack rcs were different %d\n", connack_rc2);
579     assert("session present flags should be the same", sessionPresent == sessionPresent2,
580             "session present flags were different %d\n", sessionPresent2);
581 
582 /* exit: */
583     MyLog(LOGA_INFO, "TEST6: test %s. %d tests run, %d failures.",
584         (failures == 0) ? "passed" : "failed", tests, failures);
585     write_test_result();
586     return failures;
587 }
588 
main(int argc,char ** argv)589 int main(int argc, char** argv)
590 {
591     int rc = 0;
592      int (*tests[])() = {NULL, test1, test2, test3, test4, test5, test6};
593 
594     xml = fopen("TEST-test1.xml", "w");
595     fprintf(xml, "<testsuite name=\"test1\" tests=\"%d\">\n", (int)(ARRAY_SIZE(tests) - 1));
596 
597     getopts(argc, argv);
598     if (options.test_no == 0) { /* run all the tests */
599         for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no) {
600             rc += tests[options.test_no](options); /* return number of failures.  0 = test succeeded */
601         }
602     } else {
603         rc = tests[options.test_no](options); /* run just the selected test */
604     }
605     if (rc == 0) {
606         MyLog(LOGA_INFO, "verdict pass");
607     } else {
608         MyLog(LOGA_INFO, "verdict fail");
609     }
610 
611     fprintf(xml, "</testsuite>\n");
612     fclose(xml);
613     return rc;
614 }
615