mosquitto-1.6.9/0000775000175000017500000000000013626052637012625 5ustar rogerrogermosquitto-1.6.9/pskfile.example0000664000175000017500000000002713626052637015636 0ustar rogerrogerid:deadbeef easy:12345 mosquitto-1.6.9/security/0000775000175000017500000000000013626052637014474 5ustar rogerrogermosquitto-1.6.9/security/mosquitto.apparmor0000664000175000017500000000110213626052637020275 0ustar rogerroger/usr/sbin/mosquitto { #include #include /usr/sbin/mosquitto r, /etc/mosquitto/mosquitto.conf r, /etc/mosquitto/ca_certificates/* r, /etc/mosquitto/certs/* r, /etc/mosquitto/conf.d/* r, /var/lib/mosquitto/ r, /var/lib/mosquitto/mosquitto.db rwk, /var/run/mosquitto.pid rw, network inet stream, network inet6 stream, network inet dgram, network inet6 dgram, # For drop privileges capability setgid, capability setuid, # For tcp-wrappers /lib{,32,64}/libwrap.so* rm, /etc/hosts.allow r, /etc/hosts.deny r, } mosquitto-1.6.9/service/0000775000175000017500000000000013626052637014265 5ustar rogerrogermosquitto-1.6.9/service/upstart/0000775000175000017500000000000013626052637015767 5ustar rogerrogermosquitto-1.6.9/service/upstart/mosquitto.conf0000664000175000017500000000026213626052637020702 0ustar rogerrogerdescription "Mosquitto MQTTv3.1 broker" author "Roger Light " start on net-device-up respawn exec /usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf mosquitto-1.6.9/service/svscan/0000775000175000017500000000000013626052637015562 5ustar rogerrogermosquitto-1.6.9/service/svscan/run0000775000175000017500000000010013626052637016303 0ustar rogerroger#!/bin/sh /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf mosquitto-1.6.9/service/systemd/0000775000175000017500000000000013626052637015755 5ustar rogerrogermosquitto-1.6.9/service/systemd/mosquitto.service.simple0000664000175000017500000000051013626052637022667 0ustar rogerroger[Unit] Description=Mosquitto MQTT v3.1/v3.1.1 Broker Documentation=man:mosquitto.conf(5) man:mosquitto(8) After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target mosquitto-1.6.9/service/systemd/README0000664000175000017500000000101013626052637016625 0ustar rogerrogerSelect appropriate systemd service based on your compile settings. If you enabled WITH_SYSTEMD, use mosquitto.service.notify, otherwise use mosquitto.service.simple. The service must be renamed to mosquitto.service before usage. Don't forget to change default paths in service file if you changed the default build settings. With WITH_SYSTEMD mosquitto will notify a complete startup after initialization. This means that follow-up units can be started after full initialization of mosquitto (i.e. sockets are opened). mosquitto-1.6.9/service/systemd/mosquitto.service.notify0000664000175000017500000000054613626052637022717 0ustar rogerroger[Unit] Description=Mosquitto MQTT v3.1/v3.1.1 Broker Documentation=man:mosquitto.conf(5) man:mosquitto(8) After=network-online.target Wants=network-online.target [Service] Type=notify NotifyAccess=main ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target mosquitto-1.6.9/service/monit/0000775000175000017500000000000013626052637015413 5ustar rogerrogermosquitto-1.6.9/service/monit/mosquitto.monit0000664000175000017500000000021113626052637020521 0ustar rogerrogercheck process mosquitto with pidfile /var/run/mosquitto.pid start = "/etc/init.d/mosquitto start" stop = "/etc/init.d/mosquitto stop" mosquitto-1.6.9/config.mk0000664000175000017500000002134213626052637014425 0ustar rogerroger# ============================================================================= # User configuration section. # # These options control compilation on all systems apart from Windows and Mac # OS X. Use CMake to compile on Windows and Mac. # # Largely, these are options that are designed to make mosquitto run more # easily in restrictive environments by removing features. # # Modify the variable below to enable/disable features. # # Can also be overriden at the command line, e.g.: # # make WITH_TLS=no # ============================================================================= # Uncomment to compile the broker with tcpd/libwrap support. #WITH_WRAP:=yes # Comment out to disable SSL/TLS support in the broker and client. # Disabling this will also mean that passwords must be stored in plain text. It # is strongly recommended that you only disable WITH_TLS if you are not using # password authentication at all. WITH_TLS:=yes # Comment out to disable TLS/PSK support in the broker and client. Requires # WITH_TLS=yes. # This must be disabled if using openssl < 1.0. WITH_TLS_PSK:=yes # Comment out to disable client threading support. WITH_THREADING:=yes # Comment out to remove bridge support from the broker. This allow the broker # to connect to other brokers and subscribe/publish to topics. You probably # want to leave this included unless you want to save a very small amount of # memory size and CPU time. WITH_BRIDGE:=yes # Comment out to remove persistent database support from the broker. This # allows the broker to store retained messages and durable subscriptions to a # file periodically and on shutdown. This is usually desirable (and is # suggested by the MQTT spec), but it can be disabled if required. WITH_PERSISTENCE:=yes # Comment out to remove memory tracking support from the broker. If disabled, # mosquitto won't track heap memory usage nor export '$SYS/broker/heap/current # size', but will use slightly less memory and CPU time. WITH_MEMORY_TRACKING:=yes # Compile with database upgrading support? If disabled, mosquitto won't # automatically upgrade old database versions. # Not currently supported. #WITH_DB_UPGRADE:=yes # Comment out to remove publishing of the $SYS topic hierarchy containing # information about the broker state. WITH_SYS_TREE:=yes # Build with systemd support. If enabled, mosquitto will notify systemd after # initialization. See README in service/systemd/ for more information. WITH_SYSTEMD:=no # Build with SRV lookup support. WITH_SRV:=no # Build with websockets support on the broker. WITH_WEBSOCKETS:=no # Use elliptic keys in broker WITH_EC:=yes # Build man page documentation by default. WITH_DOCS:=yes # Build with client support for SOCK5 proxy. WITH_SOCKS:=yes # Strip executables and shared libraries on install. WITH_STRIP:=no # Build static libraries WITH_STATIC_LIBRARIES:=no # Use this variable to add extra library dependencies when building the clients # with the static libmosquitto library. This may be required on some systems # where e.g. -lz or -latomic are needed for openssl. CLIENT_STATIC_LDADD:= # Build shared libraries WITH_SHARED_LIBRARIES:=yes # Build with async dns lookup support for bridges (temporary). Requires glibc. #WITH_ADNS:=yes # Build with epoll support. WITH_EPOLL:=yes # Build with bundled uthash.h WITH_BUNDLED_DEPS:=yes # Build with coverage options WITH_COVERAGE:=no # ============================================================================= # End of user configuration # ============================================================================= # Also bump lib/mosquitto.h, CMakeLists.txt, # installer/mosquitto.nsi, installer/mosquitto64.nsi VERSION=1.6.9 # Client library SO version. Bump if incompatible API/ABI changes are made. SOVERSION=1 # Man page generation requires xsltproc and docbook-xsl XSLTPROC=xsltproc --nonet # For html generation DB_HTML_XSL=man/html.xsl #MANCOUNTRIES=en_GB UNAME:=$(shell uname -s) ifeq ($(UNAME),SunOS) ifeq ($(CC),cc) CFLAGS?=-O else CFLAGS?=-Wall -ggdb -O2 endif else CFLAGS?=-Wall -ggdb -O2 endif STATIC_LIB_DEPS:= LIB_CPPFLAGS=$(CPPFLAGS) -I. -I.. -I../lib ifeq ($(WITH_BUNDLED_DEPS),yes) LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -I../src/deps endif LIB_CFLAGS:=$(CFLAGS) LIB_CXXFLAGS:=$(CXXFLAGS) LIB_LDFLAGS:=$(LDFLAGS) LIB_LIBADD:=$(LIBADD) BROKER_CPPFLAGS:=$(LIB_CPPFLAGS) BROKER_CFLAGS:=${CFLAGS} -DVERSION="\"${VERSION}\"" -DWITH_BROKER BROKER_LDFLAGS:=${LDFLAGS} BROKER_LDADD:= CLIENT_CPPFLAGS:=$(CPPFLAGS) -I.. -I../lib CLIENT_CFLAGS:=${CFLAGS} -DVERSION="\"${VERSION}\"" CLIENT_LDFLAGS:=$(LDFLAGS) -L../lib CLIENT_LDADD:= PASSWD_LDADD:= ifneq ($(or $(findstring $(UNAME),FreeBSD), $(findstring $(UNAME),OpenBSD), $(findstring $(UNAME),NetBSD)),) BROKER_LDADD:=$(BROKER_LDADD) -lm else BROKER_LDADD:=$(BROKER_LDADD) -ldl -lm endif ifeq ($(UNAME),Linux) BROKER_LDADD:=$(BROKER_LDADD) -lrt BROKER_LDFLAGS:=$(BROKER_LDFLAGS) -Wl,--dynamic-list=linker.syms LIB_LIBADD:=$(LIB_LIBADD) -lrt endif ifeq ($(WITH_SHARED_LIBRARIES),yes) CLIENT_LDADD:=${CLIENT_LDADD} ../lib/libmosquitto.so.${SOVERSION} endif ifeq ($(UNAME),SunOS) ifeq ($(CC),cc) LIB_CFLAGS:=$(LIB_CFLAGS) -xc99 -KPIC else LIB_CFLAGS:=$(LIB_CFLAGS) -fPIC endif ifeq ($(CXX),CC) LIB_CXXFLAGS:=$(LIB_CXXFLAGS) -KPIC else LIB_CXXFLAGS:=$(LIB_CXXFLAGS) -fPIC endif else LIB_CFLAGS:=$(LIB_CFLAGS) -fPIC LIB_CXXFLAGS:=$(LIB_CXXFLAGS) -fPIC endif ifneq ($(UNAME),SunOS) LIB_LDFLAGS:=$(LIB_LDFLAGS) -Wl,--version-script=linker.version -Wl,-soname,libmosquitto.so.$(SOVERSION) endif ifeq ($(UNAME),QNX) BROKER_LDADD:=$(BROKER_LDADD) -lsocket LIB_LIBADD:=$(LIB_LIBADD) -lsocket endif ifeq ($(WITH_WRAP),yes) BROKER_LDADD:=$(BROKER_LDADD) -lwrap BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_WRAP endif ifeq ($(WITH_TLS),yes) BROKER_LDADD:=$(BROKER_LDADD) -lssl -lcrypto LIB_LIBADD:=$(LIB_LIBADD) -lssl -lcrypto BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_TLS LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_TLS PASSWD_LDADD:=$(PASSWD_LDADD) -lcrypto CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_TLS STATIC_LIB_DEPS:=$(STATIC_LIB_DEPS) -lssl -lcrypto ifeq ($(WITH_TLS_PSK),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_TLS_PSK LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_TLS_PSK CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_TLS_PSK endif endif ifeq ($(WITH_THREADING),yes) LIB_LIBADD:=$(LIB_LIBADD) -lpthread LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_THREADING CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_THREADING STATIC_LIB_DEPS:=$(STATIC_LIB_DEPS) -lpthread endif ifeq ($(WITH_SOCKS),yes) LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_SOCKS CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_SOCKS endif ifeq ($(WITH_BRIDGE),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_BRIDGE endif ifeq ($(WITH_PERSISTENCE),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_PERSISTENCE endif ifeq ($(WITH_MEMORY_TRACKING),yes) ifneq ($(UNAME),SunOS) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_MEMORY_TRACKING endif endif ifeq ($(WITH_SYS_TREE),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_SYS_TREE endif ifeq ($(WITH_SYSTEMD),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_SYSTEMD BROKER_LDADD:=$(BROKER_LDADD) -lsystemd endif ifeq ($(WITH_SRV),yes) LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_SRV LIB_LIBADD:=$(LIB_LIBADD) -lcares CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_SRV STATIC_LIB_DEPS:=$(STATIC_LIB_DEPS) -lcares endif ifeq ($(UNAME),SunOS) BROKER_LDADD:=$(BROKER_LDADD) -lsocket -lnsl LIB_LIBADD:=$(LIB_LIBADD) -lsocket -lnsl endif ifeq ($(WITH_EC),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_EC endif ifeq ($(WITH_ADNS),yes) BROKER_LDADD:=$(BROKER_LDADD) -lanl BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_ADNS endif MAKE_ALL:=mosquitto ifeq ($(WITH_DOCS),yes) MAKE_ALL:=$(MAKE_ALL) docs endif ifeq ($(WITH_WEBSOCKETS),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_WEBSOCKETS BROKER_LDADD:=$(BROKER_LDADD) -lwebsockets endif ifeq ($(WITH_WEBSOCKETS),static) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_WEBSOCKETS BROKER_LDADD:=$(BROKER_LDADD) -static -lwebsockets endif INSTALL?=install prefix?=/usr/local incdir?=${prefix}/include libdir?=${prefix}/lib${LIB_SUFFIX} localedir?=${prefix}/share/locale mandir?=${prefix}/share/man STRIP?=strip ifeq ($(WITH_STRIP),yes) STRIP_OPTS?=-s --strip-program=${CROSS_COMPILE}${STRIP} endif ifeq ($(WITH_EPOLL),yes) ifeq ($(UNAME),Linux) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_EPOLL endif endif ifeq ($(WITH_BUNDLED_DEPS),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -Ideps endif ifeq ($(WITH_COVERAGE),yes) BROKER_CFLAGS:=$(BROKER_CFLAGS) -coverage BROKER_LDFLAGS:=$(BROKER_LDFLAGS) -coverage LIB_CFLAGS:=$(LIB_CFLAGS) -coverage LIB_LDFLAGS:=$(LIB_LDFLAGS) -coverage CLIENT_CFLAGS:=$(CLIENT_CFLAGS) -coverage CLIENT_LDFLAGS:=$(CLIENT_LDFLAGS) -coverage endif BROKER_LDADD:=${BROKER_LDADD} ${LDADD} CLIENT_LDADD:=${CLIENT_LDADD} ${LDADD} PASSWD_LDADD:=${PASSWD_LDADD} ${LDADD} mosquitto-1.6.9/CMakeLists.txt0000664000175000017500000000676213626052637015400 0ustar rogerroger# This is a cmake script. Process it with the CMake gui or command line utility # to produce makefiles / Visual Studio project files on Mac OS X and Windows. # # To configure the build options either use the CMake gui, or run the command # line utility including the "-i" option. set(CMAKE_LEGACY_CYGWIN_WIN32 0) project(mosquitto) cmake_minimum_required(VERSION 2.8) # Only for version 3 and up. cmake_policy(SET CMP0042 NEW) set (VERSION 1.6.9) add_definitions (-DCMAKE -DVERSION=\"${VERSION}\") if (WIN32) add_definitions("-D_CRT_SECURE_NO_WARNINGS") add_definitions("-D_CRT_NONSTDC_NO_DEPRECATE") endif (WIN32) include(GNUInstallDirs) option(WITH_TLS "Include SSL/TLS support?" ON) option(WITH_TLS_PSK "Include TLS-PSK support (requires WITH_TLS)?" ON) option(WITH_EC "Include Elliptic Curve support (requires WITH_TLS)?" ON) if (WITH_TLS) find_package(OpenSSL REQUIRED) add_definitions("-DWITH_TLS") if (WITH_TLS_PSK) add_definitions("-DWITH_TLS_PSK") endif (WITH_TLS_PSK) if (WITH_EC) add_definitions("-DWITH_EC") endif (WITH_EC) else (WITH_TLS) set (OPENSSL_INCLUDE_DIR "") endif (WITH_TLS) option(WITH_SOCKS "Include SOCKS5 support?" ON) if (WITH_SOCKS) add_definitions("-DWITH_SOCKS") endif (WITH_SOCKS) option(WITH_SRV "Include SRV lookup support?" OFF) option(WITH_STATIC_LIBRARIES "Build static versions of the libmosquitto/pp libraries?" OFF) option(WITH_PIC "Build the static library with PIC (Position Independent Code) enabled archives?" OFF) option(WITH_THREADING "Include client library threading support?" ON) if (WITH_THREADING) add_definitions("-DWITH_THREADING") if (WIN32) if (CMAKE_CL_64) set (PTHREAD_LIBRARIES C:\\pthreads\\Pre-built.2\\lib\\x64\\pthreadVC2.lib) else (CMAKE_CL_64) set (PTHREAD_LIBRARIES C:\\pthreads\\Pre-built.2\\lib\\x86\\pthreadVC2.lib) endif (CMAKE_CL_64) set (PTHREAD_INCLUDE_DIR C:\\pthreads\\Pre-built.2\\include) else (WIN32) find_library(LIBPTHREAD pthread) if (LIBPTHREAD) set (PTHREAD_LIBRARIES pthread) else (LIBPTHREAD) set (PTHREAD_LIBRARIES "") endif() set (PTHREAD_INCLUDE_DIR "") endif (WIN32) else (WITH_THREADING) set (PTHREAD_LIBRARIES "") set (PTHREAD_INCLUDE_DIR "") endif (WITH_THREADING) option(DOCUMENTATION "Build documentation?" ON) option(WITH_DLT "Include DLT support?" OFF) message(STATUS "WITH_DLT = ${WITH_DLT}") if (WITH_DLT) #find_package(DLT REQUIRED) find_package(PkgConfig) pkg_check_modules(DLT "automotive-dlt >= 2.11") add_definitions("-DWITH_DLT") endif (WITH_DLT) # ======================================== # Include projects # ======================================== add_subdirectory(lib) add_subdirectory(client) add_subdirectory(src) if (DOCUMENTATION) add_subdirectory(man) endif (DOCUMENTATION) # ======================================== # Install config file # ======================================== install(FILES mosquitto.conf aclfile.example pskfile.example pwfile.example DESTINATION "${CMAKE_INSTALL_SYSCONFDIR}/mosquitto") # ======================================== # Install pkg-config files # ======================================== configure_file(libmosquitto.pc.in libmosquitto.pc @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libmosquitto.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") configure_file(libmosquittopp.pc.in libmosquittopp.pc @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libmosquittopp.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") # ======================================== # Testing # ======================================== enable_testing() mosquitto-1.6.9/about.html0000664000175000017500000000472413626052637014634 0ustar rogerroger About

About This Content

May 8, 2014

License

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html and a copy of the EDL is available at http://www.eclipse.org/org/documents/edl-v10.php. For purposes of the EPL, "Program" will mean the Content.

If you did not receive this Content directly from the Eclipse Foundation, the Content is being redistributed by another party ("Redistributor") and different terms and conditions may apply to your use of any object code in the Content. Check the Redistributor's license that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise indicated below, the terms and conditions of the EPL still apply to any source code in the Content and such source code may be obtained at http://www.eclipse.org.

Third Party Content

The Content includes items that have been sourced from third parties as set out below. If you did not receive this Content directly from the Eclipse Foundation, the following is provided for informational purposes only, and you should look to the Redistributor's license for terms and conditions of use.

libwebsockets 2.4.2

This project makes use of the libwebsockets library.

The use of libwebsockets is based on the terms and conditions of the LGPL 2.1 with some specific exceptions. https://github.com/warmcat/libwebsockets/blob/v2.4.2/LICENSE

When libwebsockets is distributed with the project, it is being used subject to the Static Linking Exception (Section 2) of the License. As a result, the content is not subject to the LGPL 2.1.

mosquitto-1.6.9/aclfile.example0000664000175000017500000000034613626052637015604 0ustar rogerroger# This affects access control for clients with no username. topic read $SYS/# # This only affects clients with username "roger". user roger topic foo/bar # This affects all clients. pattern write $SYS/broker/connection/%c/state mosquitto-1.6.9/ChangeLog.txt0000664000175000017500000030370713626052637015227 0ustar rogerroger1.6.9 - 20200227 ================ Broker: - Fix session expiry with very large expiry intervals. Closes #1525. - Check ACL patterns for validity when loading. Closes #1539. - Use presence of password file as indicator for whether username checks should take place, not whether usernames are defined in the password file. Closes #1545. - Strip whitespace from end of config file string options. Closes #1566. - Satisfy valgrind when exiting on error due to not being able to open a listening socket, by calling freeaddrinfo. Closes #1565. - Fix config->user not being freed on exit. Closes #1564. - Fix trailing whitespace not being trimmed on acl users. Closes #1539. - Fix `bind_interface` not working for the default listener. Closes #1533. - Improve password file parsing in the broker and mosqitto_passwd. Closes #1584. - Print OpenSSL errors in more situations, like when loading certificates fails. Closes #1552. - Fix `mosquitto_client_protocol() returning incorrect values. Client library: - Set minimum keepalive argument to `mosquitto_connect*()` to be 5 seconds. Closes #1550. - Fix `mosquitto_topic_matches_sub()` not returning MOSQ_ERR_INVAL if the topic contains a wildcard. Closes #1589. Clients: - Fix `--remove-retained` not obeying the `-T` option for filtering out topics. Closes #1585. - Default behaviour for v5 clients using `-c` is now to use infinite length sessions, as with v3 clients. Closes #1546. 1.6.8 - 20191128 ================ Broker: - Various fixes for `allow_zero_length_clientid` config, where this option was not being set correctly. Closes #1429. - Fix incorrect memory tracking causing problems with memory_limit option. Closes #1437. - Fix subscription topics being limited to 200 characters instead of 200 hierarchy levels. Closes #1441. - Only a single CRL could be loaded at once. This has been fixed. Closes #1442. - Fix problems with reloading config when `per_listener_settings` was true. Closes #1459. - Fix retained messages with an expiry interval not being expired after being restored from persistence. Closes #1464. - Fix messages with an expiry interval being sent without an expiry interval property just before they were expired. Closes #1464. - Fix TLS Websockets clients not receiving messages after taking over a previous connection. Closes #1489. - Fix MQTT 3.1.1 clients using clean session false, or MQTT 5.0 clients using session-expiry-interval set to infinity never expiring, even when the global `persistent_client_expiration` option was set. Closes #1494. Client library: - Fix publish properties not being passed to on_message_v5 callback for QoS 2 messages. Closes #1432. - Fix documentation issues in mosquitto.h. Closes #1478. - Document `mosquitto_connect_srv()`. Closes #1499. Clients: - Fix duplicate cfg definition in rr_client. Closes #1453. - Fix `mosquitto_pub -l` hang when stdin stream ends. Closes #1448. - Fix `mosquitto_pub -l` not sending the final line of stdin if it does not end with a new line. Closes #1473. - Make documentation for `mosquitto_pub -l` match reality - blank lines are sent as empty messages. Closes #1474. - Free memory in `mosquitto_sub` when quiting without having made a successful connection. Closes #1513. Build: - Added `CLIENT_STATIC_LDADD` to makefile builds to allow more libraries to be linked when compiling the clients with a static libmosquitto, as required for e.g. openssl on some systems. Installer: - Fix mosquitto_rr.exe not being included in Windows installers. Closes #1463. 1.6.7 - 20190925 ================ Broker: - Add workaround for working with libwebsockets 3.2.0. - Fix potential crash when reloading config. Closes #1424, #1425. Client library: - Don't use `/` in autogenerated client ids, to avoid confusing with topics. - Fix `mosquitto_max_inflight_messages_set()` and `mosquitto_int_option(..., MOSQ_OPT_*_MAX, ...)` behaviour. Closes #1417. - Fix regression on use of `mosquitto_connect_async()` not working. Closes #1415 and #1422. Clients: - mosquitto_sub: Fix `-E` incorrectly not working unless `-d` was also specified. Closes #1418. - Updated documentation around automatic client ids. 1.6.6 - 20190917 ================ Security: - Restrict topic hierarchy to 200 levels to prevent possible stack overflow. Closes #1412. Broker: - Restrict topic hierarchy to 200 levels to prevent possible stack overflow. Closes #1412. - mosquitto_passwd now returns 1 when attempting to update a user that does not exist. Closes #1414. 1.6.5 - 20190912 ================ Broker: - Fix v5 DISCONNECT packets with remaining length == 2 being treated as a protocol error. Closes #1367. - Fix support for libwebsockets 3.x. - Fix slow websockets performance when sending large messages. Closes #1390. - Fix bridges potentially not connecting on Windows. Closes #478. - Fix clients authorised using `use_identity_as_username` or `use_subject_as_username` being disconnected on SIGHUP. Closes #1402. - Improve error messages in some situations when clients disconnect. Reduces the number of "Socket error on client X, disconnecting" messages. - Fix Will for v5 clients not being sent if will delay interval was greater than the session expiry interval. Closes #1401. - Fix CRL file not being reloaded on HUP. Closes #35. - Fix repeated "Error in poll" messages on Windows when only websockets listeners are defined. Closes #1391. Client library: - Fix reconnect backoff for the situation where connections are dropped rather than refused. Closes #737. - Fix missing locks on `mosq->state`. Closes #1374. Documentation: - Improve details on global/per listener options in the mosquitto.conf man page. Closes #274. - Clarify behaviour when clients exceed the `message_size_limit`. Closes #448. - Improve documentation for `max_inflight_bytes`, `max_inflight_messages`, and `max_queued_messages`. Build: - Fix missing function warnings on NetBSD. - Fix WITH_STATIC_LIBRARIES using CMake on Windows. Closes #1369. - Guard ssize_t definition on Windows. Closes #522. 1.6.4 - 20190801 ================ Broker: - Fix persistent clients being incorrectly expired on Raspberry Pis. Closes #1272. - Windows: Allow other applications access to the log file when running. Closes #515. - Fix incoming QoS 2 messages being blocked when `max_inflight_messages` was set to 1. Closes #1332. - Fix incoming messages not being removed for a client if the topic being published to does not have any subscribers. Closes #1322. Client library: - Fix MQTT v5 subscription options being incorrectly set for MQTT v3 subscriptions. Closes #1353. - Make behaviour of `mosquitto_connect_async()` consistent with `mosquitto_connect()` when connecting to a non-existent server. Closes #1345. - `mosquitto_string_option(mosq, MOSQ_OPT_TLS_KEYFORM, ...)` was incorrectly returning `MOSQ_ERR_INVAL` with valid input. This has been fixed. Closes #1360. - on_connect callback is now called with the correct v5 reason code if a v5 client connects to a v3.x broker and is sent a CONNACK with the "unacceptable protocol version" connack reason code. - Fix memory leak when setting v5 properties in mosquitto_connect_v5(). - Fix properties not being sent on QoS>0 PUBLISH messages. Clients: - mosquitto_pub: fix error codes not being returned when mosquitto_pub exits. Closes #1354. - All clients: improve error messages when connecting to a v3.x broker when in v5 mode. Closes #1344. Other: - Various documentation fixes. 1.6.3 - 20190618 ================ Broker: - Fix detection of incoming v3.1/v3.1.1 bridges. Closes #1263. - Fix default max_topic_alias listener config not being copied to the in-use listener when compiled without TLS support. - Fix random number generation if compiling using `WITH_TLS=no` and on Linux with glibc >= 2.25. Without this fix, no random numbers would be generated for e.g. on broker client id generation, and so clients connecting expecting this feature would be unable to connect. - Fix compilation problem related to `getrandom()` on non-glibc systems. - Fix Will message for a persistent client incorrectly being sent when the client reconnects after a clean disconnect. Closes #1273. - Fix Will message for a persistent client not being sent on disconnect. Closes #1273. - Improve documentation around the upgrading of persistence files. Closes #1276. - Add 'extern "C"' on mosquitto_broker.h and mosquitto_plugin.h for C++ plugin writing. Closes #1290. - Fix persistent Websockets clients not receiving messages after they reconnect, having sent DISCONNECT on a previous session. Closes #1227. - Disable TLS renegotiation. Client initiated renegotiation is considered to be a potential attack vector against servers. Closes #1257. - Fix incorrect shared subscription topic '$shared'. - Fix zero length client ids being rejected for MQTT v5 clients with clean start set to true. - Fix MQTT v5 overlapping subscription behaviour. Clients now receive message from all matching subscriptions rather than the first one encountered, which ensures the maximum QoS requirement is met. - Fix incoming/outgoing quota problems for QoS>0. - Remove obsolete `store_clean_interval` from documentation. - Fix v4 authentication plugin never calling psk_key_get. Client library: - Fix typo causing build error on Windows when building without TLS support. Closes #1264. Clients: - Fix -L url parsing when `/topic` part is missing. - Stop some error messages being printed even when `--quiet` was used. Closes #1284. - Fix mosquitto_pub exiting with error code 0 when an error occurred. Closes #1285. - Fix mosquitto_pub not using the `-c` option. Closes #1273. - Fix MQTT v5 clients not being able to specify a password without a username. Closes #1274. - Fix `mosquitto_pub -l` not handling network failures. Closes #1152. - Fix `mosquitto_pub -l` not handling zero length input. Closes #1302. - Fix double free on exit in mosquitto_pub. Closes #1280. Documentation: - Remove references to Python binding and C++ wrapper in libmosquitto man page. Closes #1266. Build: - CLIENT_LDFLAGS now uses LDFLAGS. Closes #1294. 1.6.2 - 20190430 ================ Broker: - Fix memory access after free, leading to possible crash, when v5 client with Will message disconnects, where the Will message has as its first property one of `content-type`, `correlation-data`, `payload-format-indicator`, or `response-topic`. Closes #1244. - Fix build for WITH_TLS=no. Closes #1250. - Fix Will message not allowing user-property properties. - Fix broker originated messages (e.g. $SYS/broker/version) not being published when `check_retain_source` set to true. Closes #1245. - Fix $SYS/broker/version being incorrectly expired after 60 seconds. Closes #1245. Library: - Fix crash after client has been unable to connect to a broker. This occurs when the client is exiting and is part of the final library cleanup routine. Closes #1246. Clients: - Fix -L url parsing. Closes #1248. 1.6.1 - 20190426 ================ Broker: - Document `memory_limit` option. Clients: - Fix compilation on non glibc systems due to missing sys/time.h header. Build: - Add `make check` target and document testing procedure. Closes #1230. - Document bundled dependencies and how to disable. Closes #1231. - Split CFLAGS and CPPFLAGS, and LDFLAGS and LDADD/LIBADD. - test/unit now respects CPPFLAGS and LDFLAGS. Closes #1232. - Don't call ldconfig in CMake scripts. Closes #1048. - Use CMAKE_INSTALL_* variables when installing in CMake. Closes #1049. 1.6 - 20190417 ============== Broker features: - Add support for MQTT v5 - Add support for OCSP stapling. - Add support for ALPN on bridge TLS connections. Closes #924. - Add support for Automotive DLT logging. - Add TLS Engine support. - Persistence file read/write performance improvements. - General performance improvements. - Add max_keepalive option, to allow a maximum keepalive value to be set for MQTT v5 clients only. - Add `bind_interface` option which allows a listener to be bound to a specific network interface, in a similar fashion to the `bind_address` option. Linux only. - Add improved bridge restart interval based on Decorrelated Jitter. - Add `dhparamfile` option, to allow DH parameters to be loaded for Ephemeral DH support - Disallow writing to $ topics where appropriate. - Fix mosquitto_passwd crashing on corrupt password file. Closes #1207. - Add explicit support for TLS v1.3. - Drop support for TLS v1.0. - Improved general support for broker generated client ids. Removed libuuid dependency. - auto_id_prefix now defaults to 'auto-'. - QoS 1 and 2 flow control improvements. Client library features: - Add support for MQTT v5 - Add mosquitto_subscribe_multiple() for sending subscriptions to multiple topics in one command. - Add TLS Engine support. - Add explicit support for TLS v1.3. - Drop support for TLS v1.0. - QoS 1 and 2 flow control improvements. Client features: - Add support for MQTT v5 - Add mosquitto_rr client, which can be used for "request-response" messaging, by sending a request message and awaiting a response. - Add TLS Engine support. - Add support for ALPN on TLS connections. Closes #924. - Add -D option for all clients to specify MQTT v5 properties. - Add -E to mosquitto_sub, which causes it to exit immediately after having its subscriptions acknowledged. Use with -c to create a durable client session without requiring a message to be received. - Add --remove-retained to mosquitto_sub, which can be used to clear retained messages on a broker. - Add --repeat and --repeat-delay to mosquitto_pub, which can be used to repeat single message publishes at a regular interval. - -V now accepts `5, `311`, `31`, as well as `mqttv5` etc. - Add explicit support for TLS v1.3. - Drop support for TLS v1.0. Broker fixes: - Improve error reporting when creating listeners. - Fix build on SmartOS due to missing IPV6_V6ONLY. Closes #1212. Client library fixes - Add missing `mosquitto_userdata()` function. Client fixes: - mosquitto_pub wouldn't always publish all messages when using `-l` and QoS>0. This has been fixed. - mosquitto_sub was incorrectly encoding special characters when using %j output format. Closes #1220. 1.5.8 - 20190228 ================ Broker: - Fix clients being disconnected when ACLs are in use. This only affects the case where a client connects using a username, and the anonymous ACL list is defined but specific user ACLs are not defined. Closes #1162. - Make error messages for missing config file clearer. - Fix some Coverity Scan reported errors that could occur when the broker was already failing to start. - Fix broken mosquitto_passwd on FreeBSD. Closes #1032. - Fix delayed bridge local subscriptions causing missing messages. Closes #1174. Library: - Use higher resolution timer for random initialisation of client id generation. Closes #1177. - Fix some Coverity Scan reported errors that could occur when the library was already quitting. 1.5.7 - 20190213 ================ Broker: - Fix build failure when using WITH_ADNS=yes - Ensure that an error occurs if `per_listener_settings true` is given after other security options. Closes #1149. - Fix include_dir not sorting config files before loading. This was partially fixed in 1.5 previously. - Improve documentation around the `include_dir` option. Closes #1154. - Fix case where old unreferenced msg_store messages were being saved to the persistence file, bloating its size unnecessarily. Closes #389. Library: - Fix `mosquitto_topic_matches_sub()` not returning MOSQ_ERR_INVAL for invalid subscriptions like `topic/#abc`. This only affects the return value, not the match/no match result, which was already correct. Build: - Don't require C99 compiler. - Add rewritten build test script and remove some build warnings. 1.5.6 - 20190206 ================ Security: - CVE-2018-12551: If Mosquitto is configured to use a password file for authentication, any malformed data in the password file will be treated as valid. This typically means that the malformed data becomes a username and no password. If this occurs, clients can circumvent authentication and get access to the broker by using the malformed username. In particular, a blank line will be treated as a valid empty username. Other security measures are unaffected. Users who have only used the mosquitto_passwd utility to create and modify their password files are unaffected by this vulnerability. Affects version 1.0 to 1.5.5 inclusive. - CVE-2018-12550: If an ACL file is empty, or has only blank lines or comments, then mosquitto treats the ACL file as not being defined, which means that no topic access is denied. Although denying access to all topics is not a useful configuration, this behaviour is unexpected and could lead to access being incorrectly granted in some circumstances. This is now fixed. Affects versions 1.0 to 1.5.5 inclusive. - CVE-2018-12546. If a client publishes a retained message to a topic that they have access to, and then their access to that topic is revoked, the retained message will still be delivered to future subscribers. This behaviour may be undesirable in some applications, so a configuration option `check_retain_source` has been introduced to enforce checking of the retained message source on publish. Broker: - Fixed comment handling for config options that have optional arguments. - Improved documentation around bridge topic remapping. - Handle mismatched handshakes (e.g. QoS1 PUBLISH with QoS2 reply) properly. - Fix spaces not being allowed in the bridge remote_username option. Closes #1131. - Allow broker to always restart on Windows when using `log_dest file`. Closes #1080. - Fix Will not being sent for Websockets clients. Closes #1143. - Windows: Fix possible crash when client disconnects. Closes #1137. - Fixed durable clients being unable to receive messages when offline, when per_listener_settings was set to true. Closes #1081. - Add log message for the case where a client is disconnected for sending a topic with invalid UTF-8. Closes #1144. Library: - Fix TLS connections not working over SOCKS. - Don't clear SSL context when TLS connection is closed, meaning if a user provided an external SSL_CTX they have less chance of leaking references. Build: - Fix comparison of boolean values in CMake build. Closes #1101. - Fix compilation when openssl deprecated APIs are not available. Closes #1094. - Man pages can now be built on any system. Closes #1139. 1.5.5 - 20181211 ================ Security: - If `per_listener_settings` is set to true, then the `acl_file` setting was ignored for the "default listener" only. This has been fixed. This does not affect any listeners defined with the `listener` option. Closes #1073. This is now tracked as CVE-2018-20145. Broker: - Add `socket_domain` option to allow listeners to disable IPv6 support. This is required to work around a problem in libwebsockets that means sockets only listen on IPv6 by default if IPv6 support is compiled in. Closes #1004. - When using ADNS, don't ask for all network protocols when connecting, because this can lead to confusing "Protocol not supported" errors if the network is down. Closes #1062. - Fix outgoing retained messages not being sent by bridges on initial connection. Closes #1040. - Don't reload auth_opt_ options on reload, to match the behaviour of the other plugin options. Closes #1068. - Print message on error when installing/uninstalling as a Windows service. - All non-error connect/disconnect messages are controlled by the `connection_messages` option. Closes #772. Closes #613. Closes #537. Library: - Fix reconnect delay backoff behaviour. Closes #1027. - Don't call on_disconnect() twice if keepalive tests fail. Closes #1067. Client: - Always print leading zeros in mosquitto_sub when output format is hex. Closes #1066. Build: - Fix building where TLS-PSK is not available. Closes #68. 1.5.4 - 20181108 ================ Security: - When using a TLS enabled websockets listener with "require_certificate" enabled, the mosquitto broker does not correctly verify client certificates. This is now fixed. All other security measures operate as expected, and in particular non-websockets listeners are not affected by this. Closes #996. Broker: - Process all pending messages even when a client has disconnected. This means a client that send a PUBLISH then DISCONNECT quickly, then disconnects will have its DISCONNECT message processed properly and so no Will will be sent. Closes #7. - $SYS/broker/clients/disconnected should never be negative. Closes #287. - Give better error message if a client sends a password without a username. Closes #1015. - Fix bridge not honoring restart_timeout. Closes #1019. - Don't disconnect a client if an auth plugin denies access to SUBSCRIBE. Closes #1016. Library: - Fix memory leak that occurred if mosquitto_reconnect() was used when TLS errors were present. Closes #592. - Fix TLS connections when using an external event loop with mosquitto_loop_read() and mosquitto_write(). Closes #990. Build: - Fix clients not being compiled with threading support when using CMake. Closes #983. - Header fixes for FreeBSD. Closes #977. - Use _GNU_SOURCE to fix build errors in websockets and getaddrinfo usage. Closes #862 and #933. - Fix builds on QNX 7.0.0. Closes #1018. 1.5.3 - 20180925 ================ Security: - Fix CVE-2018-12543. If a message is sent to Mosquitto with a topic that begins with $, but is not $SYS, then an assert that should be unreachable is triggered and Mosquitto will exit. Broker: - Elevate log level to warning for situation when socket limit is hit. - Remove requirement to use `user root` in snap package config files. - Fix retained messages not sent by bridges on outgoing topics at the first connection. Closes #701. - Documentation fixes. Closes #520, #600. - Fix duplicate clients being added to by_id hash before the old client was removed. Closes #645. - Fix Windows version not starting if include_dir did not contain any files. Closes #566. - When an authentication plugin denied access to a SUBSCRIBE, the client would be disconnected incorrectly. This has been fixed. Closes #1016. Build: - Various fixes to ease building. 1.5.2 - 20180919 ================ Broker: - Fix build when using WITH_ADNS=yes. - Fix incorrect call to setsockopt() for TCP_NODELAY. Closes #941. - Fix excessive CPU usage when the number of sockets exceeds the system limit. Closes #948. - Fix for bridge connections when using WITH_ADNS=yes. - Fix round_robin false behaviour. Closes #481. - Fix segfault on HUP when bridges and security options are configured. Closes #965. Library: - Fix situation where username and password is used with SOCKS5 proxy. Closes #927. - Fix SOCKS5 behaviour when passing IP addresses. Closes #927. Build: - Make it easier to build without bundled uthash.h using "WITH_BUNDLED_DEPS=no". - Fix build with OPENSSL_NO_ENGINE. Closes #932. 1.5.1 - 20180816 ================ Broker: - Fix plugin cleanup function not being called on exit of the broker. Closes #900. - Print more OpenSSL errors when loading certificates/keys fail. - Use AF_UNSPEC etc. instead of PF_UNSPEC to comply with POSIX. Closes #863. - Remove use of AI_ADDRCONFIG, which means the broker can be used on systems where only the loopback interface is defined. Closes #869, Closes #901. - Fix IPv6 addresses not being able to be used as bridge addresses. Closes #886. - All clients now time out if they exceed their keepalive*1.5, rather than just reach it. This was inconsistent in two places. - Fix segfault on startup if bridge CA certificates could not be read. Closes #851. - Fix problem opening listeners on Pi caused by unsigned char being default. Found via #849. - ACL patterns that do not contain either %c or %u now produce a warning in the log. Closes #209. - Fix bridge publishing failing when per_listener_settings was true. Closes #860. - Fix `use_identity_as_username true` not working. Closes #833. - Fix UNSUBACK messages not being logged. Closes #903. - Fix possible endian issue when reading the `memory_limit` option. - Fix building for libwebsockets < 1.6. - Fix accessor functions for username and client id when used in plugin auth check. Library: - Fix some places where return codes were incorrect, including to the on_disconnect() callback. This has resulted in two new error codes, MOSQ_ERR_KEEPALIVE and MOSQ_ERR_LOOKUP. - Fix connection problems when mosquitto_loop_start() was called before mosquitto_connect_async(). Closes #848. Clients: - When compiled using WITH_TLS=no, the default port was incorrectly being set to -1. This has been fixed. - Fix compiling on Mac OS X <10.12. Closes #813 and #240. Build: - Fixes for building on NetBSD. Closes #258. - Fixes for building on FreeBSD. - Add support for compiling with static libwebsockets library. 1.5 - 20180502 ============== Security: - Fix memory leak that could be caused by a malicious CONNECT packet. This does not yet have a CVE assigned. Closes #533493 (on Eclipse bugtracker) Broker features: - Add per_listener_settings to allow authentication and access control to be per listener. - Add limited support for reloading listener settings. This allows settings for an already defined listener to be reloaded, but port numbers must not be changed. - Add ability to deny access to SUBSCRIBE messages as well as the current read/write accesses. Currently for auth plugins only. - Reduce calls to malloc through the use of UHPA. - Outgoing messages with QoS>1 are no longer retried after a timeout period. Messages will be retried when a client reconnects. This change in behaviour can be justified by considering when the timeout may have occurred. * If a connection is unreliable and has dropped, but without one end noticing, the messages will be retried on reconnection. Sending additional PUBLISH or PUBREL would not have changed anything. * If a client is overloaded/unable to respond/has a slow connection then sending additional PUBLISH or PUBREL would not help the client catch up. Once the backlog has cleared the client will respond. If it is not able to catch up, sending additional duplicates would not help either. - Add use_subject_as_username option for certificate based client authentication to use the entire certificate subject as a username, rather than just the CN. Closes #469467. - Change sys tree printing output. This format shouldn't be relied upon and may change at any time. Closes #470246. - Minimum supported libwebsockets version is now 1.3. - Add systemd startup notification and services. Closes #471053. - Reduce unnecessary malloc and memcpy when receiving a message and storing it. Closes #470258. - Support for Windows XP has been dropped. - Bridge connections now default to using MQTT v3.1.1. - mosquitto_db_dump tool can now output some stats on clients. - Perform utf-8 validation on incoming will, subscription and unsubscription topics. - new $SYS/broker/store/messages/count (deprecates $SYS/broker/messages/stored) - new $SYS/broker/store/messages/bytes - max_queued_bytes feature to limit queues by real size rather than than just message count. Closes Eclipse #452919 or Github #100 - Add support for bridges to be configured to only send notifications to the local broker. - Add set_tcp_nodelay option to allow Nagle's algorithm to be disabled on client sockets. Closes #433. - The behaviour of allow_anonymous has changed. In the old behaviour, the default if not set was to allow anonymous access. The new behaviour is to default is to allow anonymous access unless another security option is set. For example, if password_file is set and allow_anonymous is not set, then anonymous access will be denied. It is still possible to allow anonymous access by setting it explicitly. Broker fixes: - Fix UNSUBSCRIBE with no topic is accepted on MQTT 3.1.1. Closes #665. - Produce an error if two bridges share the same local_clientid. - Miscellaneous fixes on Windows. - queue_qos0_messages was not observing max_queued_** limits - When using the include_dir configuration option sort the files alphabetically before loading them. Closes #17. - IPv6 is no longer disabled for websockets listeners. - Remove all build timestamp information including $SYS/broker/timestamp. Close #651. - Correctly handle incoming strings that contain a NULL byte. Closes #693. - Use constant time memcmp for password comparisons. - Fix incorrect PSK key being used if it had leading zeroes. - Fix memory leak if a client provided a username/password for a listener with use_identity_as_username configured. - Fix use_identity_as_username not working on websockets clients. - Don't crash if an auth plugin returns MOSQ_ERR_AUTH for a username check on a websockets client. Closes #490. - Fix 08-ssl-bridge.py test when using async dns lookups. Closes #507. - Lines in the config file are no longer limited to 1024 characters long. Closes #652. - Fix $SYS counters of messages and bytes sent when message is sent over a Websockets. Closes #250. - Fix upgrade_outgoing_qos for retained message. Closes #534. - Fix CONNACK message not being sent for unauthorised connect on websockets. Closes #8. - Maximum connections on Windows increased to 2048. - When a client with an in-use client-id connects, if the old client has a will, send the will message. Closes #26. - Fix parsing of configuration options that end with a space. Closes #804. Client library features: - Outgoing messages with QoS>1 are no longer retried after a timeout period. Messages will be retried when a client reconnects. - DNS-SRV support is now disabled by default. - Add mosquitto_subscribe_simple() This is a helper function to make retrieving messages from a broker very straightforward. Examples of its use are in examples/subscribe_simple. - Add mosquitto_subscribe_callback() This is a helper function to make processing messages from a broker very straightforward. An example of its use is in examples/subscribe_simple. - Connections now default to using MQTT v3.1.1. - Add mosquitto_validate_utf8() to check whether a string is valid UTF-8 according to the UTF-8 spec and to the additional restrictions imposed by the MQTT spec. - Topic inputs are checked for UTF-8 validity. - Add mosquitto_userdata function to allow retrieving the client userdata member variable. Closes #111. - Add mosquitto_pub_topic_check2(), mosquitto_sub_topic_check2(), and mosquitto_topic_matches_sub2() which are identical to the similarly named functions but also take length arguments. - Add mosquitto_connect_with_flags_callback_set(), which allows a second connect callback to be used which also exposes the connect flags parameter. Closes #738 and #128. - Add MOSQ_OPT_SSL_CTX option to allow a user specified SSL_CTX to be used instead of the one generated by libmosquitto. This allows greater control over what options can be set. Closes #715. - Add MOSQ_OPT_SSL_CTX_WITH_DEFAULTS to work with MOSQ_OPT_SSL_CTX and have the default libmosquitto SSL_CTX configuration applied to the user provided SSL_CTX. Closes #567. Client library fixes: - Fix incorrect PSK key being used if it had leading zeroes. - Initialise "result" variable as soon as possible in mosquitto_topic_matches_sub. Closes #654. - No need to close socket again if setting non-blocking failed. Closes #649. - Fix mosquitto_topic_matches_sub() not correctly matching foo/bar against foo/+/#. Closes #670. - SNI host support added. Client features: - Add -F to mosquitto_sub to allow the user to choose the output format. - Add -U to mosquitto_sub for unsubscribing from topics. - Add -c (clean session) to mosquitto_pub. - Add --retained-only to mosquitto_sub to exit after receiving all retained messages. - Add -W to allow mosquitto_sub to stop processing incoming messages after a timeout. - Connections now default to using MQTT v3.1.1. - Default to using port 8883 when using TLS. - mosquitto_sub doesn't continue to keep connecting if CONNACK tells it the connection was refused. Client fixes: - Correctly handle empty files with "mosquitto_pub -l". Closes #676. Build: - Add WITH_STRIP option (defaulting to "no") that when set to "yes" will strip executables and shared libraries when installing. - Add WITH_STATIC_LIBRARIES (defaulting to "no") that when set to "yes" will build and install static versions of the client libraries. - Don't run TLS-PSK tests if TLS-PSK disabled at compile time. Closes #636. - Support for openssl versions 1.0.0 and 1.0.1 has been removed as these are no longer supported by openssl. Documentation: - Replace mentions of deprecated 'c_rehash' with 'openssl rehash'. 1.4.15 - 20180228 ================= Security: - Fix CVE-2017-7652. If a SIGHUP is sent to the broker when there are no more file descriptors, then opening the configuration file will fail and security settings will be set back to their default values. - Fix CVE-2017-7651. Unauthenticated clients can cause excessive memory use by setting "remaining length" to be a large value. This is now mitigated by limiting the size of remaining length to valid values. A "memory_limit" configuration option has also been added to allow the overall memory used by the broker to be limited. Broker: - Use constant time memcmp for password comparisons. - Fix incorrect PSK key being used if it had leading zeroes. - Fix memory leak if a client provided a username/password for a listener with use_identity_as_username configured. - Fix use_identity_as_username not working on websockets clients. - Don't crash if an auth plugin returns MOSQ_ERR_AUTH for a username check on a websockets client. Closes #490. - Fix 08-ssl-bridge.py test when using async dns lookups. Closes #507. - Lines in the config file are no longer limited to 1024 characters long. Closes #652. - Fix $SYS counters of messages and bytes sent when message is sent over a Websockets. Closes #250. - Fix upgrade_outgoing_qos for retained message. Closes #534. - Fix CONNACK message not being sent for unauthorised connect on websockets. Closes #8. Client library: - Fix incorrect PSK key being used if it had leading zeroes. - Initialise "result" variable as soon as possible in mosquitto_topic_matches_sub. Closes #654. - No need to close socket again if setting non-blocking failed. Closes #649. - Fix mosquitto_topic_matches_sub() not correctly matching foo/bar against foo/+/#. Closes #670. Clients: - Correctly handle empty files with "mosquitto_pub -l". Closes #676. Build: - Don't run TLS-PSK tests if TLS-PSK disabled at compile time. Closes #636. 1.4.14 - 20170710 ================= Broker: - Fix regression from 1.4.13 where persistence data was not being saved. 1.4.13 - 20170627 ================= Security: - Fix CVE-2017-9868. The persistence file was readable by all local users, potentially allowing sensitive information to be leaked. This can also be fixed administratively, by restricting access to the directory in which the persistence file is stored. Broker: - Fix for poor websockets performance. - Fix lazy bridges not timing out for idle_timeout. Closes #417. - Fix problems with large retained messages over websockets. Closes #427. - Set persistence file to only be readable by owner, except on Windows. Closes #468. - Fix CONNECT check for reserved=0, as per MQTT v3.1.1 check MQTT-3.1.2-3. - When the broker stop, wills for any connected clients are now "sent". Closes #477. - Auth plugins can be configured to disable the check for +# in usernames/client ids with the auth_plugin_deny_special_chars option. Partially closes #462. - Restrictions for CVE-2017-7650 have been relaxed - '/' is allowed in usernames/client ids. Remainder of fix for #462. Clients: - Don't use / in auto-generated client ids. 1.4.12 - 20170528 ================= Security: - Fix CVE-2017-7650, which allows clients with username or client id set to '#' or '+' to bypass pattern based ACLs or third party plugins. The fix denies message sending or receiving of messages for clients with a '#' or '+' in their username or client id and if the message is subject to a pattern ACL check or plugin check. Patches for other versions are available at https://mosquitto.org/files/cve/2017-7650/ Broker: - Fix mosquitto.db from becoming corrupted due to client messages being persisted with no stored message. Closes #424. - Fix bridge not restarting properly. Closes #428. - Fix unitialized memory in gets_quiet on Windows. Closes #426. - Fix building with WITH_ADNS=no for systems that don't use glibc. Closes #415. - Fixes to readme.md. - Fix deprecation warning for OpenSSL 1.1. PR #416. - Don't segfault on duplicate bridge names. Closes #446. - Fix CVE-2017-7650. 1.4.11 - 20170220 ================= Broker: - Fix crash when "lazy" type bridge attempts to reconnect. Closes #259. - maximum_connections now applies to websockets listeners. Closes #271. - Allow bridges to use TLS with IPv6. - Don't error on zero length persistence files. Closes #316. - For http only websockets clients, close files served over http in all cases when the client disconnects. Closes #354. - Fix error message when websockets http_dir directory does not exist. - Improve password utility error message. Closes #379. Clients: - Use of --ciphers no longer requires you to also pass --tls-version. Closes #380. Client library: - Clients can now use TLS with IPv6. - Fix potential socket leakage when reconnecting. Closes #304. - Fix potential negative timeout being passed to pselect. Closes #329. 1.4.10 - 20160816 ================= Broker: - Fix TLS operation with websockets listeners and libwebsockts 2.x. Closes #186. - Don't disconnect client on HUP before reading the pending data. Closes #7. - Fix some $SYS messages being incorrectly persisted. Closes #191. - Support OpenSSL 1.1.0. - Call fsync after persisting data to ensure it is correctly written. Closes #189. - Fix persistence saving of subscription QoS on big-endian machines. - Fix will retained flag handling on Windows. Closes #222. - Broker now displays an error if it is unable to open the log file. Closes #234. Client library: - Support OpenSSL 1.1.0. - Fixed the C++ library not allowing SOCKS support to be used. Closes #198. - Fix memory leak when verifying a server certificate with a subjectAltName section. Closes #237. Build: - Don't attempt to install docs when WITH_DOCS=no. Closes #184. 1.4.9 - 20160603 ================ Broker: - Ensure websockets clients that previously connected with clean session set to false have their queued messages delivered immediately on reconnecting. Closes #476314. - Reconnecting client with clean session set to false doesn't start with mid=1 again. - Will topic isn't truncated by one byte when using a mount_point any more. - Network errors are printed correctly on Windows. - Fix incorrect $SYS heap memory reporting when using ACLs. - Bridge config parameters couldn't contain a space, this has been fixed. Closes #150. - Fix saving of persistence messages that start with a '/'. Closes #151. - Fix reconnecting for bridges that use TLS on Windows. Closes #154. - Broker and bridges can now cope with unknown incoming PUBACK, PUBREC, PUBREL, PUBCOMP without disconnecting. Closes #57. - Fix websockets listeners not being able to bind to an IP address. Closes #170. - mosquitto_passwd utility now correctly deals with unknown command line arguments in all cases. Closes #169. - Fix publishing of $SYS/broker/clients/maximum - Fix order of #includes in lib/send_mosq.c to ensure struct mosquitto doesn't differ between source files when websockets is being used. Closes #180. - Fix possible rare crash when writing out persistence file and a client has incomplete messages inflight that it has been denied the right to publish. Client library: - Fix the case where a message received just before the keepalive timer expired would cause the client to miss the keepalive timer. - Return value of pthread_create is now checked. - _mosquitto_destroy should not cancel threads that weren't created by libmosquitto. Closes #166. - Clients can now cope with unknown incoming PUBACK, PUBREC, PUBREL, PUBCOMP without disconnecting. Closes #57. - Fix mosquitto_topic_matches_sub() reporting matches on some invalid subscriptions. Clients: - Handle some unchecked malloc() calls. Closes #1. Build: - Fix string quoting in CMakeLists.txt. Closes #4. - Fix building on Visual Studio 2015. Closes #136. 1.4.8 - 20160214 ================ Broker: - Wills published by clients connected to a listener with mount_point defined now correctly obey the mount point. This was a potential security risk because it allowed clients to publish messages outside of their restricted mount point. This is only affects brokers where the mount_point option is in use. Closes #487178. - Fix detection of broken connections on Windows. Closes #485143. - Close stdin etc. when daemonised. Closes #485589. - Fix incorrect detection of FreeBSD and OpenBSD. Closes #485131. Client library: - mosq->want_write should be cleared immediately before a call to SSL_write, to allow clients using mosquitto_want_write() to get accurate results. 1.4.7 - 20151221 ================ Broker: - Fix support for libwebsockets 1.22. 1.4.6 - 20151220 ================ Broker: - Add support for libwebsockets 1.6. Client library: - Fix _mosquitto_socketpair() on Windows, reducing the chance of delays when publishing. Closes #483979. Clients: - Fix "mosquitto_pub -l" stripping the final character on a line. Closes #483981. 1.4.5 - 20151108 ================ Broker: - Fix possible memory leak if bridge using SSL attempts to connect to a host that is not up. - Free unused topic tree elements (fix in 1.4.3 was incomplete). Closes #468987. Clients: - "mosquitto_pub -l" now no longer limited to 1024 byte lines. Closes #478917. 1.4.4 - 20150916 ================ Broker: - Don't leak sockets when outgoing bridge with multiple addresses cannot connect. Closes #477571. - Fix cross compiling of websockets. Closes #475807. - Fix memory free related crashes on openwrt. Closes #475707. - Fix excessive calls to message retry check. 1.4.3 - 20150818 ================ Broker: - Fix incorrect bridge notification on initial connection. Closes #467096. - Build fixes for OpenBSD. - Fix incorrect behaviour for autosave_interval, most noticable for autosave_interval=1. Closes #465438. - Fix handling of outgoing QoS>0 messages for bridges that could not be sent because the bridge connection was down. - Free unused topic tree elements. Closes #468987. - Fix some potential memory leaks. Closes #470253. - Fix potential crash on libwebsockets error. Client library: - Add missing error strings to mosquitto_strerror. - Handle fragmented TLS packets without a delay. Closes #470660. - Fix incorrect loop timeout being chosen when using threaded interface and keepalive = 0. Closes #471334. - Increment inflight messages count correctly. Closes #474935. Clients: - Report error string on connection failure rather than error code. 1.4.2 - 20150507 ================ Broker: - Fix bridge prefixes only working for the first outgoing message. Closes #464437. - Fix incorrect bridge connection notifications on local broker. - Fix persistent db writing on Windows. Closes #464779. - ACLs are now checked before sending a will message. - Fix possible crash when using bridges on Windows. Closes #465384. - Fix parsing of auth_opt_ arguments with extra spaces/tabs. - Broker will return CONNACK rc=5 when a username/password is not authorised. This was being incorrectly set as rc=4. - Fix handling of payload lengths>4096 with websockets. Client library: - Inflight message count wasn't being decreased for outgoing messages using QoS 2, meaning that only up to 20 QoS 2 messages could be sent. This has been fixed. Closes #464436. - Fix CMake dependencies for C++ wrapper building. Closes #463884. - Fix possibility of select() being called with a socket that is >FD_SETSIZE. This is a fix for #464632 that will be followed up by removing the select() call in a future version. - Fix calls to mosquitto_connect*_async() not completing. 1.4.1 - 20150403 ================ Broker: - Fix possible crash under heavy network load. Closes #463241. - Fix possible crash when using pattern ACLs. - Fix problems parsing config strings with multiple leading spaces. Closes #462154. - Websockets clients are now periodically disconnected if they have not maintained their keepalive timer. Closes #461619. - Fix possible minor memory leak on acl parsing. Client library: - Inflight limits should only apply to outgoing messages. Closes #461620. - Fix reconnect bug on Windows. Closes #463000. - Return -1 on error from mosquitto_socket(). Closes #461705. - Fix crash on multiple calls to mosquitto_lib_init/mosquitto_lib_cleanup. Closes #462780. - Allow longer paths on Windows. Closes #462781. - Make _mosquitto_mid_generate() thread safe. Closes #463479. 1.4 - 20150218 ============== Important changes: - Websockets support in the broker. - Bridge behaviour on the local broker has changed due to the introduction of the local_* options. This may affect you if you are using authentication and/or ACLs with bridges. - The default TLS behaviour has changed to accept all of TLS v1.2, v1.1 and v1.0, rather than only only one version of the protocol. It is still possible to restrict a listener to a single version of TLS. - The Python client has been removed now that the Eclipse Paho Python client has had a release. - When a durable client reconnects, its queued messages are now checked against ACLs in case of a change in username/ACL state since it last connected. - New use_username_as_clientid option on the broker, for preventing hijacking of a client id. - The client library and clients now have experimental SOCKS5 support. - Wildcard TLS certificates are now supported for bridges and clients. - The clients have support for config files with default options. - Client and client libraries have support for MQTT v3.1.1. - Bridge support for MQTT v3.1.1. Broker: - Websockets support in the broker. - Add local_clientid, local_username, local_password for bridge connections to authenticate to the local broker. - Default TLS mode now accepts TLS v1.2, v1.1 and v1.0. - Support for ECDHE-ECDSA family ciphers. - Fix bug #1324411, which could have had unexpected consequences for delayed messages in rare circumstances. - Add support for "session present" in CONNACK messages for MQTT v3.1.1. - Remove strict protocol #ifdefs. - Change $SYS/broker/clients/active -> $SYS/broker/clients/connected - Change $SYS/broker/clients/inactive -> $SYS/broker/clients/disconnected - When a durable client reconnects, its queued messages are now checked against ACLs in case of a change in username/ACL state since it last connected. - libuuid is used to generate client ids, where it is available, when an MQTT v3.1.1 client connects with a zero length client id. - Anonymous clients are no longer accidently disconnected from the broker after a SIGHUP. - mosquitto_passwd now supports -b (batch mode) to allow the password to be provided at the command line. - Removed $SYS/broker/changeset. This was intended for use with debugging, but in practice is of no use. - Add support for use_username_as_clientid which can be used with authentication to restrict ownership of client ids and hence prevent one client disconnecting another by using the same client id. - When "require_certificate" was false, the broker was incorrectly asking for a certificate (but not checking it). This caused problems with some clients and has been fixed so the broker no longer asks. - When using syslog logging on non-Windows OSs, it is now possible to specify the logging facility to one of local0-7 instead of the default "daemon". - The bridge_attempt_unsubscribe option has been added, to allow the sending of UNSUBSCRIBE requests to be disabled for topics with "out" direction. Closes bug #456899. - Wildcard TLS certificates are now supported for bridges. - Support for "hour" client expiration lengths for the persistent_client_expiration option. Closes bug #425835. - Bridge support for MQTT v3.1.1. - Root privileges are now dropped after starting listeners and loading certificates/private keys, to allow private keys to have their permissions restricted to the root user only. Closes bug #452914. - Usernames and topics given in ACL files can now include a space. Closes bug #431780. - Fix hang if pattern acl contains a %u but an anonymous client connect. Closes bug #455402. - Fix man page installation with cmake. Closes bug #458843. - When using "log_dest file" the output file is now flushed periodically. Clients: - Both clients can now load default configuration options from a file. - Add -C option to mosquitto_sub to allow the client to quit after receiving a certain count of messages. Closes bug #453850. - Add --proxy SOCKS5 support for both clients. - Pub client supports setting its keepalive. Closes bug #454852. - Add support for config files with default options. - Add support for MQTT v3.1.1. Client library: - Add experimental SOCKS5 support. - mosquitto_loop_forever now quits after a fatal error, rather than blindly retrying. - SRV support is now not compiled in by default. - Wildcard TLS certificates are now supported. - mosquittopp now has a virtual destructor. Closes bug #452915. - Add support for MQTT v3.1.1. - Don't quit mosquitto_loop_forever() if broker not available on first connect. Closes bug #453293, but requires more work. 1.3.5 - 20141008 ================ Broker: - Fix possible memory leak when using a topic that has a leading slash. Fixes bug #1360985. - Fix saving persistent database on Windows. - Temporarily disable ACL checks on subscriptions when using MQTT v3.1.1. This is due to the complexity of checking wildcard ACLs against wildcard subscriptions. This does not have a negative impact on security because checks are still made before a message is sent to a client. Fixes bug #1374291. - When using -v and the broker receives a SIGHUP, verbose logging was being disabled. This has been fixed. Client library: - Fix mutex being incorrectly passed by value. Fixes bug #1373785. 1.3.4 - 20140806 ================ Broker: - Don't ask client for certificate when require_certificate is false. - Backout incomplete functionality that was incorrectly included in 1.3.2. 1.3.3 - 20140801 ================ Broker: - Fix incorrect handling of anonymous bridges on the local broker. 1.3.2 - 20140713 ================ Broker: - Don't allow access to clients when authenticating if a security plugin returns an application error. Fixes bug #1340782. - Ensure that bridges verify certificates by default when using TLS. - Fix possible crash when using pattern ACLs that do not include a %u and clients that connect without a username. - Fix subscriptions being deleted when clients subscribed to a topic beginning with a $ but that is not $SYS. - When a durable client reconnects, its queued messages are now checked against ACLs in case of a change in username/ACL state since it last connected. - Fix bug #1324411, which could have had unexpected consequences for delayed messages in rare circumstances. - Anonymous clients are no longer accidently disconnected from the broker after a SIGHUP. Client library: - Fix topic matching edge case. - Fix callback deadlocks after calling mosquitto_disconnect(), when using the threaded interfaces. Closes bug #1313725. - Fix SRV support when building with CMake. - Remove strict protocol #ifdefs. General: - Use $(STRIP) for stripping binaries when installing, to allow easier cross compilation. 1.3.1 - 20140324 ================ Broker: - Prevent possible crash on client reconnect. Closes bug #1294108. - Don't accept zero length unsubscription strings (MQTT v3.1.1 fix) - Don't accept QoS 3 (MQTT v3.1.1 fix) - Don't disconnect clients immediately on HUP to give chance for all data to be read. - Reject invalid un/subscriptions e.g. foo/+bar #/bar. - Take more care not to disconnect clients that are sending large messages. Client library: - Fix socketpair code on the Mac. - Fix compilation for WITH_THREADING=no. - Break out of select() when calling mosquitto_loop_stop(). - Reject invalid un/subscriptions e.g. foo/+bar #/bar. - Add mosquitto_threaded_set(). Clients: - Fix keepalive value on mosquitto_pub. - Fix possibility of mosquitto_pub not exiting after sending messages when using -l. 1.3 - 20140316 ============== Broker: - The broker no longer ignores the auth_plugin_init() return value. - Accept SSLv2/SSLv3 HELLOs when using TLSv1, whilst keeping SSLv2 and SSLv3 disabled. This increases client compatibility without sacrificing security. - The $SYS tree can now be disabled at runtime as well as at compile time. - When remapping bridged topics, only check for matches when the message direction is correct. This allows two identical topics to be remapped differently for both in and out. - Change "$SYS/broker/heap/current size" to "$SYS/broker/heap/current" for easier parsing. - Change "$SYS/broker/heap/maximum size" to "$SYS/broker/heap/maximum" for easier parsing. - Topics are no longer normalised from e.g a///topic to a/topic. This matches the behaviour as clarified by the Oasis MQTT spec. This will lead to unexpected behaviour if you were using topics of this form. - Log when outgoing messages for a client begin to drop off the end of the queue. - Bridge clients are recognised as bridges even after reloading from persistence. - Basic support for MQTT v3.1.1. This does not include being able to bridge to an MQTT v3.1.1 broker. - Username is displayed in log if present when a client connects. - Support for 0 length client ids (v3.1.1 only) that result in automatically generated client ids on the broker (see option allow_zero_length_clientid). - Ability to set the prefix of automatically generated client ids (see option auto_id_prefix). - Add support for TLS session resumption. - When using TLS, the server now chooses the cipher to use when negotiating with the client. - Weak TLS ciphers are now disabled by default. Client library: - Fix support for Python 2.6, 3.0, 3.1. - Add support for un/subscribing to multiple topics at once in un/subscribe(). - Clients now close their socket after sending DISCONNECT. - Python client now contains its version number. - C library mosquitto_want_write() now supports TLS clients. - Fix possible memory leak in C/C++ library when communicating with a broker that doesn't follow the spec. - Return strerror() through mosquitto_strerror() to make error printing easier. - Topics are no longer normalised from e.g a///topic to a/topic. This matches the behaviour as clarified by the Oasis MQTT spec. This will lead to unexpected behaviour if you were using topics of this form. - Add support for SRV lookups. - Break out of select() on publish(), subscribe() etc. when using the threaded interface. Fixes bug #1270062. - Handle incoming and outgoing messages separately. Fixes bug #1263172. - Don't terminate threads on mosquitto_destroy() when a client is not using the threaded interface but does use their own thread. Fixes bug #1291473. Clients: - Add --ciphers to allow specifying which TLS ciphers to support. - Add support for SRV lookups. - Add -N to sub client to suppress printing of EOL after the payload. - Add -T to sub client to suppress printing of a topic hierarchy. 1.2.3 - 20131202 ================ Broker: - Don't always attempt to call read() for SSL clients, irrespective of whether they were ready to read or not. Reduces syscalls significantly. - Possible memory leak fixes. - Further fix for bug #1226040: multiple retained messages being delivered for subscriptions ending in #. - Fix bridge reconnections when using multiple bridge addresses. Client library: - Fix possible memory leak in C/C++ library when communicating with a broker that doesn't follow the spec. - Block in Python loop_stop() until all messages are sent, as the documentation states should happen. - Fix for asynchronous connections on Windows. Closes bug #1249202. - Module version is now available in mosquitto.py. Clients: - mosquitto_sub now uses fwrite() instead of printf() to output messages, so messages with NULL characters aren't truncated. 1.2.2 - 20131021 ================ Broker: - Fix compliance with max_inflight_messages when a non-clean session client reconnects. Closes one of the issues on bug #1237389. Client library: - Fix incorrect inflight message accounting, which caused messages to go unsent. Partial fix for bug #1237351. - Fix potential memory corruption when sending QoS>0 messages at a high rate using the threaded interface. Further fix for #1237351. - Fix incorrect delay scaling when exponential_backoff=true in mosquitto_reconnect_delay_set(). - Some pep8 fixes for Python. 1.2.1 - 20130918 ================ Broker: - The broker no longer ignores the auth_plugin_init() return value. Closes bug #1215084. - Use RTLD_GLOBAL when opening authentication plugins on posix systems. Fixes resolving of symbols in libraries used by authentication plugins. - Add/fix some config documentation. - Fix ACLs for topics with $SYS. - Clients loaded from the persistence file on startup were not being added to the client hash, causing subtle problems when the client reconnected, including ACLs failing. This has been fixed. - Add note to mosquitto-tls man page stating that certificates need to be unique. Closes bug #1221285. - Fix incorrect retained message delivery when using wildcard subs in some circumstances. Fixes bug #1226040. Client library: - Fix support for Python 2.6, 3.0, 3.1. - Fix TLS subjectAltName verification and segfaults. - Handle EAGAIN in Python on Windows. Closes bug #1220004. - Fix compilation when using WITH_TLS=no. - Don't fail reconnecting in Python when broker is temporarily unavailable. 1.2 - 20130708 ============== Broker: - Replace O(n) username lookup on CONNECT with a roughly O(1) hashtable version. - It is now possible to disable $SYS at compile time. - Add dropped publish messages to load tree in $SYS. Closes bug #1183318. - Add support for logging SUBSCRIBE/UNSUBSCRIBE events. - Add "log_dest file" logging support. - Auth plugin ACL check function now passes the client id as well as username and password. - The queue_qos0_messages option wasn't working correctly, this has now been fixed. Closes bug #1125200. - Don't drop all messages for disconnected durable clients when max_queued_messages=0. - Add support for "log_type all". - Add support for "-v" option on the command line to provide the equivalent of "log_type all" without needing a config file. - Add the "upgrade_outgoing_qos" option, a non-standard feature. - Persistence data is now written to a temporary file which is atomically renamed on completion, so a crash during writing will not produce a corrupt file. - mosquitto.conf is now installed as mosquitto.conf.example - Configuration file errors are now reported with filename and line number. - The broker now uses a monotonic clock if available, to avoid changes in time causing client disconnections or message retries. - Clean session and keepalive status are now display the log when a client connects. - Add support for TLSv1.2 and TLSv1.1. - Clients that connect with zero length will topics are now rejected. - Add the ability to set a maximum allowed PUBLISH payload size. - Fix an ACL with topic "#" incorrectly granting access to $SYS. - Fix retained messages incorrectly being set on wildcard topics, leading to duplicate retained messages being sent on subscription. Closes bug #1116233. - Don't discard listener values when no "port" option given. Closes bug #1131406. - Client password check was always failing when security was being reapplied after a config reload. This meant that all clients were being disconnected. This has been fixed. - Fix build when WITH_TLS=no. Closes bug #1174971. - Fix single outgoing packets not being sent in a timely fashion if they were not sent in one call to write(). Closes bug #1176796. - Fix remapping of messages for clients connected to a listener with mount_point set. Closes bug #1180765. - Fix duplicate retained messages being sent for some wildcard patterns. - If a client connects with a will topic to which they do not have write access, they are now disconnected with CONNACK "not authorised". - Fix retained messages on topic foo being incorrectly delivered to subscriptions of /# - Fix handling of SSL errors on SSL_accept(). - Fix handling of QoS 2 messages on client reconnect. - Drop privileges now sets supplementary groups correctly. - Fix load reporting interval (is now 60s). - Be strict with malformed PUBLISH packets - clients are now disconnected rather than the packet discarded. This goes inline with future OASIS spec changes and makes other changes more straightforward. - Process incoming messages denied by ACL properly so that clients don't keep resending them. - Add support for round_robin bridge option. - Add bridge support for verifying remote server certificate subject against the remote hostname. - Fix problem with out of order calls to free() when restarting a lazy bridge. - The broker now attempts to resolve bind_address and bridge addresses immediately when parsing the config file in order to detect invalid hosts. - Bridges now set their notification state before attempting to connect, so if they fail to connect the state can still be seen. - Fix bridge notification payload length - no need to send a null byte. - mosquitto_passwd utility now reports errors more clearly. - Fix "mosquitto_passwd -U". Client library: - Add support for TLSv1.2 and TLSv1.1, except for on the Python module. - Add support for verifying remote server certificate subject against the remote hostname. - Add mosquitto_reconnect_async() support and make asynchronous connections truely asynchronous rather than simply deferred. DNS lookups are still blocking, so asynchronous connections require an IP address instead of hostname. - Allow control of reconnection timeouts in mosquitto_loop_forever() and after mosquitto_loop_start() by using mosquitto_reconnect_delay_set(). - Fix building on Android NDK. - Re-raise unhandled errors in Python so as not to provide confusing error messages later on. - Python module supports IPv6 connections. - mosquitto_sub_topic_tokenise() was behaving incorrectly if the last topic hierarchy had only a single character. This has been fixed. Closes bug #1163348. - Fix possible crash after disconnects when using the threaded interface with TLS. - Allow build/install without Python. Closes bug #1174972. - Add support for binding connection to a local interface. - Implement maximum inflight messages handling. - Fix Python client not handling will_payload==None. - Fix potential memory leak when setting username/password. - Fix handling of QoS 2 messages on reconnect. - Improve handling of mosquitto_disconnect() with threaded mode. Clients: - Add support for TLSv1.2 and TLSv1.1. - Sub client can now suppress printing of messages with the retain bit set. - Add support for binding connection to a local interface. - Implement maximum inflight messages handling for the pub client. 1.1.3 - 20130211 ================ Broker: - mosquitto_passwd utility now uses tmpfile() to generate its temporary data storage file. It also creates a backup file that can be used to recover data if an errors occur. Other: - Build script fixes to help packaging on Debian. 1.1.2 - 20130130 ================ Client library: - Fix tls_cert_reqs not being set to SSL_VERIFY_PEER by default. This meant that clients were not verifying the server certificate when connecting over TLS. This affects the C, C++ and Python libraries. 1.1.1 - 20130116 ================ Broker: - Fix crash on reload if using acl patterns. Client library: - Fix static C++ functions not being exported on Windows. Fixes bug #1098256. 1.1 - 20121219 ============== Broker: - Add $SYS/broker/messages/dropped - Add $SYS/broker/clients/expired - Replace $SYS/broker/+/per second/+ with moving average versions published at $SYS/broker/load/# - Add $SYS/broker/load/sockets/+ and $SYS/broker/load/connections/+ - Documentation on password file format has been fixed. - Disable SSL compression. This reduces memory usage significantly and removes the possibility of CRIME type attacks. - Enable SSL_MODE_RELEASE_BUFFERS mode to reduce SSL memory usage further. - Add allow_duplicate_messages option. - ACL files can now have comment lines with # as the first character. - Display message on startup about which config is being loaded. - Fix max_inflight_messages and max_queued_messages not being applied. - Fix documentation error in mosquitto.conf. - Ensure that QoS 2 queued messages are sent out in a timely manner. - Local bridges now act on clean_session correctly. - Local bridges with clean_session==false now remove unused subscriptions on broker restart. - The $SYS/broker/heap/# messages now no longer include "bytes" as part of the string for ease of use. Client library: - Free memory used by OpenSSL in mosquitto_lib_cleanup() where possible. - Change WebSocket subprotocol name to mqttv3.1 to make future changes easier and for compatibility with other implementations. - mosquitto_loop_read() and mosquitto_loop_write() now handle errors themselves rather than having mosquitto_loop() handle their errors. This makes using them in a separate event loop more straightforward. - Add mosquitto_loop_forever() / loop_forever() function call to make simple clients easier. - Disable SSL compression. This reduces memory usage significantly and removes the possibility of CRIME type attacks. - Enable SSL_MODE_RELEASE_BUFFERS mode to reduce SSL memory usage further. - mosquitto_tls_set() will now return an error or raise an exception immediately if the CA certificate or client certificate/key cannot be accessed. - Fix potential memory leaks on connection failures. - Don't produce return error from mosquitto_loop() if a system call is interrupted. This prevents disconnects/reconnects in threaded mode and simplifies non-threaded client handling. - Ignore SIGPIPE to prevent unnecessary client quits in threaded mode. - Fix document error for mosquitto_message_retry_set(). - Fix mosquitto_topic_matches_sub() for subscriptions with + as the final character. Fixes bug #1085797. - Rename all "obj" parameters to "userdata" for consistency with other libraries. - Reset errno before network read/write to ensure EAGAIN isn't mistakenly returned. - The message queue length is now tracked and used to determine the maximum number of packets to process at once. This removes the need for the max_packets parameter which is now unused. - Fix incorrect error value in Python error_string() function. Fixes bug #1086777. - Reset last message in/out timer in Python module when we send a PINGREQ. Fixes too-early disconnects. Clients: - Clients now display their own version number and library version number in their help messages. - Fix "mosquitto_pub -l -q 2" disconnecting before all messages were transmitted. - Fix potential out-of-bounds array access with client ids. Fixes bug #1083182. Other: - mosquitto_passwd can now convert password files with plain text files to hashed versions. 1.0.5 - 20121103 ================ Broker: - Fix crash when the broker has use_identity_as_username set to true but a client connects without a certificate. - mosquitto_passwd should only be installed if WITH_TLS=yes. Library: - Use symbolic errno values rather than numbers in Python module to avoid cross platform issues (incorrect errno on Mac OS). Other: - Build script fixes for FreeBSD. 1.0.4 - 20121017 ================ Broker: - Deal with poll() POLLIN/POLLOUT before POLL[RD]HUP to correctly handle the case where a client sends data and immediately closes its socket. Library: - Fix memory leak with messages of QoS=2. Fixes bug #1064981. - Fix potential thread synchronisation problem with outgoing packets in the Python module. Fixes bug #1064977. Clients: - Fix "mosquitto_sub -l" incorrectly only sending one message per second. 1.0.3 - 20120927 ================ Broker: - Fix loading of psk files. - Don't return an error when reloading config if an ACL file isn't defined. This was preventing psk files being reloaded. - Clarify meaning of $SYS/broker/clients/total in mosquitto(8) man page. - Clarify meaning of $SYS/broker/messages/stored in mosquitto(8) man page. - Fix non-retained message delivery when subscribing to #. - Fix retained message delivery for subs to foo/# with retained messages at foo. - Include the filename in password/acl file loading errors. Library: - Fix possible AttributeError when self._sock == None in Python module. - Fix reconnecting after a timeout in Python module. - Fix reconnecting when there were outgoing packets in the queue in the Python module. - Fix problem with mutex initialisation causing crashes on some Windows installations. 1.0.2 - 20120919 ================ Broker: - If the broker was configured for persistence, a durable client had a subscription to topics in $SYS/# and had messages in its queue when the broker restarted, then the persistent database would have messages missing and so the broker would not restart properly. This has been fixed. Library: - Fix threading problem on some systems. Tests: - Close socket after 08-ssl-connect-no-auth-wrong-ca.py test to prevent subsequent tests having problems. Build scripts: - Install pskfile.example in CMake. Fixes bug #1037504. Other: - Fix db_dump parameter printing message store and sub chunks. 1.0.1 - 20120815 ================ Broker: - Fix default log_dest when running as a Windows service. Client library: - Fix incorrect parameters in Python on_log() callback call. Fixes bug #1036818. Clients: - Clients now don't display TLS/TLS-PSK usage help if they don't support it. Build scripts: - Fix TLS-PSK support in the CMake build files. - Fix man page installation in the CMake build files. - Fix SYSCONFDIR in cmake on *nix when installing to /usr. Fixes bug #1036908. Documentation: - Fix mqtt/MQTT capitalisation in man pages. - Update compiling.txt. - Fix incorrect callback docs in mosquitto.py. Fixes bug #1036607. - Fix various doc typos and remove obsolete script. Fixes bug #1037088. 1.0 - 20120814 ============== Broker: - Add SSL/TLS support. - Add TLS-PSK support, providing a simpler encryption method for constrained devices. - Passwords are now salted+hashed if compiled with WITH_TLS (recommended). - Add mosquitto_passwd for handling password files. - Add $SYS/broker/publish/messages/{sent|received} to show the number of PUBLISH messages sent/received. - Add $SYS/broker/publish/bytes/{sent|received} to show the number of PUBLISH bytes sent/received. - Add reload parameter for security init/cleanup functions. - Add option for expiring disconnected persistent clients. - Add option for queueing of QoS 0 messages when persistent clients are disconnected. - Enforce client id limits in the broker (only when WITH_STRICT_PROTOCOL is defined). - Fix reloading of log configuration. - Add support for try_private config option for bridge connections. - Add support for autosave_on_changes config option. - Add support for include_dir config option. - Add support for topic remapping. - Usernames were being lost when a non clean-session client reconnected, potentially causing problems with ACLs. This has been fixed. - Significant improvement to memory handling on Windows. - Bridges with outgoing topics will now set the retain flag correctly so that messages will be retained on the remote broker. - Incoming bridge connections are now detected by checking if bit 8 of the protocol version number is set. This requires support from the remote broker. - Add support for notification_topic option. - Add $SYS/broker/subscriptions/count and $SYS/broker/retained messages/count. - Add restart_timeout to control the amount of time an automatic bridge will wait before reconnecting. - Overlapping subscriptions are now handled properly. Fixes bug #928538. - Fix reloading of persistence_file and persistence_location. - Fix broker crash on incorrect protocol number. - Fix missing COMPAT_ECONNRESET define on Windows. - Clients that had disconnected were not always being detected immediately on Linux. This has been fixed. - Don't save $SYS messages to the on-disk persistent db. All $SYS messages should be reconstructed on a restart. This means bridge connection notifications will now be correct on a restart. - Fix reloading of bridge clients from the persistent db. This means that outgoing bridged topics should always work. - Local bridges are now no longer restricted by local ACLs. - Discard publish messages with zero length topics. - Drop to "mosquitto" user even if no config file specified. - Don't incorrectly allow topic access if ACL patterns but no normal ACL rules are defined. Client library: - Add SSL/TLS support. - Add TLS-PSK support, providing a simpler encryption method for constrained devices. - Add javascript/websockets client library. - Add "struct mosquitto *mosq" parameter for all callbacks in the client library. This is a binary incompatible change so the soversion of the libraries has been incremented. The new parameter should make it easier to use callbacks in practice. - Add mosquitto_want_write() for use when using own select() loop with mosquitto_socket(). - Add mosquitto_connect_async() to provide a non-blocking connect client call. - Add mosquitto_user_data_set() to allow user data pointer to be updated. - Add "int rc" parameter to disconnect callback to indicate whether disconnect was unexpected or the result of calling mosquitto_disconnect(). - Add mosquitto_strerror() for obtaining a string description of error numbers. - Add mosquitto_connack_string() for obtaining a string description of MQTT connection results. - Add mosquitto_will_clear() and change mosquitto_will_set() to only set the will. - Add mosquitto_sub_topic_tokenise() and mosquitto_sub_topic_tokens_free() utility functions to tokenise a subscription/topic string into a string array. - Add mosquitto_topic_matches_sub() to check whether a topic matches a subscription. - Replaced mosquitto_log_init() with mosquitto_log_callback_set() to allow clients to decide what to do with log messages. - Client will now disconnect itself from the broker if it doesn't receive a PINGRESP in the keepalive period after sending a PINGREQ. - Client will now send a PINGREQ if it has not received a message from the broker in keepalive seconds. - mosquitto_new() will now generate a random client id if the id parameter is NULL. - Added max_packets to mosquitto_loop(), mosquitto_loop_read() and mosquitto_loop_write() to control the maximum number of packets that are handled per call. - Payload parameters are now void * instead of uint8_t *. - The clean_session parameter has been moved from mosquitto_connect() to mosquitto_new() because it is a client parameter rather than a connection parameter. - Functions now use int instead of uint*_t where possible. - mosquitto_new() now sets errno to indicate failure type. - Return MOSQ_ERR_INVAL on zero length topic. - Fix automatic client id generation on Windows. - mosquitto_loop_misq() can now return MOSQ_ERR_NO_CONN. - Compile static library as well as dynamic library with default makefiles. - Rename C++ namespace from mosquittopp to mosqpp to remove ambiguity. - C++ lib_init(), lib_version() and lib_cleanup() are now in the mosqpp namespace directly, not mosquittopp class members. - The Python library is now written in pure Python and so no longer depends on libmosquitto. - The Python library includes SSL/TLS support. - The Python library should now be compatible with Python 3. Other: - Fix db_dump reading of retained messages. - Add example of logging all messages to mysql. - Add C++ client example. - Fix potential buffer overflow in pub/sub clients. - Add "make binary" target that doesn't make documents. - Add "--help" arguments to pub/sub clients. - Fix building on Solaris. 0.15 - 20120205 =============== - Add support for $SYS/broker/clients/maximum and $SYS/broker/clients/active topics. - Add support for $SYS messages/byte per second received/sent topics. - Updated mosquitto man page - $SYS hierarchy and signal support were out of date. - Auto generated pub/sub client ids now include the hostname. - Tool for dumping persistent DB contents is available in src/db_dump. It isn't installed by default. - Enforce topic length checks in client library. - Implement "once" and "lazy" bridge start types. - Add new return type MOSQ_ERR_ERRNO to indicate that the errno variable should be checked for the real error code. - Add support for connection_messages config option. - mosquitto_sub will now refuse to run if the -c option (disable clean session) is given and no client id is provided. - mosquitto_pub now gives more useful error messages on invalid input or other error conditions. - Fix Python will_set() true/True typo. - Fix messages to topic "a/b" incorrectly matching on a subscription "a" if another subscription "a/#" exists. 0.14.4 - 20120106 ================= - Fix local bridge notification messages. - Fix return values for more internal library calls. - Fix incorrect out of memory checks in library and broker. - Never time out local bridge connections. 0.14.3 - 20111210 ================= - Fix potential crash when client connects with an invalid CONNECT packet. - Fix incorrect invalid socket comparison on Windows. - Server shouldn't crash when a message is published to foo/ when a subscription to foo/# exists (bug #901697). - SO_REUSEADDR doesn't work the same on Windows, so don't use it. - Cygwin builds now support Windows service features. - Fix $SYS/broker/bytes/sent reporting. 0.14.2 - 20111123 ================= - Add uninstall target for libs. - Don't try to write packet whilst in a callback. 0.14.1 - 20111117 ================= - Fix Python sytax errors (bug #891673). 0.14 - 20111116 =============== - Add support for matching ACLs based on client id and username. - Add a Windows installer file (NSIS based). - Add native support for running the broker as a Windows service. This is the default when installed using the new installer. - Fix client count for listeners. When clients disconnect, decrement the count. Allow max_connections to work again. - Attempt to send all packets immediately upon being queued. This will result in more immediate network communication in many cases. - Log IP address when reporting CONNACK packets if the client id isn't yet known. - Fix payload length calculation in python will_set function. - Fix Python publish and will_set functions for payload=None. - Fix keepalive value being lost when reconnecting a client (bug #880863). - Persistence file writing now uses portable file functions, so the Cygwin broker build should no longer be necessary. - Duplicate code between the client and broker side has been reduced. - Queued messages for clients reconnecting with clean_session=false set were not being sent until the next message for that client was received. This has been fixed (bug #890724). - Fix subscriptions to # incorrectly matching against topics beginning with / 0.13 - 20110920 =============== - Implement bridge state notification messages. - Save client last used mid in persistent database (DB version number bumped). - Expose message id in Python MosquittoMessage. - It is now possible to set the topic QoS level for bridges. - Python MosquittoMessage payload parameter is now a Python string, not a ctypes object which makes it much easier to use. - Fix queueing of messages for disconnected clients. The max_queued_messages option is now obeyed. - C++ library is now in its own namespace, mosquittopp. - Add support for adding log message timestamps in the broker. - Fix missing mosquitto_username_pw_set() python binding. - Fix keepalive timeout for reconnecting non clean-session clients. Prevents immediate disconnection on reconnection. - Fix subscription wildcard matching - a subscription of +/+ will now match against /foo - Fix subscription wildcard matching - a subscription of foo/# will now match against foo - When restoring persistent database, clients should be set to non clean-session or their subscriptions will be immediately removed. - Fix SUBACK payload for multiple topic subscriptions. - Don't send retained messages when a client subscribes to a topic it is already subscribed to. 0.12 - 20110725 =============== - Reload (most) configuration on SIGHUP. - Memory tracking is no longer compiled in the client library. - Add --help option to mosquitto to display usage. - Add --id-prefix option to clients to allow easier use with brokers that are using the clientid_prefix option. - Fix compilation on QNX. - Add -P as a synonym argument for --pw in the clients. - Fix python MosquittoMessage payload parameter. This is now returned as a pointer to an array of c_uint8 values so binary data is handled correctly. If a string is needed, use msg.payload_str - Fix memory leaks on client authentication. - If password_file is not defined then clients can now connect even if they use a username/password. - Add mosquitto_reconnect() to the client library. - Add option for compiling with liberal protocol compliance support (enabled by default). - Fix problems with clients reconnecting and old messages remaining in the message store. - Display both ip and client id in the log message when a client connects. Change the socket connection message to make it more obvious that it is just a socket connection being made (bug #801135). - Fix retained message delivery where a subscription contains a +. - Be more lenient when reloading persistent database to reduce errors with empty retained messages. 0.11.3 - 20110707 ================= - Don't complain and quit if persistence_file option is given (bug #802423). - Initialise listeners correctly when clients with duplicate client ids connect. Bug #801678. - Memory tracking is now disabled for Symbian builds due to lack of malloc.h. - Fix memory tracking compilation for kFreeBSD. - Python callbacks can now be used with class member functions. - Fix persistent database writing of client message chunks which caused errors when restoring (bug #798164). 0.11.2 - 20110626 ================= - Don't free contexts in mqtt3_context_disconnect() (bug #799688 / #801678). - Only free will if present when freeing a client context. 0.11.1 - 20110620 ================= - Fix buffer overrun when checking for + and # in topics (bug #799688). - Pub client now quits if publish fails. 0.11 - 20110619 =============== - Removed all old sqlite code. - Remove client id limit in clients. - Implemented $SYS/broker/heap/maximum size - Implemented $SYS/broker/clients/inactive to show the number of disconnected non-clean session clients. - $SYS/broker/heap/current size and maximum size messages now include "bytes" to match rsmb message format. - Implemented the retained_persistence config file option - a synonym of the "persistence" option. - Added security_external.c to broker source to make it easier for third parties to add support for their existing username/password and ACL database for security checks. See external_security_checks.txt. - $SYS messages are now only republished when their value changes. - Windows native broker now responds to command line arguments. - Simplify client disconnecting so wills gets sent in all cases (bug #792468). - Clients now have a --quiet option. - The on_disconnect() callback will always be called now, even if the client has disconnected unexpectedly. - Always close persistent DB file after restoring. - Return error code when exiting the clients. - mosquitto_publish() now returns MOSQ_ERR_INVAL if the topic contains + or # - mosquitto now silently rejects published messages with + or # in the topic. - max_connections is now a per-listener setting instead of global. - Connection count is now reduced when clients disconnect (bug #797983). 0.10.2 - 20110106 ================= - Don't abort when connecting if the first connection fails. This is important on e.g. Windows 7, where IPV6 is offered as the first choice but may not be available. - Deal with long logging messages properly (bug #785882). - Fix library compilation on Symbian - no pselect() available. - Don't stop processing subscriptions on received messages after a subscription with # matches. (bug #791206). 0.10.1 - 20110512 ================= - Fix Windows compilation. - Fix mosquitto.py on Windows - call lib init/cleanup. - Don't abort when connecting if given an unknown address type (assuming an IPv4 or IPv6 address is given). 0.10 - 20110429 =============== - Implement support for the password_file option and accompanying authentication requirements in the broker. - Implement topic Access Control Lists. - mosquitto_will_set() and mosquitto_publish() now return MOSQ_ERR_PAYLOAD_SIZE if the payload is too large (>268,435,455 bytes). - Bridge support can now be disabled at compile time. - Group together network writes for outgoing packets - don't send single byte writes! - Add support for clientid_prefixes variable. - Add support for the clientid config variable for controlling bridge client ids. - Remove 32-bit database ID support because htobe64() no longer used. - Multiple client subscriptions to the same topic result in only a single subscription. Bug #744077. 0.9.3 - 20110310 ================ - Set retained message status for QoS 2 messages (bug #726535). - Only abort with an error when opening listening sockets if no address family is available, rather than aborting when any address family is not available. - Don't clean queued messages when a non clean session client reconnects. - Make mosquitto.py compatible with Python <2.6. - Fix mosquitto.h header includes for Windows. 0.9.2 - 20110208 ================ - Only send a single DISCONNECT command when using -l in the pub client. - Set QoS=1 on PUBREL commands to meet protocol spec. - Don't leak sockets on connection failure in the library. - Install man pages when building under cmake. - Fix crash bug on malformed CONNECT message. - Clients are now rejected if their socket peer name cannot be obtained on connection. - Fix a number of potential problems caused when a client with a duplicate id connects. - Install mosquitto.conf under cmake. 0.9.1 - 20101203 ================ - Add missing code for parsing the "bind_address" configuration option. - Fix missing include when compiling with tcp-wrappers support. - Add linker version script for C library to control exported functions. 0.9 - 20101114 ============== - Client and message data is now stored in memory with custom routines rather than a sqlite database. This removes the dependencies on sqlite, pcre and sqlite3-pcre. It also means that the persistent database format has had to be reimplemented in a custom format. Optional support for importing old sqlite databases is provided. - Added IPv6 support for mosquitto and the clients. - Provide username and password support for the clients and client libraries. This is part of the new MQTT v3.1 spec. - The broker supports the username and password connection flags, but will not do anything with the username and password. - Python callback functions now optionally take an extra argument which will return the user object passed to the Mosquitto() constructor, or the calling python object itself if nothing was given to Mosquitto(). - Remove the mosquitto command line option "-i interface". - Remove the mosquitto.conf "interface" variable. - Add support for the listener config variable (replaces the interface variable) - Add support for the bind_address config variable. - Change the port config variable behaviour to match that of rsmb (applies to the default listener only, can be given just once). - Fix QoS 2 protocol compliance - stop sending duplicate messages and handle timeouts correctly. Fixes bug #598290. - Set retain flag correctly for outgoing messages. It should only be set for messages sent in response to a subscribe command (ie. stale data). - Fix bug in returning correct CONNACK result to on_connect client callback. - Don't send client will if it is disconnected for exceeding its keepalive timer. - Fix client library unsubscribe function incorrectly sending a SUBSCRIBE command when it should be UNSUBSCRIBE. - Fix max_inflight_messages and max_queued_messages operation. These parameters now apply only to QoS 1 and 2 messages and are used regardless of the client connection state. - mosquitto.conf now installed to /etc/mosquitto/mosquitto.conf instead of /etc/mosquitto.conf. The /etc/mosquitto/ directory will be used for password and access control files in the future. - Give the compile time option of using 32-bit integers for the database IDs instead of 64-bit integers. This is useful where htobe64()/be64toh() are not available or for embedded systems for example. - The DUP bit is now set correctly when resending PUBREL messages. - A port to Windows native has been partially completed. This currently drops a number of features, including the ability to change configuration parameters and persistent storage. 0.8.3 - 20101004 ================ - Fix QoS 2 protocol compliance - stop sending duplicate messages and handle timeouts correctly. Fixes bug #598290. (backported from future 0.9 code) 0.8.2 - 20100815 ================ - Fix default loop() timeout value in mosquitto.py. Previous value was 0, causing high cpu load. - Fix message handling problem in client library when more than one message was in the client queue. - Fix the logic used to determine whether a QoS>0 message needs to be retried. - Fix the Python sub.py example so that it quits on error. 0.8.1 - 20100812 ================ - Improve python interface - Fix incorrect return value from message delete function - Use logging function to print error messages in clients. - Fix python installation script DESTDIR. - Fix library destination path for 64-bit machines. 0.8 - 20100807 ============== - Topics starting with a / are treated as distinct to those not starting with a /. For example, /topic/path is different to topic/path. This matches the behaviour of rsmb. - Correctly calculate the will QoS on a new client connection (bug #597451). - Add "addresses" configuration file variable as an alias of "address", for better rsmb compatibility. - Bridge clean_session setting is now false, to give more sensible behaviour and be more compatible with rsmb. - Add cleansession variable for configuring bridges. - Add keepalive_interval variable for bridges. - Remove default topic subscription for mosquitto_sub because the old behaviour was too confusing. - Added a C client library, which the pub and sub clients now use. - Added a C++ client library (bound to the C library). - Added a Python client library (bound to the C library). - Added CMake build scripts to allow the library and clients (not the broker) to be compiled natively on Windows. 0.7 - 20100615 ============== - mosquitto_pub can now send null (zero length) messages. - Don't store QoS=0 messages for disconnected clients with subscriptions of QoS>0. - accept() all available sockets when new clients are connecting, rather than just one. - Add option to print debug messages in pub and sub clients. - hg revision is now exported via $SYS/broker/changeset - Send Will when client exceeds keepalive timer and is disconnected. - Check to see if a client has a will before sending it. - Correctly deal with clients connecting with the same id multiple times. - Add compile time option to disable heap memory tracking. - Use poll() instead of select() to allow >1024 clients. - Implement max_connections. - Run VACUUM on in-memory database on receiving SIGUSR2. - Fix bridge keepalive timeouts and reconnects. - Don't attempt to drop root privileges when running on Windows as this isn't well supported (bug #586231). 0.6.1 - 20100506 ================ - Fix DB auto upgrade for messages table. 0.6 - 20100505 ============== - Basic support for connecting multiple MQTT brokers together (bridging). - mosquitto_sub can now subscribe to multiple topics (limited to a global QoS). - mosquitto_pub can now send a file as a message. - mosquitto_pub can now read all of stdin and send it as a message. - mosquitto_pub can now read stdin and send each line as a message. - mosquitto will now correctly run VACUUM on the persistent database on exit. - Implement a more efficient database design, so that only one copy of each message is held in the database, rather than one per subscribed client. - Add the store_cleanup_interval config option for dealing with the internal message store. - Add support for disabling "clean session" for the sub client. - Add support for automatic upgrading of the mosquitto DB from v1 to v2. - Add persistence_file config option to allow changing the filename of the persistence database. This allows multiple mosquitto DBs to be stored in the same location whilst keeping persistence_location compatible with rsmb. - Don't store QoS=0 messages for disconnected clients. Fixes bug #572608. This wasn't correctly fixed in version 0.5. - Don't disconnect clients if they send a PUBLISH with zero length payload (bug #573610). - If a retained message is received with a zero length payload, the retained message for that topic is deleted. - Send through zero length messages. - Produce a warning on unsupported rsmb options instead of quitting. - Describe clean session flag in the mqtt man page. - Implement the max_inflight_messages and max_queued_messages features in the broker. 0.5.4 - 20100311 ================ - Fix memory allocation in mqtt3_fix_sub_topic() (bug #531861). - Remove accidental limit of 100 client connections. - Fix mosquitto_pub handling of messages with QoS>0 (bug #537061). 0.5.3 - 20100303 ================ - Will messages are now only sent when a client disconnects unexpectedly. - Fix all incoming topics/subscriptions that start with a / or contain multiple / in a row (//). - Do actually disconnect client when it sends an empty subscription/topic string. - Add missing $SYS/broker/clients/total to man page. 0.5.2 - 20100302 ================ - Always update last backup time, so that the backup doesn't run every time through the main loop once autosave_interval has been reached. - Report $SYS/broker/uptime in the same format as rsmb. - Make mandatory options obvious in usage output and man page of mosquitto_pub. Fixes bug #529990. - Treat subscriptions with a trailing slash correctly. This should fix bugs #530369 and #530099. 0.5.1 - 20100227 ================ - Must daemonise before pid file is written. 0.5 - 20100227 ============== - No longer store QoS=0 messages for disconnected clients that do not have clean start set. - Rename msg_timeout option to retry_interval for better rsmb compatibility. - Change persistence behaviour. The database is now stored in memory even if persistence is enabled. It is written to disk when mosquitto exits and also at periodic intervals as defined by the new autosave_interval option. - The writing of the persistence database may be forced by sending mosquitto the SIGUSR1 signal. - Clients that do not send CONNECT as their first command are now disconnected. - Boolean configuration values may now be specified with true/false as well as 1/0. - Log message on CONNECT with invalid protocol or protocol version. - Default sqlite3-pcre path on Linux is now /usr/lib/sqlite3/pcre.so to match future sqlite3-pcre packages. - Add mosquitto_sub and mosquitto_pub, simple clients for subscribe/publish. - Add man pages for clients. - Add general man page on mqtt. - Root privileges are now dropped only after attempting to write a pid file (if configured). This means that the pid file can be written to /var/run/ directly and should fix bug #523183. 0.4.2 - 20100203 ================ - Fix segfault on client connect with invalid protocol name/version. 0.4.1 - 20100112 =============== - Fix regex used for finding retained messages to send on new subscription. 0.4 - 20100105 ============== - Added support for wildcard subscriptions using + and #. - All network operations are now non-blocking and can cope with partial packets, meaning that networking should be a lot more reliable. - Total messsages/bytes sent/received are now available in $SYS. - Improved logging information - use client ip address and id instead of socket number. - Broker build timestamp is available in $SYS. - Keepalive==0 is now correctly treated as "never disconnect". - Fixed manpage installation. - Fixed incorrect $SYS hierarchy locations in documentation and code. - Debug type log messages are no longer sent to "topics". - Default logging destination no longer includes "topics" to prevent possible error logging to the db before it is initialised. - Periodic $SYS messages can now be disabled. - stdout and stderr are flushed when logging to them to give more timely updates. - dup is now set correctly when resending messages. - Database format bumped due to topic column naming fix. 0.3 - 20091217 ============== - The port option in the configuration file and --port command line argument may now be given any number of times to make mosquitto listen on multiple sockets. - Add new config file and command line option "interface" to specify an interface to listen on, rather than all interfaces. - Added host access control through tcp-wrappers support. - Set SO_REUSEADDR on the listening socket so restart is much quicker. - Added support for tracking current heap memory usage - this is published on the topic "$SYS/broker/heap/current size" - Added code for logging to stderr, stdout, syslog and topics. - Added logging to numerous places - still plenty of scope for more. 0.2 - 20091204 ============== - Replaced the command line option --foreground with --daemon, swapping the default behaviour. - Added the command line option --config-file, to specify a config file to load. If this is not given, no config file is load and the default options are used. - Added the command line option --port for specifying the port to listen on. This overrides values in the config file. - Don't use persistence by default. - Default behaviour is now more sane when run by a normal user with no command line options (combination of above changes). - Added option user to config file, defaulting to a value of mosquitto. If this value isn't blank and mosquitto is started by root, then it will drop privileges by changing to the user and its primary group. This replaces the current behaviour of refusing to start if run by root. - Fix non-persistent mode, which would never work in the previous release. - Added information on default values of msg_timeout and sys_interval to the mosquitto.conf man page. (closes bug #492045). mosquitto-1.6.9/examples/0000775000175000017500000000000013626052637014443 5ustar rogerrogermosquitto-1.6.9/examples/mysql_log/0000775000175000017500000000000013626052637016451 5ustar rogerrogermosquitto-1.6.9/examples/mysql_log/mysql_log.c0000664000175000017500000000527713626052637020636 0ustar rogerroger#include #include #include #ifndef WIN32 # include #else # include # define snprintf sprintf_s #endif #include #include #define db_host "localhost" #define db_username "mqtt_log" #define db_password "password" #define db_database "mqtt_log" #define db_port 3306 #define db_query "INSERT INTO mqtt_log (topic, payload) VALUES (?,?)" #define mqtt_host "localhost" #define mqtt_port 1883 static int run = 1; static MYSQL_STMT *stmt = NULL; void handle_signal(int s) { run = 0; } void connect_callback(struct mosquitto *mosq, void *obj, int result) { } void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) { MYSQL_BIND bind[2]; memset(bind, 0, sizeof(bind)); bind[0].buffer_type = MYSQL_TYPE_STRING; bind[0].buffer = message->topic; bind[0].buffer_length = strlen(message->topic); // Note: payload is normally a binary blob and could contains // NULL byte. This sample does not handle it and assume payload is a // string. bind[1].buffer_type = MYSQL_TYPE_STRING; bind[1].buffer = message->payload; bind[1].buffer_length = message->payloadlen; mysql_stmt_bind_param(stmt, bind); mysql_stmt_execute(stmt); } int main(int argc, char *argv[]) { MYSQL *connection; my_bool reconnect = true; char clientid[24]; struct mosquitto *mosq; int rc = 0; signal(SIGINT, handle_signal); signal(SIGTERM, handle_signal); mysql_library_init(0, NULL, NULL); mosquitto_lib_init(); connection = mysql_init(NULL); if(connection){ mysql_options(connection, MYSQL_OPT_RECONNECT, &reconnect); connection = mysql_real_connect(connection, db_host, db_username, db_password, db_database, db_port, NULL, 0); if(connection){ stmt = mysql_stmt_init(connection); mysql_stmt_prepare(stmt, db_query, strlen(db_query)); memset(clientid, 0, 24); snprintf(clientid, 23, "mysql_log_%d", getpid()); mosq = mosquitto_new(clientid, true, connection); if(mosq){ mosquitto_connect_callback_set(mosq, connect_callback); mosquitto_message_callback_set(mosq, message_callback); rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60); mosquitto_subscribe(mosq, NULL, "#", 0); while(run){ rc = mosquitto_loop(mosq, -1, 1); if(run && rc){ sleep(20); mosquitto_reconnect(mosq); } } mosquitto_destroy(mosq); } mysql_stmt_close(stmt); mysql_close(connection); }else{ fprintf(stderr, "Error: Unable to connect to database.\n"); printf("%s\n", mysql_error(connection)); rc = 1; } }else{ fprintf(stderr, "Error: Unable to start mysql.\n"); rc = 1; } mysql_library_end(); mosquitto_lib_cleanup(); return rc; } mosquitto-1.6.9/examples/mysql_log/Makefile0000664000175000017500000000043713626052637020115 0ustar rogerrogerCFLAGS=-Wall -ggdb LDFLAGS=../../lib/libmosquitto.so.1 -lmysqlclient .PHONY: all clean all : mosquitto_mysql_log mosquitto_mysql_log : mysql_log.o ${CC} $^ -o $@ ${LDFLAGS} mysql_log.o : mysql_log.c ${CC} -c $^ -o $@ ${CFLAGS} -I../../lib clean : -rm -f *.o mosquitto_mysql_log mosquitto-1.6.9/examples/subscribe_simple/0000775000175000017500000000000013626052637017775 5ustar rogerrogermosquitto-1.6.9/examples/subscribe_simple/single.c0000664000175000017500000000103613626052637021422 0ustar rogerroger#include #include #include "mosquitto.h" int main(int argc, char *argv[]) { int rc; struct mosquitto_message *msg; mosquitto_lib_init(); rc = mosquitto_subscribe_simple( &msg, 1, true, "irc/#", 0, "test.mosquitto.org", 1883, NULL, 60, true, NULL, NULL, NULL, NULL); if(rc){ printf("Error: %s\n", mosquitto_strerror(rc)); mosquitto_lib_cleanup(); return rc; } printf("%s %s\n", msg->topic, (char *)msg->payload); mosquitto_message_free(&msg); mosquitto_lib_cleanup(); return 0; } mosquitto-1.6.9/examples/subscribe_simple/callback.c0000664000175000017500000000110513626052637021672 0ustar rogerroger#include #include #include "mosquitto.h" int on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) { printf("%s %s (%d)\n", msg->topic, (const char *)msg->payload, msg->payloadlen); return 0; } int main(int argc, char *argv[]) { int rc; mosquitto_lib_init(); rc = mosquitto_subscribe_callback( on_message, NULL, "irc/#", 0, "test.mosquitto.org", 1883, NULL, 60, true, NULL, NULL, NULL, NULL); if(rc){ printf("Error: %s\n", mosquitto_strerror(rc)); } mosquitto_lib_cleanup(); return rc; } mosquitto-1.6.9/examples/subscribe_simple/multiple.c0000664000175000017500000000116513626052637021777 0ustar rogerroger#include #include #include "mosquitto.h" #define COUNT 3 int main(int argc, char *argv[]) { int rc; int i; struct mosquitto_message *msg; mosquitto_lib_init(); rc = mosquitto_subscribe_simple( &msg, COUNT, true, "irc/#", 0, "test.mosquitto.org", 1883, NULL, 60, true, NULL, NULL, NULL, NULL); if(rc){ printf("Error: %s\n", mosquitto_strerror(rc)); mosquitto_lib_cleanup(); return rc; } for(i=0; iloop_forever(); mosqpp::lib_cleanup(); return 0; } mosquitto-1.6.9/examples/temperature_conversion/temperature_conversion.cpp0000664000175000017500000000227713626052637026563 0ustar rogerroger#include #include #include "temperature_conversion.h" #include mqtt_tempconv::mqtt_tempconv(const char *id, const char *host, int port) : mosquittopp(id) { int keepalive = 60; /* Connect immediately. This could also be done by calling * mqtt_tempconv->connect(). */ connect(host, port, keepalive); }; mqtt_tempconv::~mqtt_tempconv() { } void mqtt_tempconv::on_connect(int rc) { printf("Connected with code %d.\n", rc); if(rc == 0){ /* Only attempt to subscribe on a successful connect. */ subscribe(NULL, "temperature/celsius"); } } void mqtt_tempconv::on_message(const struct mosquitto_message *message) { double temp_celsius, temp_farenheit; char buf[51]; if(!strcmp(message->topic, "temperature/celsius")){ memset(buf, 0, 51*sizeof(char)); /* Copy N-1 bytes to ensure always 0 terminated. */ memcpy(buf, message->payload, 50*sizeof(char)); temp_celsius = atof(buf); temp_farenheit = temp_celsius*9.0/5.0 + 32.0; snprintf(buf, 50, "%f", temp_farenheit); publish(NULL, "temperature/farenheit", strlen(buf), buf); } } void mqtt_tempconv::on_subscribe(int mid, int qos_count, const int *granted_qos) { printf("Subscription succeeded.\n"); } mosquitto-1.6.9/examples/temperature_conversion/temperature_conversion.h0000664000175000017500000000062213626052637026220 0ustar rogerroger#ifndef TEMPERATURE_CONVERSION_H #define TEMPERATURE_CONVERSION_H #include class mqtt_tempconv : public mosqpp::mosquittopp { public: mqtt_tempconv(const char *id, const char *host, int port); ~mqtt_tempconv(); void on_connect(int rc); void on_message(const struct mosquitto_message *message); void on_subscribe(int mid, int qos_count, const int *granted_qos); }; #endif mosquitto-1.6.9/examples/temperature_conversion/readme.txt0000664000175000017500000000045613626052637023250 0ustar rogerrogerThis is a simple example of the C++ library mosquittopp. It is a client that subscribes to the topic temperature/celsius which should have temperature data in text form being published to it. It reads this data as a Celsius temperature, converts to Farenheit and republishes on temperature/farenheit. mosquitto-1.6.9/examples/temperature_conversion/Makefile0000664000175000017500000000071213626052637022705 0ustar rogerrogerCFLAGS=-Wall -ggdb -I../../lib -I../../lib/cpp LDFLAGS=-L../../lib ../../lib/cpp/libmosquittopp.so.1 ../../lib/libmosquitto.so.1 .PHONY: all clean all : mqtt_temperature_conversion mqtt_temperature_conversion : main.o temperature_conversion.o ${CXX} $^ -o $@ ${LDFLAGS} main.o : main.cpp ${CXX} -c $^ -o $@ ${CFLAGS} temperature_conversion.o : temperature_conversion.cpp ${CXX} -c $^ -o $@ ${CFLAGS} clean : -rm -f *.o mqtt_temperature_conversion mosquitto-1.6.9/mosquitto.conf0000664000175000017500000012701313626052637015544 0ustar rogerroger# Config file for mosquitto # # See mosquitto.conf(5) for more information. # # Default values are shown, uncomment to change. # # Use the # character to indicate a comment, but only if it is the # very first character on the line. # ================================================================= # General configuration # ================================================================= # Use per listener security settings. # # It is recommended this option be set before any other options. # # If this option is set to true, then all authentication and access control # options are controlled on a per listener basis. The following options are # affected: # # password_file acl_file psk_file auth_plugin auth_opt_* allow_anonymous # auto_id_prefix allow_zero_length_clientid # # Note that if set to true, then a durable client (i.e. with clean session set # to false) that has disconnected will use the ACL settings defined for the # listener that it was most recently connected to. # # The default behaviour is for this to be set to false, which maintains the # setting behaviour from previous versions of mosquitto. #per_listener_settings false # If a client is subscribed to multiple subscriptions that overlap, e.g. foo/# # and foo/+/baz , then MQTT expects that when the broker receives a message on # a topic that matches both subscriptions, such as foo/bar/baz, then the client # should only receive the message once. # Mosquitto keeps track of which clients a message has been sent to in order to # meet this requirement. The allow_duplicate_messages option allows this # behaviour to be disabled, which may be useful if you have a large number of # clients subscribed to the same set of topics and are very concerned about # minimising memory usage. # It can be safely set to true if you know in advance that your clients will # never have overlapping subscriptions, otherwise your clients must be able to # correctly deal with duplicate messages even when then have QoS=2. #allow_duplicate_messages false # This option controls whether a client is allowed to connect with a zero # length client id or not. This option only affects clients using MQTT v3.1.1 # and later. If set to false, clients connecting with a zero length client id # are disconnected. If set to true, clients will be allocated a client id by # the broker. This means it is only useful for clients with clean session set # to true. #allow_zero_length_clientid true # If allow_zero_length_clientid is true, this option allows you to set a prefix # to automatically generated client ids to aid visibility in logs. # Defaults to 'auto-' #auto_id_prefix auto- # This option affects the scenario when a client subscribes to a topic that has # retained messages. It is possible that the client that published the retained # message to the topic had access at the time they published, but that access # has been subsequently removed. If check_retain_source is set to true, the # default, the source of a retained message will be checked for access rights # before it is republished. When set to false, no check will be made and the # retained message will always be published. This affects all listeners. #check_retain_source true # QoS 1 and 2 messages will be allowed inflight per client until this limit # is exceeded. Defaults to 0. (No maximum) # See also max_inflight_messages #max_inflight_bytes 0 # The maximum number of QoS 1 and 2 messages currently inflight per # client. # This includes messages that are partway through handshakes and # those that are being retried. Defaults to 20. Set to 0 for no # maximum. Setting to 1 will guarantee in-order delivery of QoS 1 # and 2 messages. #max_inflight_messages 20 # For MQTT v5 clients, it is possible to have the server send a "server # keepalive" value that will override the keepalive value set by the client. # This is intended to be used as a mechanism to say that the server will # disconnect the client earlier than it anticipated, and that the client should # use the new keepalive value. The max_keepalive option allows you to specify # that clients may only connect with keepalive less than or equal to this # value, otherwise they will be sent a server keepalive telling them to use # max_keepalive. This only applies to MQTT v5 clients. The maximum value # allowable is 65535. Do not set below 10. #max_keepalive 65535 # For MQTT v5 clients, it is possible to have the server send a "maximum packet # size" value that will instruct the client it will not accept MQTT packets # with size greater than max_packet_size bytes. This applies to the full MQTT # packet, not just the payload. Setting this option to a positive value will # set the maximum packet size to that number of bytes. If a client sends a # packet which is larger than this value, it will be disconnected. This applies # to all clients regardless of the protocol version they are using, but v3.1.1 # and earlier clients will of course not have received the maximum packet size # information. Defaults to no limit. Setting below 20 bytes is forbidden # because it is likely to interfere with ordinary client operation, even with # very small payloads. #max_packet_size 0 # QoS 1 and 2 messages above those currently in-flight will be queued per # client until this limit is exceeded. Defaults to 0. (No maximum) # See also max_queued_messages. # If both max_queued_messages and max_queued_bytes are specified, packets will # be queued until the first limit is reached. #max_queued_bytes 0 # The maximum number of QoS 1 and 2 messages to hold in a queue per client # above those that are currently in-flight. Defaults to 100. Set # to 0 for no maximum (not recommended). # See also queue_qos0_messages. # See also max_queued_bytes. #max_queued_messages 100 # # This option sets the maximum number of heap memory bytes that the broker will # allocate, and hence sets a hard limit on memory use by the broker. Memory # requests that exceed this value will be denied. The effect will vary # depending on what has been denied. If an incoming message is being processed, # then the message will be dropped and the publishing client will be # disconnected. If an outgoing message is being sent, then the individual # message will be dropped and the receiving client will be disconnected. # Defaults to no limit. #memory_limit 0 # This option sets the maximum publish payload size that the broker will allow. # Received messages that exceed this size will not be accepted by the broker. # The default value is 0, which means that all valid MQTT messages are # accepted. MQTT imposes a maximum payload size of 268435455 bytes. #message_size_limit 0 # This option allows persistent clients (those with clean session set to false) # to be removed if they do not reconnect within a certain time frame. # # This is a non-standard option in MQTT V3.1 but allowed in MQTT v3.1.1. # # Badly designed clients may set clean session to false whilst using a randomly # generated client id. This leads to persistent clients that will never # reconnect. This option allows these clients to be removed. # # The expiration period should be an integer followed by one of h d w m y for # hour, day, week, month and year respectively. For example # # persistent_client_expiration 2m # persistent_client_expiration 14d # persistent_client_expiration 1y # # The default if not set is to never expire persistent clients. #persistent_client_expiration # Write process id to a file. Default is a blank string which means # a pid file shouldn't be written. # This should be set to /var/run/mosquitto.pid if mosquitto is # being run automatically on boot with an init script and # start-stop-daemon or similar. #pid_file # Set to true to queue messages with QoS 0 when a persistent client is # disconnected. These messages are included in the limit imposed by # max_queued_messages and max_queued_bytes # Defaults to false. # This is a non-standard option for the MQTT v3.1 spec but is allowed in # v3.1.1. #queue_qos0_messages false # Set to false to disable retained message support. If a client publishes a # message with the retain bit set, it will be disconnected if this is set to # false. #retain_available true # Disable Nagle's algorithm on client sockets. This has the effect of reducing # latency of individual messages at the potential cost of increasing the number # of packets being sent. #set_tcp_nodelay false # Time in seconds between updates of the $SYS tree. # Set to 0 to disable the publishing of the $SYS tree. #sys_interval 10 # The MQTT specification requires that the QoS of a message delivered to a # subscriber is never upgraded to match the QoS of the subscription. Enabling # this option changes this behaviour. If upgrade_outgoing_qos is set true, # messages sent to a subscriber will always match the QoS of its subscription. # This is a non-standard option explicitly disallowed by the spec. #upgrade_outgoing_qos false # When run as root, drop privileges to this user and its primary # group. # Set to root to stay as root, but this is not recommended. # If run as a non-root user, this setting has no effect. # Note that on Windows this has no effect and so mosquitto should # be started by the user you wish it to run as. #user mosquitto # ================================================================= # Default listener # ================================================================= # IP address/hostname to bind the default listener to. If not # given, the default listener will not be bound to a specific # address and so will be accessible to all network interfaces. # bind_address ip-address/host name #bind_address # Port to use for the default listener. #port 1883 # Bind the listener to a specific interface. This is similar to # bind_address above but is useful when an interface has multiple addresses or # the address may change. It is valid to use this with the bind_address option, # but take care that the interface you are binding to contains the address you # are binding to, otherwise you will not be able to connect. # Example: bind_interface eth0 #bind_interface # When a listener is using the websockets protocol, it is possible to serve # http data as well. Set http_dir to a directory which contains the files you # wish to serve. If this option is not specified, then no normal http # connections will be possible. #http_dir # The maximum number of client connections to allow. This is # a per listener setting. # Default is -1, which means unlimited connections. # Note that other process limits mean that unlimited connections # are not really possible. Typically the default maximum number of # connections possible is around 1024. #max_connections -1 # Choose the protocol to use when listening. # This can be either mqtt or websockets. # Websockets support is currently disabled by default at compile time. # Certificate based TLS may be used with websockets, except that # only the cafile, certfile, keyfile and ciphers options are supported. #protocol mqtt # Set use_username_as_clientid to true to replace the clientid that a client # connected with with its username. This allows authentication to be tied to # the clientid, which means that it is possible to prevent one client # disconnecting another by using the same clientid. # If a client connects with no username it will be disconnected as not # authorised when this option is set to true. # Do not use in conjunction with clientid_prefixes. # See also use_identity_as_username. #use_username_as_clientid # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- # The following options can be used to enable SSL/TLS support for # this listener. Note that the recommended port for MQTT over TLS # is 8883, but this must be set manually. # # See also the mosquitto-tls man page. # At least one of cafile or capath must be defined. They both # define methods of accessing the PEM encoded Certificate # Authority certificates that have signed your server certificate # and that you wish to trust. # cafile defines the path to a file containing the CA certificates. # capath defines a directory that will be searched for files # containing the CA certificates. For capath to work correctly, the # certificate files must have ".crt" as the file ending and you must run # "openssl rehash " each time you add/remove a certificate. #cafile #capath # Path to the PEM encoded server certificate. #certfile # Path to the PEM encoded keyfile. #keyfile # If you have require_certificate set to true, you can create a certificate # revocation list file to revoke access to particular client certificates. If # you have done this, use crlfile to point to the PEM encoded revocation file. #crlfile # If you wish to control which encryption ciphers are used, use the ciphers # option. The list of available ciphers can be obtained using the "openssl # ciphers" command and should be provided in the same format as the output of # that command. # If unset defaults to DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH #ciphers DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH # To allow the use of ephemeral DH key exchange, which provides forward # security, the listener must load DH parameters. This can be specified with # the dhparamfile option. The dhparamfile can be generated with the command # e.g. "openssl dhparam -out dhparam.pem 2048" #dhparamfile # By default a TLS enabled listener will operate in a similar fashion to a # https enabled web server, in that the server has a certificate signed by a CA # and the client will verify that it is a trusted certificate. The overall aim # is encryption of the network traffic. By setting require_certificate to true, # the client must provide a valid certificate in order for the network # connection to proceed. This allows access to the broker to be controlled # outside of the mechanisms provided by MQTT. #require_certificate false # This option defines the version of the TLS protocol to use for this listener. # The default value allows all of v1.3, v1.2 and v1.1. The valid values are # tlsv1.3 tlsv1.2 and tlsv1.1. #tls_version # If require_certificate is true, you may set use_identity_as_username to true # to use the CN value from the client certificate as a username. If this is # true, the password_file option will not be used for this listener. # This takes priority over use_subject_as_username. # See also use_subject_as_username. #use_identity_as_username false # If require_certificate is true, you may set use_subject_as_username to true # to use the complete subject value from the client certificate as a username. # If this is true, the password_file option will not be used for this listener. # See also use_identity_as_username #use_subject_as_username false # ----------------------------------------------------------------- # Pre-shared-key based SSL/TLS support # ----------------------------------------------------------------- # The following options can be used to enable PSK based SSL/TLS support for # this listener. Note that the recommended port for MQTT over TLS is 8883, but # this must be set manually. # # See also the mosquitto-tls man page and the "Certificate based SSL/TLS # support" section. Only one of certificate or PSK encryption support can be # enabled for any listener. # The psk_hint option enables pre-shared-key support for this listener and also # acts as an identifier for this listener. The hint is sent to clients and may # be used locally to aid authentication. The hint is a free form string that # doesn't have much meaning in itself, so feel free to be creative. # If this option is provided, see psk_file to define the pre-shared keys to be # used or create a security plugin to handle them. #psk_hint # When using PSK, the encryption ciphers used will be chosen from the list of # available PSK ciphers. If you want to control which ciphers are available, # use the "ciphers" option. The list of available ciphers can be obtained # using the "openssl ciphers" command and should be provided in the same format # as the output of that command. #ciphers # Set use_identity_as_username to have the psk identity sent by the client used # as its username. Authentication will be carried out using the PSK rather than # the MQTT username/password and so password_file will not be used for this # listener. #use_identity_as_username false # ================================================================= # Extra listeners # ================================================================= # Listen on a port/ip address combination. By using this variable # multiple times, mosquitto can listen on more than one port. If # this variable is used and neither bind_address nor port given, # then the default listener will not be started. # The port number to listen on must be given. Optionally, an ip # address or host name may be supplied as a second argument. In # this case, mosquitto will attempt to bind the listener to that # address and so restrict access to the associated network and # interface. By default, mosquitto will listen on all interfaces. # Note that for a websockets listener it is not possible to bind to a host # name. # listener port-number [ip address/host name] #listener # Bind the listener to a specific interface. This is similar to # the [ip address/host name] part of the listener definition, but is useful # when an interface has multiple addresses or the address may change. It is # valid to use this with the [ip address/host name] part of the listener # definition, but take care that the interface you are binding to contains the # address you are binding to, otherwise you will not be able to connect. # Only available on Linux and requires elevated privileges. # # Example: bind_interface eth0 #bind_interface # When a listener is using the websockets protocol, it is possible to serve # http data as well. Set http_dir to a directory which contains the files you # wish to serve. If this option is not specified, then no normal http # connections will be possible. #http_dir # The maximum number of client connections to allow. This is # a per listener setting. # Default is -1, which means unlimited connections. # Note that other process limits mean that unlimited connections # are not really possible. Typically the default maximum number of # connections possible is around 1024. #max_connections -1 # The listener can be restricted to operating within a topic hierarchy using # the mount_point option. This is achieved be prefixing the mount_point string # to all topics for any clients connected to this listener. This prefixing only # happens internally to the broker; the client will not see the prefix. #mount_point # Choose the protocol to use when listening. # This can be either mqtt or websockets. # Certificate based TLS may be used with websockets, except that only the # cafile, certfile, keyfile and ciphers options are supported. #protocol mqtt # Set use_username_as_clientid to true to replace the clientid that a client # connected with with its username. This allows authentication to be tied to # the clientid, which means that it is possible to prevent one client # disconnecting another by using the same clientid. # If a client connects with no username it will be disconnected as not # authorised when this option is set to true. # Do not use in conjunction with clientid_prefixes. # See also use_identity_as_username. #use_username_as_clientid # Change the websockets headers size. This is a global option, it is not # possible to set per listener. This option sets the size of the buffer used in # the libwebsockets library when reading HTTP headers. If you are passing large # header data such as cookies then you may need to increase this value. If left # unset, or set to 0, then the default of 1024 bytes will be used. #websockets_headers_size # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- # The following options can be used to enable certificate based SSL/TLS support # for this listener. Note that the recommended port for MQTT over TLS is 8883, # but this must be set manually. # # See also the mosquitto-tls man page and the "Pre-shared-key based SSL/TLS # support" section. Only one of certificate or PSK encryption support can be # enabled for any listener. # At least one of cafile or capath must be defined to enable certificate based # TLS encryption. They both define methods of accessing the PEM encoded # Certificate Authority certificates that have signed your server certificate # and that you wish to trust. # cafile defines the path to a file containing the CA certificates. # capath defines a directory that will be searched for files # containing the CA certificates. For capath to work correctly, the # certificate files must have ".crt" as the file ending and you must run # "openssl rehash " each time you add/remove a certificate. #cafile #capath # Path to the PEM encoded server certificate. #certfile # Path to the PEM encoded keyfile. #keyfile # If you wish to control which encryption ciphers are used, use the ciphers # option. The list of available ciphers can be optained using the "openssl # ciphers" command and should be provided in the same format as the output of # that command. #ciphers # If you have require_certificate set to true, you can create a certificate # revocation list file to revoke access to particular client certificates. If # you have done this, use crlfile to point to the PEM encoded revocation file. #crlfile # To allow the use of ephemeral DH key exchange, which provides forward # security, the listener must load DH parameters. This can be specified with # the dhparamfile option. The dhparamfile can be generated with the command # e.g. "openssl dhparam -out dhparam.pem 2048" #dhparamfile # By default an TLS enabled listener will operate in a similar fashion to a # https enabled web server, in that the server has a certificate signed by a CA # and the client will verify that it is a trusted certificate. The overall aim # is encryption of the network traffic. By setting require_certificate to true, # the client must provide a valid certificate in order for the network # connection to proceed. This allows access to the broker to be controlled # outside of the mechanisms provided by MQTT. #require_certificate false # If require_certificate is true, you may set use_identity_as_username to true # to use the CN value from the client certificate as a username. If this is # true, the password_file option will not be used for this listener. #use_identity_as_username false # ----------------------------------------------------------------- # Pre-shared-key based SSL/TLS support # ----------------------------------------------------------------- # The following options can be used to enable PSK based SSL/TLS support for # this listener. Note that the recommended port for MQTT over TLS is 8883, but # this must be set manually. # # See also the mosquitto-tls man page and the "Certificate based SSL/TLS # support" section. Only one of certificate or PSK encryption support can be # enabled for any listener. # The psk_hint option enables pre-shared-key support for this listener and also # acts as an identifier for this listener. The hint is sent to clients and may # be used locally to aid authentication. The hint is a free form string that # doesn't have much meaning in itself, so feel free to be creative. # If this option is provided, see psk_file to define the pre-shared keys to be # used or create a security plugin to handle them. #psk_hint # When using PSK, the encryption ciphers used will be chosen from the list of # available PSK ciphers. If you want to control which ciphers are available, # use the "ciphers" option. The list of available ciphers can be optained # using the "openssl ciphers" command and should be provided in the same format # as the output of that command. #ciphers # Set use_identity_as_username to have the psk identity sent by the client used # as its username. Authentication will be carried out using the PSK rather than # the MQTT username/password and so password_file will not be used for this # listener. #use_identity_as_username false # ================================================================= # Persistence # ================================================================= # If persistence is enabled, save the in-memory database to disk # every autosave_interval seconds. If set to 0, the persistence # database will only be written when mosquitto exits. See also # autosave_on_changes. # Note that writing of the persistence database can be forced by # sending mosquitto a SIGUSR1 signal. #autosave_interval 1800 # If true, mosquitto will count the number of subscription changes, retained # messages received and queued messages and if the total exceeds # autosave_interval then the in-memory database will be saved to disk. # If false, mosquitto will save the in-memory database to disk by treating # autosave_interval as a time in seconds. #autosave_on_changes false # Save persistent message data to disk (true/false). # This saves information about all messages, including # subscriptions, currently in-flight messages and retained # messages. # retained_persistence is a synonym for this option. #persistence false # The filename to use for the persistent database, not including # the path. #persistence_file mosquitto.db # Location for persistent database. Must include trailing / # Default is an empty string (current directory). # Set to e.g. /var/lib/mosquitto/ if running as a proper service on Linux or # similar. #persistence_location # ================================================================= # Logging # ================================================================= # Places to log to. Use multiple log_dest lines for multiple # logging destinations. # Possible destinations are: stdout stderr syslog topic file # # stdout and stderr log to the console on the named output. # # syslog uses the userspace syslog facility which usually ends up # in /var/log/messages or similar. # # topic logs to the broker topic '$SYS/broker/log/', # where severity is one of D, E, W, N, I, M which are debug, error, # warning, notice, information and message. Message type severity is used by # the subscribe/unsubscribe log_types and publishes log messages to # $SYS/broker/log/M/susbcribe or $SYS/broker/log/M/unsubscribe. # # The file destination requires an additional parameter which is the file to be # logged to, e.g. "log_dest file /var/log/mosquitto.log". The file will be # closed and reopened when the broker receives a HUP signal. Only a single file # destination may be configured. # # Note that if the broker is running as a Windows service it will default to # "log_dest none" and neither stdout nor stderr logging is available. # Use "log_dest none" if you wish to disable logging. #log_dest stderr # Types of messages to log. Use multiple log_type lines for logging # multiple types of messages. # Possible types are: debug, error, warning, notice, information, # none, subscribe, unsubscribe, websockets, all. # Note that debug type messages are for decoding the incoming/outgoing # network packets. They are not logged in "topics". #log_type error #log_type warning #log_type notice #log_type information # If set to true, client connection and disconnection messages will be included # in the log. #connection_messages true # If using syslog logging (not on Windows), messages will be logged to the # "daemon" facility by default. Use the log_facility option to choose which of # local0 to local7 to log to instead. The option value should be an integer # value, e.g. "log_facility 5" to use local5. #log_facility # If set to true, add a timestamp value to each log message. #log_timestamp true # Set the format of the log timestamp. If left unset, this is the number of # seconds since the Unix epoch. # This is a free text string which will be passed to the strftime function. To # get an ISO 8601 datetime, for example: # log_timestamp_format %Y-%m-%dT%H:%M:%S #log_timestamp_format # Change the websockets logging level. This is a global option, it is not # possible to set per listener. This is an integer that is interpreted by # libwebsockets as a bit mask for its lws_log_levels enum. See the # libwebsockets documentation for more details. "log_type websockets" must also # be enabled. #websockets_log_level 0 # ================================================================= # Security # ================================================================= # If set, only clients that have a matching prefix on their # clientid will be allowed to connect to the broker. By default, # all clients may connect. # For example, setting "secure-" here would mean a client "secure- # client" could connect but another with clientid "mqtt" couldn't. #clientid_prefixes # Boolean value that determines whether clients that connect # without providing a username are allowed to connect. If set to # false then a password file should be created (see the # password_file option) to control authenticated client access. # # Defaults to true if no other security options are set. If `password_file` or # `psk_file` is set, or if an authentication plugin is loaded which implements # username/password or TLS-PSK checks, then `allow_anonymous` defaults to # false. # #allow_anonymous true # ----------------------------------------------------------------- # Default authentication and topic access control # ----------------------------------------------------------------- # Control access to the broker using a password file. This file can be # generated using the mosquitto_passwd utility. If TLS support is not compiled # into mosquitto (it is recommended that TLS support should be included) then # plain text passwords are used, in which case the file should be a text file # with lines in the format: # username:password # The password (and colon) may be omitted if desired, although this # offers very little in the way of security. # # See the TLS client require_certificate and use_identity_as_username options # for alternative authentication options. If an auth_plugin is used as well as # password_file, the auth_plugin check will be made first. #password_file # Access may also be controlled using a pre-shared-key file. This requires # TLS-PSK support and a listener configured to use it. The file should be text # lines in the format: # identity:key # The key should be in hexadecimal format without a leading "0x". # If an auth_plugin is used as well, the auth_plugin check will be made first. #psk_file # Control access to topics on the broker using an access control list # file. If this parameter is defined then only the topics listed will # have access. # If the first character of a line of the ACL file is a # it is treated as a # comment. # Topic access is added with lines of the format: # # topic [read|write|readwrite] # # The access type is controlled using "read", "write" or "readwrite". This # parameter is optional (unless contains a space character) - if not # given then the access is read/write. can contain the + or # # wildcards as in subscriptions. # # The first set of topics are applied to anonymous clients, assuming # allow_anonymous is true. User specific topic ACLs are added after a # user line as follows: # # user # # The username referred to here is the same as in password_file. It is # not the clientid. # # # If is also possible to define ACLs based on pattern substitution within the # topic. The patterns available for substition are: # # %c to match the client id of the client # %u to match the username of the client # # The substitution pattern must be the only text for that level of hierarchy. # # The form is the same as for the topic keyword, but using pattern as the # keyword. # Pattern ACLs apply to all users even if the "user" keyword has previously # been given. # # If using bridges with usernames and ACLs, connection messages can be allowed # with the following pattern: # pattern write $SYS/broker/connection/%c/state # # pattern [read|write|readwrite] # # Example: # # pattern write sensor/%u/data # # If an auth_plugin is used as well as acl_file, the auth_plugin check will be # made first. #acl_file # ----------------------------------------------------------------- # External authentication and topic access plugin options # ----------------------------------------------------------------- # External authentication and access control can be supported with the # auth_plugin option. This is a path to a loadable plugin. See also the # auth_opt_* options described below. # # The auth_plugin option can be specified multiple times to load multiple # plugins. The plugins will be processed in the order that they are specified # here. If the auth_plugin option is specified alongside either of # password_file or acl_file then the plugin checks will be made first. # #auth_plugin # If the auth_plugin option above is used, define options to pass to the # plugin here as described by the plugin instructions. All options named # using the format auth_opt_* will be passed to the plugin, for example: # # auth_opt_db_host # auth_opt_db_port # auth_opt_db_username # auth_opt_db_password # ================================================================= # Bridges # ================================================================= # A bridge is a way of connecting multiple MQTT brokers together. # Create a new bridge using the "connection" option as described below. Set # options for the bridges using the remaining parameters. You must specify the # address and at least one topic to subscribe to. # # Each connection must have a unique name. # # The address line may have multiple host address and ports specified. See # below in the round_robin description for more details on bridge behaviour if # multiple addresses are used. Note that if you use an IPv6 address, then you # are required to specify a port. # # The direction that the topic will be shared can be chosen by # specifying out, in or both, where the default value is out. # The QoS level of the bridged communication can be specified with the next # topic option. The default QoS level is 0, to change the QoS the topic # direction must also be given. # # The local and remote prefix options allow a topic to be remapped when it is # bridged to/from the remote broker. This provides the ability to place a topic # tree in an appropriate location. # # For more details see the mosquitto.conf man page. # # Multiple topics can be specified per connection, but be careful # not to create any loops. # # If you are using bridges with cleansession set to false (the default), then # you may get unexpected behaviour from incoming topics if you change what # topics you are subscribing to. This is because the remote broker keeps the # subscription for the old topic. If you have this problem, connect your bridge # with cleansession set to true, then reconnect with cleansession set to false # as normal. #connection #address [:] [[:]] #topic [[[out | in | both] qos-level] local-prefix remote-prefix] # If a bridge has topics that have "out" direction, the default behaviour is to # send an unsubscribe request to the remote broker on that topic. This means # that changing a topic direction from "in" to "out" will not keep receiving # incoming messages. Sending these unsubscribe requests is not always # desirable, setting bridge_attempt_unsubscribe to false will disable sending # the unsubscribe request. #bridge_attempt_unsubscribe true # Set the version of the MQTT protocol to use with for this bridge. Can be one # of mqttv311 or mqttv11. Defaults to mqttv311. #bridge_protocol_version mqttv311 # Set the clean session variable for this bridge. # When set to true, when the bridge disconnects for any reason, all # messages and subscriptions will be cleaned up on the remote # broker. Note that with cleansession set to true, there may be a # significant amount of retained messages sent when the bridge # reconnects after losing its connection. # When set to false, the subscriptions and messages are kept on the # remote broker, and delivered when the bridge reconnects. #cleansession false # Set the amount of time a bridge using the lazy start type must be idle before # it will be stopped. Defaults to 60 seconds. #idle_timeout 60 # Set the keepalive interval for this bridge connection, in # seconds. #keepalive_interval 60 # Set the clientid to use on the local broker. If not defined, this defaults to # 'local.'. If you are bridging a broker to itself, it is important # that local_clientid and clientid do not match. #local_clientid # If set to true, publish notification messages to the local and remote brokers # giving information about the state of the bridge connection. Retained # messages are published to the topic $SYS/broker/connection//state # unless the notification_topic option is used. # If the message is 1 then the connection is active, or 0 if the connection has # failed. # This uses the last will and testament feature. #notifications true # Choose the topic on which notification messages for this bridge are # published. If not set, messages are published on the topic # $SYS/broker/connection//state #notification_topic # Set the client id to use on the remote end of this bridge connection. If not # defined, this defaults to 'name.hostname' where name is the connection name # and hostname is the hostname of this computer. # This replaces the old "clientid" option to avoid confusion. "clientid" # remains valid for the time being. #remote_clientid # Set the password to use when connecting to a broker that requires # authentication. This option is only used if remote_username is also set. # This replaces the old "password" option to avoid confusion. "password" # remains valid for the time being. #remote_password # Set the username to use when connecting to a broker that requires # authentication. # This replaces the old "username" option to avoid confusion. "username" # remains valid for the time being. #remote_username # Set the amount of time a bridge using the automatic start type will wait # until attempting to reconnect. # This option can be configured to use a constant delay time in seconds, or to # use a backoff mechanism based on "Decorrelated Jitter", which adds a degree # of randomness to when the restart occurs. # # Set a constant timeout of 20 seconds: # restart_timeout 20 # # Set backoff with a base (start value) of 10 seconds and a cap (upper limit) of # 60 seconds: # restart_timeout 10 30 # # Defaults to jitter with a base of 5 and cap of 30 #restart_timeout 5 30 # If the bridge has more than one address given in the address/addresses # configuration, the round_robin option defines the behaviour of the bridge on # a failure of the bridge connection. If round_robin is false, the default # value, then the first address is treated as the main bridge connection. If # the connection fails, the other secondary addresses will be attempted in # turn. Whilst connected to a secondary bridge, the bridge will periodically # attempt to reconnect to the main bridge until successful. # If round_robin is true, then all addresses are treated as equals. If a # connection fails, the next address will be tried and if successful will # remain connected until it fails #round_robin false # Set the start type of the bridge. This controls how the bridge starts and # can be one of three types: automatic, lazy and once. Note that RSMB provides # a fourth start type "manual" which isn't currently supported by mosquitto. # # "automatic" is the default start type and means that the bridge connection # will be started automatically when the broker starts and also restarted # after a short delay (30 seconds) if the connection fails. # # Bridges using the "lazy" start type will be started automatically when the # number of queued messages exceeds the number set with the "threshold" # parameter. It will be stopped automatically after the time set by the # "idle_timeout" parameter. Use this start type if you wish the connection to # only be active when it is needed. # # A bridge using the "once" start type will be started automatically when the # broker starts but will not be restarted if the connection fails. #start_type automatic # Set the number of messages that need to be queued for a bridge with lazy # start type to be restarted. Defaults to 10 messages. # Must be less than max_queued_messages. #threshold 10 # If try_private is set to true, the bridge will attempt to indicate to the # remote broker that it is a bridge not an ordinary client. If successful, this # means that loop detection will be more effective and that retained messages # will be propagated correctly. Not all brokers support this feature so it may # be necessary to set try_private to false if your bridge does not connect # properly. #try_private true # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- # Either bridge_cafile or bridge_capath must be defined to enable TLS support # for this bridge. # bridge_cafile defines the path to a file containing the # Certificate Authority certificates that have signed the remote broker # certificate. # bridge_capath defines a directory that will be searched for files containing # the CA certificates. For bridge_capath to work correctly, the certificate # files must have ".crt" as the file ending and you must run "openssl rehash # " each time you add/remove a certificate. #bridge_cafile #bridge_capath # If the remote broker has more than one protocol available on its port, e.g. # MQTT and WebSockets, then use bridge_alpn to configure which protocol is # requested. Note that WebSockets support for bridges is not yet available. #bridge_alpn # When using certificate based encryption, bridge_insecure disables # verification of the server hostname in the server certificate. This can be # useful when testing initial server configurations, but makes it possible for # a malicious third party to impersonate your server through DNS spoofing, for # example. Use this option in testing only. If you need to resort to using this # option in a production environment, your setup is at fault and there is no # point using encryption. #bridge_insecure false # Path to the PEM encoded client certificate, if required by the remote broker. #bridge_certfile # Path to the PEM encoded client private key, if required by the remote broker. #bridge_keyfile # ----------------------------------------------------------------- # PSK based SSL/TLS support # ----------------------------------------------------------------- # Pre-shared-key encryption provides an alternative to certificate based # encryption. A bridge can be configured to use PSK with the bridge_identity # and bridge_psk options. These are the client PSK identity, and pre-shared-key # in hexadecimal format with no "0x". Only one of certificate and PSK based # encryption can be used on one # bridge at once. #bridge_identity #bridge_psk # ================================================================= # External config files # ================================================================= # External configuration files may be included by using the # include_dir option. This defines a directory that will be searched # for config files. All files that end in '.conf' will be loaded as # a configuration file. It is best to have this as the last option # in the main file. This option will only be processed from the main # configuration file. The directory specified must not contain the # main configuration file. # Files within include_dir will be loaded sorted in case-sensitive # alphabetical order, with capital letters ordered first. If this option is # given multiple times, all of the files from the first instance will be # processed before the next instance. See the man page for examples. #include_dir mosquitto-1.6.9/readme-windows.txt0000664000175000017500000000476613626052637016330 0ustar rogerrogerMosquitto for Windows ===================== Mosquitto for Windows comes in 32-bit and 64-bit flavours. In both cases, the dependencies are not provided in this installer and must be installed separately in the case that they are not already available. Capabilities ------------ Some versions of Windows have limitations on the number of concurrent connections, set at approximately 2048 connections depending on the version of Windows you are using. Websockets ---------- The broker executables provided in the installers have Websockets support through a statically compiled version of libwebsockets and is being distributed under the Static Linking Exception (Section 2) of the License. As a result, the content is not subject to the LGPL 2.1. Please note that on Windows, libwebsockets limits connections to a maximum of 64 clients. Library Thread Support ---------------------- libmosquitto on Windows is currently compiled without thread support, so neither of mosquitto_loop_start() nor "mosquitto_pub -l" are available. A better solution that the old pthreads-win32 is being looked into, so support will return in the future. If you need thread support, the code still supports it just fine. Support has been dropped to simplify installation. Dependencies ------------ * OpenSSL Link: http://slproweb.com/products/Win32OpenSSL.html Install "Win32 OpenSSL 1.1.0* Light" or "Win64 OpenSSL 1.1.0* Light" Required DLLs: libssl-1_1.dll, libcrypto-1_1.dll or libssl-1_1-x64.dll, libcrypto-1_1-x64.dll Please ensure that the required DLLs are on the system path, or are in the same directory as the mosquitto executable - usually C:\Program Files (x86)\mosquitto or C:\Program Files\mosquitto. Windows Service --------------- If you wish, mosquitto can be installed as a Windows service so you can start/stop it from the control panel as well as running it as a normal executable. When running as a service, the configuration file used is mosquitto.conf in the directory that you installed to. If you want to install/uninstall mosquitto as a Windows service run from the command line as follows: C:\Program Files\mosquitto\mosquitto install C:\Program Files\mosquitto\mosquitto uninstall Logging ------- If you use `log_dest file ...` in your configuration, the log file will be created with security permissions for the current user only. If running as a service, this means the SYSTEM user. You will only be able to view the log file if you add permissions for yourself or whatever user you wish to view the logs. mosquitto-1.6.9/man/0000775000175000017500000000000013626052637013400 5ustar rogerrogermosquitto-1.6.9/man/mosquitto.80000664000175000017500000003416213626052637015543 0ustar rogerroger'\" t .\" Title: mosquitto .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: System management commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO" "8" "02/27/2020" "Mosquitto Project" "System management commands" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto \- an MQTT broker .SH "SYNOPSIS" .HP \w'\fBmosquitto\fR\ 'u \fBmosquitto\fR [\-c\ \fIconfig\ file\fR] [\-d | \-\-daemon] [\-p\ \fIport\ number\fR] [\-v] .SH "DESCRIPTION" .PP \fBmosquitto\fR is a broker for the MQTT protocol version 3\&.1\&.1/3\&.1\&. .SH "OPTIONS" .PP \fB\-c\fR, \fB\-\-config\-file\fR .RS 4 Load configuration from a file\&. If not given, the default values as described in \fBmosquitto.conf\fR(5) are used\&. .RE .PP \fB\-d\fR, \fB\-\-daemon\fR .RS 4 Run \fBmosquitto\fR in the background as a daemon\&. All other behaviour remains the same\&. .RE .PP \fB\-p\fR, \fB\-\-port\fR .RS 4 Listen on the port specified instead of the default 1883\&. This acts in addition to the port setting in the config file\&. May be specified multiple times to open multiple sockets listening on different ports\&. This socket will be bound to all network interfaces\&. .RE .PP \fB\-v\fR, \fB\-\-verbose\fR .RS 4 Use verbose logging\&. This is equivalent to setting \fBlog_type\fR to \fBall\fR in the configuration file\&. This overrides and logging options given in the configuration file\&. .RE .SH "CONFIGURATION" .PP The broker can be configured using a configuration file as described in \fBmosquitto.conf\fR(5) and this is the main point of information for mosquitto\&. The files required for SSL/TLS support are described in \fBmosquitto-tls\fR(7)\&. .SH "BROKER STATUS" .PP Clients can find information about the broker by subscribing to topics in the $SYS hierarchy as follows\&. Topics marked as static are only sent once per client on subscription\&. All other topics are updated every \fBsys_interval\fR seconds\&. If \fBsys_interval\fR is 0, then updates are not sent\&. .PP Note that if you are using a command line client to interact with the $SYS topics and your shell interprets $ as an environment variable, you need to place the topic in single quotes \*(Aq$SYS/\&.\&.\&.\*(Aq or to escape the dollar symbol: \e$SYS/\&.\&.\&. otherwise the $SYS will be treated as an environment variable\&. .PP \fB$SYS/broker/bytes/received\fR .RS 4 The total number of bytes received since the broker started\&. .RE .PP \fB$SYS/broker/bytes/sent\fR .RS 4 The total number of bytes sent since the broker started\&. .RE .PP \fB$SYS/broker/clients/connected\fR, \fB$SYS/broker/clients/active\fR (deprecated) .RS 4 The number of currently connected clients\&. .RE .PP \fB$SYS/broker/clients/expired\fR .RS 4 The number of disconnected persistent clients that have been expired and removed through the persistent_client_expiration option\&. .RE .PP \fB$SYS/broker/clients/disconnected\fR, \fB$SYS/broker/clients/inactive\fR (deprecated) .RS 4 The total number of persistent clients (with clean session disabled) that are registered at the broker but are currently disconnected\&. .RE .PP \fB$SYS/broker/clients/maximum\fR .RS 4 The maximum number of clients that have been connected to the broker at the same time\&. .RE .PP \fB$SYS/broker/clients/total\fR .RS 4 The total number of active and inactive clients currently connected and registered on the broker\&. .RE .PP \fB$SYS/broker/connection/#\fR .RS 4 When bridges are configured to/from the broker, common practice is to provide a status topic that indicates the state of the connection\&. This is provided within $SYS/broker/connection/ by default\&. If the value of the topic is 1 the connection is active, if 0 then it is not active\&. See the Bridges section below for more information on bridges\&. .RE .PP \fB$SYS/broker/heap/current size\fR .RS 4 The current size of the heap memory in use by mosquitto\&. Note that this topic may be unavailable depending on compile time options\&. .RE .PP \fB$SYS/broker/heap/maximum size\fR .RS 4 The largest amount of heap memory used by mosquitto\&. Note that this topic may be unavailable depending on compile time options\&. .RE .PP \fB$SYS/broker/load/connections/+\fR .RS 4 The moving average of the number of CONNECT packets received by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of connections received in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/bytes/received/+\fR .RS 4 The moving average of the number of bytes received by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of bytes received in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/bytes/sent/+\fR .RS 4 The moving average of the number of bytes sent by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of bytes sent in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/messages/received/+\fR .RS 4 The moving average of the number of all types of MQTT messages received by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of messages received in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/messages/sent/+\fR .RS 4 The moving average of the number of all types of MQTT messages sent by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of messages send in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/publish/dropped/+\fR .RS 4 The moving average of the number of publish messages dropped by the broker over different time intervals\&. This shows the rate at which durable clients that are disconnected are losing messages\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of messages dropped in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/publish/received/+\fR .RS 4 The moving average of the number of publish messages received by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of publish messages received in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/publish/sent/+\fR .RS 4 The moving average of the number of publish messages sent by the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of publish messages sent in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/load/sockets/+\fR .RS 4 The moving average of the number of socket connections opened to the broker over different time intervals\&. The final "+" of the hierarchy can be 1min, 5min or 15min\&. The value returned represents the number of socket connections in 1 minute, averaged over 1, 5 or 15 minutes\&. .RE .PP \fB$SYS/broker/messages/inflight\fR .RS 4 The number of messages with QoS>0 that are awaiting acknowledgments\&. .RE .PP \fB$SYS/broker/messages/received\fR .RS 4 The total number of messages of any type received since the broker started\&. .RE .PP \fB$SYS/broker/messages/sent\fR .RS 4 The total number of messages of any type sent since the broker started\&. .RE .PP \fB$SYS/broker/publish/messages/dropped\fR .RS 4 The total number of publish messages that have been dropped due to inflight/queuing limits\&. See the max_inflight_messages and max_queued_messages options in \fBmosquitto.conf\fR(5) for more information\&. .RE .PP \fB$SYS/broker/publish/messages/received\fR .RS 4 The total number of PUBLISH messages received since the broker started\&. .RE .PP \fB$SYS/broker/publish/messages/sent\fR .RS 4 The total number of PUBLISH messages sent since the broker started\&. .RE .PP \fB$SYS/broker/retained messages/count\fR .RS 4 The total number of retained messages active on the broker\&. .RE .PP \fB$SYS/broker/store/messages/count\fR, \fB$SYS/broker/messages/stored\fR (deprecated) .RS 4 The number of messages currently held in the message store\&. This includes retained messages and messages queued for durable clients\&. .RE .PP \fB$SYS/broker/store/messages/bytes\fR .RS 4 The number of bytes currently held by message payloads in the message store\&. This includes retained messages and messages queued for durable clients\&. .RE .PP \fB$SYS/broker/subscriptions/count\fR .RS 4 The total number of subscriptions active on the broker\&. .RE .PP \fB$SYS/broker/version\fR .RS 4 The version of the broker\&. Static\&. .RE .SH "WILDCARD TOPIC SUBSCRIPTIONS" .PP In addition to allowing clients to subscribe to specific topics, mosquitto also allows the use of two wildcards in subscriptions\&. \fB+\fR is the wildcard used to match a single level of hierarchy\&. For example, for a topic of "a/b/c/d", the following example subscriptions will match: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/b/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/+/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/+/+/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/+/+/+ .RE .PP The following subscriptions will not match: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} b/+/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/+/+ .RE .PP The second wildcard is \fB#\fR and is used to match all subsequent levels of hierarchy\&. With a topic of "a/b/c/d", the following example subscriptions will match: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} # .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/# .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/# .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c/# .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/b/c/# .RE .PP The $SYS hierarchy does not match a subscription of "#"\&. If you want to observe the entire $SYS hierarchy, subscribe to $SYS/#\&. .PP Note that the wildcards must be only ever used on their own, so a subscription of "a/b+/c" is not valid use of a wildcard\&. The \fB#\fR wildcard must only ever be used as the final character of a subscription\&. .SH "BRIDGES" .PP Multiple brokers can be connected together with the bridging functionality\&. This is useful where it is desirable to share information between locations, but where not all of the information needs to be shared\&. An example could be where a number of users are running a broker to help record power usage and for a number of other reasons\&. The power usage could be shared through bridging all of the user brokers to a common broker, allowing the power usage of all users to be collected and compared\&. The other information would remain local to each broker\&. .PP For information on configuring bridges, see \fBmosquitto.conf\fR(5)\&. .SH "SIGNALS" .PP SIGHUP .RS 4 Upon receiving the SIGHUP signal, mosquitto will attempt to reload configuration file data, assuming that the \fB\-c\fR argument was provided when mosquitto was started\&. Not all configuration parameters can be reloaded without restarting\&. See \fBmosquitto.conf\fR(5) for details\&. .RE .PP SIGUSR1 .RS 4 Upon receiving the SIGUSR1 signal, mosquitto will write the persistence database to disk\&. This signal is only acted upon if persistence is enabled\&. .RE .PP SIGUSR2 .RS 4 The SIGUSR2 signal causes mosquitto to print out the current subscription tree, along with information about where retained messages exist\&. This is intended as a testing feature only and may be removed at any time\&. .RE .SH "FILES" .PP /etc/mosquitto/mosquitto\&.conf .RS 4 Configuration file\&. See \fBmosquitto.conf\fR(5)\&. .RE .PP /var/lib/mosquitto/mosquitto\&.db .RS 4 Persistent message data storage location if persist enabled\&. .RE .PP /etc/hosts\&.allow, /etc/hosts\&.deny .RS 4 Host access control via tcp\-wrappers as described in \fBhosts_access\fR(5)\&. .RE .SH "BUGS" .PP \fBmosquitto\fR bug information can be found at \m[blue]\fB\%https://github.com/eclipse/mosquitto/issues\fR\m[] .SH "SEE ALSO" \fBmqtt\fR(7), \fBmosquitto-tls\fR(7), \fBmosquitto.conf\fR(5), \fBhosts_access\fR(5), \fBmosquitto_passwd\fR(1), \fBmosquitto_pub\fR(1), \fBmosquitto_rr\fR(1), \fBmosquitto_sub\fR(1), \fBlibmosquitto\fR(3) .SH "THANKS" .PP Thanks to Andy Stanford\-Clark for being one of the people who came up with MQTT in the first place\&. Thanks to Andy and Nicholas O\*(AqLeary for providing clarifications of the protocol\&. .PP Thanks also to everybody at the Ubuntu UK Podcast and Linux Outlaws for organising OggCamp, where Andy gave a talk that inspired mosquitto\&. .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/mosquitto_sub.1.meta0000664000175000017500000000015513626052637017325 0ustar rogerroger.. title: mosquitto_sub man page .. slug: mosquitto_sub-1 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/mqtt.7.xml0000664000175000017500000002031613626052637015256 0ustar rogerroger mqtt 7 Mosquitto Project Conventions and miscellaneous mqtt MQ Telemetry Transport MQTT Description MQTT is a lightweight publish/subscribe messaging protocol. It is useful for use with low power sensors, but is applicable to many scenarios. This manual describes some of the features of MQTT version 3.1.1/3.1, to assist end users in getting the most out of the protocol. For more complete information on MQTT, see http://mqtt.org/. Publish/Subscribe The MQTT protocol is based on the principle of publishing messages and subscribing to topics, or "pub/sub". Multiple clients connect to a broker and subscribe to topics that they are interested in. Clients also connect to the broker and publish messages to topics. Many clients may subscribe to the same topics and do with the information as they please. The broker and MQTT act as a simple, common interface for everything to connect to. This means that you if you have clients that dump subscribed messages to a database, to Twitter, Cosm or even a simple text file, then it becomes very simple to add new sensors or other data input to a database, Twitter or so on. Topics/Subscriptions Messages in MQTT are published on topics. There is no need to configure a topic, publishing on it is enough. Topics are treated as a hierarchy, using a slash (/) as a separator. This allows sensible arrangement of common themes to be created, much in the same way as a filesystem. For example, multiple computers may all publish their hard drive temperature information on the following topic, with their own computer and hard drive name being replaced as appropriate: sensors/COMPUTER_NAME/temperature/HARDDRIVE_NAME Clients can receive messages by creating subscriptions. A subscription may be to an explicit topic, in which case only messages to that topic will be received, or it may include wildcards. Two wildcards are available, or . can be used as a wildcard for a single level of hierarchy. It could be used with the topic above to get information on all computers and hard drives as follows: sensors/+/temperature/+ As another example, for a topic of "a/b/c/d", the following example subscriptions will match: a/b/c/d +/b/c/d a/+/c/d a/+/+/d +/+/+/+ The following subscriptions will not match: a/b/c b/+/c/d +/+/+ can be used as a wildcard for all remaining levels of hierarchy. This means that it must be the final character in a subscription. With a topic of "a/b/c/d", the following example subscriptions will match: a/b/c/d # a/# a/b/# a/b/c/# +/b/c/# Zero length topic levels are valid, which can lead to some slightly non-obvious behaviour. For example, a topic of "a//topic" would correctly match against a subscription of "a/+/topic". Likewise, zero length topic levels can exist at both the beginning and the end of a topic string, so "/a/topic" would match against a subscription of "+/a/topic", "#" or "/#", and a topic "a/topic/" would match against a subscription of "a/topic/+" or "a/topic/#". Quality of Service MQTT defines three levels of Quality of Service (QoS). The QoS defines how hard the broker/client will try to ensure that a message is received. Messages may be sent at any QoS level, and clients may attempt to subscribe to topics at any QoS level. This means that the client chooses the maximum QoS it will receive. For example, if a message is published at QoS 2 and a client is subscribed with QoS 0, the message will be delivered to that client with QoS 0. If a second client is also subscribed to the same topic, but with QoS 2, then it will receive the same message but with QoS 2. For a second example, if a client is subscribed with QoS 2 and a message is published on QoS 0, the client will receive it on QoS 0. Higher levels of QoS are more reliable, but involve higher latency and have higher bandwidth requirements. 0: The broker/client will deliver the message once, with no confirmation. 1: The broker/client will deliver the message at least once, with confirmation required. 2: The broker/client will deliver the message exactly once by using a four step handshake. Retained Messages All messages may be set to be retained. This means that the broker will keep the message even after sending it to all current subscribers. If a new subscription is made that matches the topic of the retained message, then the message will be sent to the client. This is useful as a "last known good" mechanism. If a topic is only updated infrequently, then without a retained message, a newly subscribed client may have to wait a long time to receive an update. With a retained message, the client will receive an instant update. Clean session / Durable connections On connection, a client sets the "clean session" flag, which is sometimes also known as the "clean start" flag. If clean session is set to false, then the connection is treated as durable. This means that when the client disconnects, any subscriptions it has will remain and any subsequent QoS 1 or 2 messages will be stored until it connects again in the future. If clean session is true, then all subscriptions will be removed for the client when it disconnects. Wills When a client connects to a broker, it may inform the broker that it has a will. This is a message that it wishes the broker to send when the client disconnects unexpectedly. The will message has a topic, QoS and retain status just the same as any other message. See Also mosquitto 8 mosquitto_pub 1 mosquitto_sub 1 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mosquitto-tls.70000664000175000017500000001021613626052637016334 0ustar rogerroger'\" t .\" Title: mosquitto-tls .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Conventions and miscellaneous .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO\-TLS" "7" "02/27/2020" "Mosquitto Project" "Conventions and miscellaneous" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto-tls \- Configure SSL/TLS support for Mosquitto .SH "DESCRIPTION" .PP \fBmosquitto\fR provides SSL support for encrypted network connections and authentication\&. This manual describes how to create the files needed\&. .if n \{\ .sp .\} .RS 4 .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBNote\fR .ps -1 .br .PP It is important to use different certificate subject parameters for your CA, server and clients\&. If the certificates appear identical, even though generated separately, the broker/client will not be able to distinguish between them and you will experience difficult to diagnose errors\&. .sp .5v .RE .SH "GENERATING CERTIFICATES" .PP The sections below give the openssl commands that can be used to generate certificates, but without any context\&. The asciicast at \m[blue]\fBhttps://asciinema\&.org/a/201826\fR\m[] gives a full run through of how to use those commands\&. .SH "CERTIFICATE AUTHORITY" .PP Generate a certificate authority certificate and key\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl req \-new \-x509 \-days \-extensions v3_ca \-keyout ca\&.key \-out ca\&.crt .RE .SH "SERVER" .PP Generate a server key\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl genrsa \-des3 \-out server\&.key 2048 .RE .PP Generate a server key without encryption\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl genrsa \-out server\&.key 2048 .RE .PP Generate a certificate signing request to send to the CA\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl req \-out server\&.csr \-key server\&.key \-new .RE .if n \{\ .sp .\} .RS 4 .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBNote\fR .ps -1 .br .PP When prompted for the CN (Common Name), please enter either your server (or broker) hostname or domain name\&. .sp .5v .RE .PP Send the CSR to the CA, or sign it with your CA key: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl x509 \-req \-in server\&.csr \-CA ca\&.crt \-CAkey ca\&.key \-CAcreateserial \-out server\&.crt \-days .RE .SH "CLIENT" .PP Generate a client key\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl genrsa \-des3 \-out client\&.key 2048 .RE .PP Generate a certificate signing request to send to the CA\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl req \-out client\&.csr \-key client\&.key \-new .RE .PP Send the CSR to the CA, or sign it with your CA key: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} openssl x509 \-req \-in client\&.csr \-CA ca\&.crt \-CAkey ca\&.key \-CAcreateserial \-out client\&.crt \-days .RE .SH "SEE ALSO" \fBmosquitto\fR(8), \fBmosquitto-conf\fR(5) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/mosquitto_pub.1.xml0000664000175000017500000007447513626052637017214 0ustar rogerroger mosquitto_pub 1 Mosquitto Project Commands mosquitto_pub an MQTT version 5/3.1.1/3.1 client for publishing simple messages mosquitto_pub hostname port-number username password message-topic URL bind-address command identifier value client-id client-id-prefix keepalive-time message-QoS count seconds file message topic payload qos file dir file file ciphers version protocol engine pem engine kpass-sha1 hex-key identity ciphers version socks-url protocol-version mosquitto_pub Description mosquitto_pub is a simple MQTT version 5/3.1.1 client that will publish a single message on a topic and exit. Encrypted Connections mosquitto_pub supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup. To enable TLS connections when using x509 certificates, one of either or must be provided as an option. To enable TLS connections when using TLS-PSK, you must use the and the options. Options The options below may be given on the command line, but may also be placed in a config file located at or with one pair of per line. The values in the config file will be used as defaults and can be overridden by using the command line. The exceptions to this are the message type options, of which only one can be specified. Note also that currently some options cannot be negated, e.g. . Config file lines that have a as the first character are treated as comments and not processed any further. Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface. Disable the 'clean session' flag. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive. When the client reconnects, it will receive all of the queued messages. If using this option, the client id must be set manually with Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. See also Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. For to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a certificate. See also Define the path to a file containing a PEM encoded certificate for this client, if required by the server. See also . An openssl compatible list of TLS ciphers to support in the client. See ciphers1 for more information. Enable debug messages. Use an MQTT v5 property with this publish. If you use this option, the client will be set to be an MQTT v5 client. This option has two forms: is the MQTT command/packet identifier and can be one of CONNECT, PUBLISH, PUBREL, DISCONNECT, AUTH, or WILL. The properties available for each command are listed in the Properties section. is the name of the property to add. This is as described in the specification, but with '-' as a word separator. For example: . More details are in the Properties section. is the value of the property to add, with a data type that is property specific. is only used for the property as the first of the two strings in the string pair. In that case, is the second of the strings in the pair. Send the contents of a file as the message. Display usage information. Specify the host to connect to. Defaults to localhost. The id to use for this client. If not given, a client id will be generated depending on the MQTT version being used. For v3.1.1/v3.1, the client generates a client id in the format , where the are replaced with random alphanumeric characters. For v5.0, the client sends a zero length client id, and the server will generate a client id for the client. This option cannot be used at the same time as the argument. Provide a prefix that the client id will be built from by appending the process id of the client. This is useful where the broker is using the clientid_prefixes option. Cannot be used at the same time as the argument. When using certificate based encryption, this option disables verification of the server hostname in the server certificate. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only. If you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption. The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. Defaults to 60 seconds. Define the path to a file containing a PEM encoded private key for this client, if required by the server. See also . Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the private key has been created with it. Defaults to "pem", which means normal private key files are used. See also . Specify specify user, password, hostname, port and topic at once as a URL. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883. Send messages read from stdin, splitting separate lines into separate messages. Send a single message from the command line. Send a null (zero length) message. Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used. Provide a password to be used for authenticating with the broker. Using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. See also the option. Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The must be of the form . The protocol prefix means that hostnames are resolved by the proxy. The symbols %25, %3A and %40 are URL decoded into %, : and @ respectively, if present in the username or password. If username is not given, then no authentication is attempted. If the port is not given, then the default of 1080 is used. More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl 1 . Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support. must also be provided to enable TLS-PSK. The client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so. Specify the quality of service to use for the message, from 0, 1 and 2. Defaults to 0. If this argument is given, no runtime errors will be printed. This excludes any error messages given in case of invalid user input (e.g. using without a port). If retain is given, the message will be retained as a "last known good" value on the broker. See mqtt7 for more information. If the publish mode is, , or (i.e. the modes where only a single message is sent), then can be used to specify that the message will be published multiple times. See also . If using , then the default behaviour is to publish repeated messages as soon as the previous message is delivered. Use to specify the number of seconds to wait after the previous message was delivered before publishing the next. Does not need to be an integer number of seconds. Note that there is no guarantee as to the actual interval between messages, this option simply defines the minimum time from delivery of one message to the start of the publish of the next. Send a message read from stdin, sending the entire content as a single message. Use SRV lookups to determine which host to connect to. Performs lookups to when used in conjunction with , otherwise uses . The MQTT topic on which to publish the message. See mqtt7 for more information on MQTT topics. Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets. A valid openssl engine id. These can be listed with openssl engine command. See also . SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password. See also . Choose which TLS protocol version to use when communicating with the broker. Valid options are , and . The default value is . Must match the protocol version used by the broker. Provide a username to be used for authenticating with the broker. See also the argument. Specify which version of the MQTT protocol should be used when connecting to the rmeote broker. Can be , , , or the more verbose , , or . Defaults to . Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with . The QoS to use for the Will. Defaults to 0. This must be used in conjunction with . If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with . The topic on which to send a Will, in the event that the client disconnects unexpectedly. Wills mosquitto_sub can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt7 for more information. The minimum requirement for this is to use to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS 0. Use the , and arguments to modify the other will parameters. Properties The / option allows adding properties to different stages of the mosquitto_pub run. The properties supported for each command are as follows: Connect (binary data - note treated as a string in mosquitto_pub) (UTF-8 string pair) (32-bit unsigned integer) (16-bit unsigned integer) (8-bit unsigned integer) (8-bit unsigned integer) (32-bit unsigned integer) (16-bit unsigned integer) (UTF-8 string pair) Publish (UTF-8 string) (binary data - note treated as a string in mosquitto_pub) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (16-bit unsigned integer) (UTF-8 string pair) Disconnect (32-bit unsigned integer) (UTF-8 string pair) Will properties (UTF-8 string) (binary data - note treated as a string in mosquitto_pub) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (UTF-8 string pair) (32-bit unsigned integer) Examples Publish temperature information to localhost with QoS 1: mosquitto_pub -t sensors/temperature -m 32 -q 1 Publish timestamp and temperature information to a remote host on a non-standard port and QoS 0: mosquitto_pub -h 192.168.1.1 -p 1885 -t sensors/temperature -m "1266193804 32" Publish light switch status. Message is set to retained because there may be a long period of time between light switch events: mosquitto_pub -r -t switches/kitchen_lights/status -m "on" Send the contents of a file in two ways: mosquitto_pub -t my/topic -f ./data mosquitto_pub -t my/topic -s < ./data Send parsed electricity usage data from a Current Cost meter, reading from stdin with one line/reading as one message: read_cc128.pl | mosquitto_pub -t sensors/cc128 -l Files $XDG_CONFIG_HOME/mosquitto_pub $HOME/.config/mosquitto_pub Configuration file for default options. Bugs mosquitto bug information can be found at See Also mqtt 7 mosquitto_rr 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/CMakeLists.txt0000664000175000017500000000063513626052637016144 0ustar rogerrogerinstall(FILES mosquitto_passwd.1 mosquitto_pub.1 mosquitto_sub.1 mosquitto_rr.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1) install(FILES libmosquitto.3 DESTINATION ${CMAKE_INSTALL_MANDIR}/man3) install(FILES mosquitto.conf.5 DESTINATION ${CMAKE_INSTALL_MANDIR}/man5) install(FILES mosquitto-tls.7 mqtt.7 DESTINATION ${CMAKE_INSTALL_MANDIR}/man7) install(FILES mosquitto.8 DESTINATION ${CMAKE_INSTALL_MANDIR}/man8) mosquitto-1.6.9/man/mosquitto.conf.5.xml0000664000175000017500000025567513626052637017301 0ustar rogerroger mosquitto.conf 5 Mosquitto Project File formats and conventions mosquitto.conf the configuration file for mosquitto mosquitto.conf Description mosquitto.conf is the configuration file for mosquitto. This file can reside anywhere as long as mosquitto can read it. By default, mosquitto does not need a configuration file and will use the default values listed below. See mosquitto8 for information on how to load a configuration file. File Format All lines with a # as the very first character are treated as a comment. Configuration lines start with a variable name. The variable value is separated from the name by a single space. Authentication The authentication options described below allow a wide range of possibilities in conjunction with the listener options. This section aims to clarify the possibilities. The simplest option is to have no authentication at all. This is the default if no other options are given. Unauthenticated encrypted support is provided by using the certificate based SSL/TLS based options cafile/capath, certfile and keyfile. MQTT provides username/password authentication as part of the protocol. Use the password_file option to define the valid usernames and passwords. Be sure to use network encryption if you are using this option otherwise the username and password will be vulnerable to interception. Use the to control whether passwords are required globally or on a per-listener basis. When using certificate based encryption there are three options that affect authentication. The first is require_certificate, which may be set to true or false. If false, the SSL/TLS component of the client will verify the server but there is no requirement for the client to provide anything for the server: authentication is limited to the MQTT built in username/password. If require_certificate is true, the client must provide a valid certificate in order to connect successfully. In this case, the second and third options, use_identity_as_username and use_subject_as_username, become relevant. If set to true, use_identity_as_username causes the Common Name (CN) from the client certificate to be used instead of the MQTT username for access control purposes. The password is not used because it is assumed that only authenticated clients have valid certificates. This means that any CA certificates you include in cafile or capath will be able to issue client certificates that are valid for connecting to your broker. If use_identity_as_username is false, the client must authenticate as normal (if required by password_file) through the MQTT options. The same principle applies for the use_subject_as_username option, but the entire certificate subject is used as the username instead of just the CN. When using pre-shared-key based encryption through the psk_hint and psk_file options, the client must provide a valid identity and key in order to connect to the broker before any MQTT communication takes place. If use_identity_as_username is true, the PSK identity is used instead of the MQTT username for access control purposes. If use_identity_as_username is false, the client may still authenticate using the MQTT username/password if using the password_file option. Both certificate and PSK based encryption are configured on a per-listener basis. Authentication plugins can be created to augment the password_file, acl_file and psk_file options with e.g. SQL based lookups. It is possible to support multiple authentication schemes at once. A config could be created that had a listener for all of the different encryption options described above and hence a large number of ways of authenticating. General Options file path Set the path to an access control list file. If defined, the contents of the file are used to control client access to topics on the broker. If this parameter is defined then only the topics listed will have access. Topic access is added with lines of the format: topic [read|write|readwrite] <topic> The access type is controlled using "read", "write" or "readwrite". This parameter is optional (unless <topic> includes a space character) - if not given then the access is read/write. <topic> can contain the + or # wildcards as in subscriptions. The first set of topics are applied to anonymous clients, assuming is true. User specific topic ACLs are added after a user line as follows: user <username> The username referred to here is the same as in . It is not the clientid. It is also possible to define ACLs based on pattern substitution within the topic. The form is the same as for the topic keyword, but using pattern as the keyword. pattern [read|write|readwrite] <topic> The patterns available for substition are: %c to match the client id of the client %u to match the username of the client The substitution pattern must be the only text for that level of hierarchy. Pattern ACLs apply to all users even if the "user" keyword has previously been given. Example: pattern write sensor/%u/data Allow access for bridge connection messages: pattern write $SYS/broker/connection/%c/state If the first character of a line of the ACL file is a # it is treated as a comment. If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. Reloaded on reload signal. The currently loaded ACLs will be freed and reloaded. Existing subscriptions will be affected after the reload. [ true | false ] Boolean value that determines whether clients that connect without providing a username are allowed to connect. If set to false then another means of connection should be created to control authenticated client access. Defaults to true if no other security options are set. If or is set, or if an authentication plugin is loaded which implements username/password or TLS-PSK checks, then defaults to false. If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. Reloaded on reload signal. [ true | false ] If a client is subscribed to multiple subscriptions that overlap, e.g. foo/# and foo/+/baz , then MQTT expects that when the broker receives a message on a topic that matches both subscriptions, such as foo/bar/baz, then the client should only receive the message once. Mosquitto keeps track of which clients a message has been sent to in order to meet this requirement. This option allows this behaviour to be disabled, which may be useful if you have a large number of clients subscribed to the same set of topics and want to minimise memory usage. It can be safely set to true if you know in advance that your clients will never have overlapping subscriptions, otherwise your clients must be able to correctly deal with duplicate messages even when then have QoS=2. Defaults to true. This option applies globally. Reloaded on reload signal. [ true | false ] MQTT 3.1.1 and MQTT 5 allow clients to connect with a zero length client id and have the broker generate a client id for them. Use this option to allow/disallow this behaviour. Defaults to true. See also the option. If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. Reloaded on reload signal. value Options to be passed to the auth plugin. See the specific plugin instructions. Applies to the current authentication plugin being configured. file path Specify an external module to use for authentication and access control. This allows custom username/password and access control functions to be created. Can be specified multiple times to load multiple plugins. The plugins will be processed in the order that they are specified. If , or are used in the config file alongsize , the plugin checks will run after the built in checks. Not currently reloaded on reload signal. [ true | false ] If true then before an ACL check is made, the username/client id of the client needing the check is searched for the presence of either a '+' or '#' character. If either of these characters is found in either the username or client id, then the ACL check is denied before it is sent to the plugin. This check prevents the case where a malicious user could circumvent an ACL check by using one of these characters as their username or client id. This is the same issue as was reported with mosquitto itself as CVE-2017-7650. If you are entirely sure that the plugin you are using is not vulnerable to this attack (i.e. if you never use usernames or client ids in topics) then you can disable this extra check and hence have all ACL checks delivered to your plugin by setting this option to false. Defaults to true. Applies to the current authentication plugin being configured. Not currently reloaded on reload signal. prefix If is true, this option allows you to set a string that will be prefixed to the automatically generated client ids to aid visibility in logs. Defaults to . If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. Reloaded on reload signal. seconds The number of seconds that mosquitto will wait between each time it saves the in-memory database to disk. If set to 0, the in-memory database will only be saved when mosquitto exits or when receiving the SIGUSR1 signal. Note that this setting only has an effect if persistence is enabled. Defaults to 1800 seconds (30 minutes). This option applies globally. Reloaded on reload signal. [ true | false ] If true, mosquitto will count the number of subscription changes, retained messages received and queued messages and if the total exceeds then the in-memory database will be saved to disk. If false, mosquitto will save the in-memory database to disk by treating as a time in seconds. This option applies globally. Reloaded on reload signal. [ true | false ] This option affects the scenario when a client subscribes to a topic that has retained messages. It is possible that the client that published the retained message to the topic had access at the time they published, but that access has been subsequently removed. If is set to true, the default, the source of a retained message will be checked for access rights before it is republished. When set to false, no check will be made and the retained message will always be published. This option applies globally, regardless of the option. prefix If defined, only clients that have a clientid with a prefix that matches clientid_prefixes will be allowed to connect to the broker. For example, setting "secure-" here would mean a client "secure-client" could connect but another with clientid "mqtt" couldn't. By default, all client ids are valid. This option applies globally. Reloaded on reload signal. Note that currently connected clients will be unaffected by any changes. [ true | false ] If set to true, the log will include entries when clients connect and disconnect. If set to false, these entries will not appear. This option applies globally. Reloaded on reload signal. dir External configuration files may be included by using the include_dir option. This defines a directory that will be searched for config files. All files that end in '.conf' will be loaded as a configuration file. It is best to have this as the last option in the main file. This option will only be processed from the main configuration file. The directory specified must not contain the main configuration file. The configuration files in are loaded in case sensitive alphabetical order, with the upper case of each letter ordered before the lower case of the same letter. Given the files b.conf, A.conf, 01.conf, a.conf, B.conf, and 00.conf inside , the config files would be loaded in this order: 00.conf 01.conf A.conf a.conf B.conf b.conf If this option is used multiple times, then each option is processed completely in the order that they are written in the main configuration file. Assuming a directory one.d containing files B.conf and C.conf, and a second directory two.d containing files A.conf and D.conf, and a config: include_dir one.d include_dir two.d Then the config files would be loaded in this order: # files from one.d B.conf C.conf # files from two.d A.conf D.conf destinations Send log messages to a particular destination. Possible destinations are: . and log to the console on the named output. uses the userspace syslog facility which usually ends up in /var/log/messages or similar and topic logs to the broker topic '$SYS/broker/log/<severity>', where severity is one of D, E, W, N, I, M which are debug, error, warning, notice, information and message. Message type severity is used by the subscribe and unsubscribe log_type options and publishes log messages at $SYS/broker/log/M/subscribe and $SYS/broker/log/M/unsubscribe. The destination requires an additional parameter which is the file to be logged to, e.g. "log_dest file /var/log/mosquitto.log". The file will be closed and reopened when the broker receives a HUP signal. Only a single file destination may be configured. Use "log_dest none" if you wish to disable logging. Defaults to stderr. This option may be specified multiple times. Note that if the broker is running as a Windows service it will default to "log_dest none" and neither stdout nor stderr logging is available. Reloaded on reload signal. local facility If using syslog logging (not on Windows), messages will be logged to the "daemon" facility by default. Use the option to choose which of local0 to local7 to log to instead. The option value should be an integer value, e.g. "log_facility 5" to use local5. [ true | false ] Boolean value, if set to true a timestamp value will be added to each log entry. The default is true. Reloaded on reload signal. format Set the format of the log timestamp. If left unset, this is the number of seconds since the Unix epoch. This option is a free text string which will be passed to the strftime function as the format specifier. To get an ISO 8601 datetime, for example: log_timestamp_format %Y-%m-%dT%H:%M:%S Reloaded on reload signal. types Choose types of messages to log. Possible types are: debug, error, warning, notice, information, subscribe, unsubscribe, websockets, none, all. Defaults to error, warning, notice and information. This option may be specified multiple times. Note that the debug type (used for decoding incoming/outgoing network packets) is never logged in topics. Reloaded on reload signal. count Outgoing QoS 1 and 2 messages will be allowed in flight until this byte limit is reached. This allows control of outgoing message rate based on message size rather than message count. If the limit is set to 100, messages of over 100 bytes are still allowed, but only a single message can be in flight at once. Defaults to 0. (No limit). See also the option. This option applies globally. Reloaded on reload signal. count The maximum number of outgoing QoS 1 or 2 messages that can be in the process of being transmitted simultaneously. This includes messages currently going through handshakes and messages that are being retried. Defaults to 20. Set to 0 for no maximum. If set to 1, this will guarantee in-order delivery of messages. This option applies globally. Reloaded on reload signal. value For MQTT v5 clients, it is possible to have the server send a "server keepalive" value that will override the keepalive value set by the client. This is intended to be used as a mechanism to say that the server will disconnect the client earlier than it anticipated, and that the client should use the new keepalive value. The max_keepalive option allows you to specify that clients may only connect with keepalive less than or equal to this value, otherwise they will be sent a server keepalive telling them to use max_keepalive. This only applies to MQTT v5 clients. The maximum value allowable, and default value, is 65535. Do not set below 10 seconds. This option applies globally. Reloaded on reload signal. value For MQTT v5 clients, it is possible to have the server send a "maximum packet size" value that will instruct the client it will not accept MQTT packets with size greater than bytes. This applies to the full MQTT packet, not just the payload. Setting this option to a positive value will set the maximum packet size to that number of bytes. If a client sends a packet which is larger than this value, it will be disconnected. This applies to all clients regardless of the protocol version they are using, but v3.1.1 and earlier clients will of course not have received the maximum packet size information. Defaults to no limit. This option applies to all clients, not just those using MQTT v5, but it is not possible to notify clients using MQTT v3.1.1 or MQTT v3.1 of the limit. Setting below 20 bytes is forbidden because it is likely to interfere with normal client operation even with small payloads. This option applies globally. Reloaded on reload signal. count The number of outgoing QoS 1 and 2 messages above those currently in-flight will be queued (per client) by the broker. Once this limit has been reached, subsequent messages will be silently dropped. This is an important option if you are sending messages at a high rate and/or have clients who are slow to respond or may be offline for extended periods of time. Defaults to 0. (No maximum). See also the option. If both max_queued_messages and max_queued_bytes are specified, packets will be queued until the first limit is reached. This option applies globally. Reloaded on reload signal. count The maximum number of QoS 1 or 2 messages to hold in the queue (per client) above those messages that are currently in flight. Defaults to 100. Set to 0 for no maximum (not recommended). See also the and options. This option applies globally. Reloaded on reload signal. limit This option sets the maximum number of heap memory bytes that the broker will allocate, and hence sets a hard limit on memory use by the broker. Memory requests that exceed this value will be denied. The effect will vary depending on what has been denied. If an incoming message is being processed, then the message will be dropped and the publishing client will be disconnected. If an outgoing message is being sent, then the individual message will be dropped and the receiving client will be disconnected. Defaults to no limit. This option is only available if memory tracking support is compiled in. Reloaded on reload signal. Setting to a lower value and reloading will not result in memory being freed. limit This option sets the maximum publish payload size that the broker will allow. Received messages that exceed this size will not be accepted by the broker. This means that the message will not be forwarded on to subscribing clients, but the QoS flow will be completed for QoS 1 or QoS 2 messages. MQTT v5 clients using QoS 1 or QoS 2 will receive a PUBACK or PUBREC with the "implementation specific error" reason code. The default value is 0, which means that all valid MQTT messages are accepted. MQTT imposes a maximum payload size of 268435455 bytes. This option applies globally. Reloaded on reload signal. file path Set the path to a password file. If defined, the contents of the file are used to control client access to the broker. The file can be created using the mosquitto_passwd1 utility. If mosquitto is compiled without TLS support (it is recommended that TLS support is included), then the password file should be a text file with each line in the format "username:password", where the colon and password are optional but recommended. If is set to false, only users defined in this file will be able to connect. Setting to true when password_fileis defined is valid and could be used with acl_file to have e.g. read only guest/anonymous accounts and defined users that can publish. If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. Reloaded on reload signal. The currently loaded username and password data will be freed and reloaded. Clients that are already connected will not be affected. See also mosquitto_passwd1. [ true | false ] If true, then authentication and access control settings will be controlled on a per-listener basis. The following options are affected: , , , , , , , . Note that if set to true, then a durable client (i.e. with clean session set to false) that has disconnected will use the ACL settings defined for the listener that it was most recently connected to. The default behaviour is for this to be set to false, which maintains the settings behaviour from previous versions of mosquitto. Reloaded on reload signal. [ true | false ] If true, connection, subscription and message data will be written to the disk in mosquitto.db at the location dictated by persistence_location. When mosquitto is restarted, it will reload the information stored in mosquitto.db. The data will be written to disk when mosquitto closes and also at periodic intervals as defined by autosave_interval. Writing of the persistence database may also be forced by sending mosquitto the SIGUSR1 signal. If false, the data will be stored in memory only. Defaults to false. The persistence file may change its format in a new version. The broker can currently read all old formats, but will only save in the latest format. It should always be safe to upgrade, but cautious users may wish to take a copy of the persistence file before installing a new version so that they can roll back to an earlier version if necessary. This option applies globally. Reloaded on reload signal. file name The filename to use for the persistent database. Defaults to mosquitto.db. This option applies globally. Reloaded on reload signal. path The path where the persistence database should be stored. Must end in a trailing slash. If not given, then the current directory is used. This option applies globally. Reloaded on reload signal. duration This option allows persistent clients (those with clean session set to false) to be removed if they do not reconnect within a certain time frame. This is a non-standard option. As far as the MQTT spec is concerned, persistent clients persist forever. Badly designed clients may set clean session to false whilst using a randomly generated client id. This leads to persistent clients that will never reconnect. This option allows these clients to be removed. The expiration period should be an integer followed by one of h d w m y for hour, day, week, month and year respectively. For example: persistent_client_expiration 2m persistent_client_expiration 14d persistent_client_expiration 1y As this is a non-standard option, the default if not set is to never expire persistent clients. This option applies globally. Reloaded on reload signal. file path Write a pid file to the file specified. If not given (the default), no pid file will be written. If the pid file cannot be written, mosquitto will exit. This option only has an effect is mosquitto is run in daemon mode. If mosquitto is being automatically started by an init script it will usually be required to write a pid file. This should then be configured as e.g. /var/run/mosquitto.pid Not reloaded on reload signal. file path Set the path to a pre-shared-key file. This option requires a listener to be have PSK support enabled. If defined, the contents of the file are used to control client access to the broker. Each line should be in the format "identity:key", where the key is a hexadecimal string with no leading "0x". A client connecting to a listener that has PSK support enabled must provide a matching identity and PSK to allow the encrypted connection to proceed. If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. Reloaded on reload signal. The currently loaded identity and key data will be freed and reloaded. Clients that are already connected will not be affected. [ true | false ] Set to true to queue messages with QoS 0 when a persistent client is disconnected. These messages are included in the limit imposed by max_queued_messages. Defaults to false. Note that the MQTT v3.1.1 spec states that only QoS 1 and 2 messages should be saved in this situation so this is a non-standard option. This option applies globally. Reloaded on reload signal. [ true | false ] If set to false, then retained messages are not supported. Clients that send a message with the retain bit will be disconnected if this option is set to false. Defaults to true. This option applies globally. Reloaded on reload signal. [ true | false ] This is a synonym of the option. Reloaded on reload signal. [ true | false ] If set to true, the TCP_NODELAY option will be set on client sockets to disable Nagle's algorithm. This has the effect of reducing latency of some messages at potentially increasing the number of TCP packets being sent. Defaults to false. This option applies globally. Reloaded on reload signal. seconds The integer number of seconds between updates of the $SYS subscription hierarchy, which provides status information about the broker. If unset, defaults to 10 seconds. Set to 0 to disable publishing the $SYS hierarchy completely. This option applies globally. Reloaded on reload signal. [ true | false ] The MQTT specification requires that the QoS of a message delivered to a subscriber is never upgraded to match the QoS of the subscription. Enabling this option changes this behaviour. If is set true, messages sent to a subscriber will always match the QoS of its subscription. This is a non-standard option not provided for by the spec. Defaults to false. This option applies globally. Reloaded on reload signal. username When run as root, change to this user and its primary group on startup. If mosquitto is unable to change to this user and group, it will exit with an error. The user specified must have read/write access to the persistence database if it is to be written, and read access to certificate, password, and ACL files. If run as a non-root user, this setting has no effect. Defaults to mosquitto. This setting has no effect on Windows and so you should run mosquitto as the user you wish it to run as. Not reloaded on reload signal. Listeners The network ports that mosquitto listens on can be controlled using listeners. The default listener options can be overridden and further listeners can be created. General Options address Listen for incoming network connections on the specified IP address/hostname only. This is useful to restrict access to certain network interfaces. To restrict access to mosquitto to the local host only, use "bind_address localhost". This only applies to the default listener. Use the option to control other listeners. It is recommended to use an explicit rather than rely on the implicit default listener options like this. Not reloaded on reload signal. device Listen for incoming network connections only on the specified interface. This is similar to the option but is useful when an interface has multiple addresses or the address may change. It is valid to use this option together with for the default listener, or the bind address/host part of the definition. Care should be taken to ensure that the address being bound to is on the interface being bound to. If you set the to be eth0, and to 127.0.0.1, then the broker will start correctly but you will be unable to connect. This option is currently only available on Linux, and requires elevated privileges. Not reloaded on reload signal. directory When a listener is using the websockets protocol, it is possible to serve http data as well. Set to a directory which contains the files you wish to serve. If this option is not specified, then no normal http connections will be possible. Not reloaded on reload signal. port bind address/host Listen for incoming network connection on the specified port. A second optional argument allows the listener to be bound to a specific ip address/hostname. If this variable is used and neither the global nor options are used then the default listener will not be started. The option allows this listener to be bound to a specific IP address by passing an IP address or hostname. For websockets listeners, it is only possible to pass an IP address here. This option may be specified multiple times. See also the option. Not reloaded on reload signal. count Limit the total number of clients connected for the current listener. Set to -1 to have "unlimited" connections. Note that other limits may be imposed that are outside the control of mosquitto. See e.g. limits.conf5. Not reloaded on reload signal. count Limit the QoS value allowed for clients connecting to this listener. Defaults to 2, which means any QoS can be used. Set to 0 or 1 to limit to those QoS values. This makes use of an MQTT v5 feature to notify clients of the limitation. MQTT v3.1.1 clients will not be aware of the limitation. Clients publshing to this listener with a too-high QoS will be disconnected. Not reloaded on reload signal. number This option sets the maximum number topic aliases that an MQTT v5 client is allowed to create. This option applies per listener. Defaults to 10. Set to 0 to disallow topic aliases. The maximum value possible is 65535. Not reloaded on reload signal. topic prefix This option is used with the listener option to isolate groups of clients. When a client connects to a listener which uses this option, the string argument is attached to the start of all topics for this client. This prefix is removed when any messages are sent to the client. This means a client connected to a listener with mount point example can only see messages that are published in the topic hierarchy example and below. Not reloaded on reload signal. port number Set the network port for the default listener to listen on. Defaults to 1883. Not reloaded on reload signal. It is recommended to use an explicit rather than rely on the implicit default listener options like this. value Set the protocol to accept for the current listener. Can be , the default, or if available. Websockets support is currently disabled by default at compile time. Certificate based TLS may be used with websockets, except that only the , , and options are supported. Not reloaded on reload signal. [ ipv4 | ipv6 ] By default, a listener will attempt to listen on all supported IP protocol versions. If you do not have an IPv4 or IPv6 interface you may wish to disable support for either of those protocol versions. In particular, note that due to the limitations of the websockets library, it will only ever attempt to open IPv6 sockets if IPv6 support is compiled in, and so will fail if IPv6 is not available. Set to to force the listener to only use IPv4, or set to to force the listener to only use IPv6. If you want support for both IPv4 and IPv6, then do not use the option. Not reloaded on reload signal. [ true | false ] Set to true to replace the clientid that a client connected with with its username. This allows authentication to be tied to the clientid, which means that it is possible to prevent one client disconnecting another by using the same clientid. Defaults to false. If a client connects with no username it will be disconnected as not authorised when this option is set to true. Do not use in conjunction with . See also . Not reloaded on reload signal. level Change the websockets logging level. This is a global option, it is not possible to set per listener. This is an integer that is interpreted by libwebsockets as a bit mask for its lws_log_levels enum. See the libwebsockets documentation for more details. To use this option, must also be enabled. Defaults to 0. size Change the websockets headers size. This is a global option, it is not possible to set per listener. This option sets the size of the buffer used in the libwebsockets library when reading HTTP headers. If you are passing large header data such as cookies then you may need to increase this value. If left unset, or set to 0, then the default of 1024 bytes will be used. Certificate based SSL/TLS Support The following options are available for all listeners to configure certificate based SSL support. See also "Pre-shared-key based SSL/TLS support". file path At least one of or must be provided to enable SSL support. is used to define the path to a file containing the PEM encoded CA certificates that are trusted. directory path At least one of or must be provided to enable SSL support. is used to define a directory that contains PEM encoded CA certificates that are trusted. For to work correctly, the certificates files must have ".pem" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a certificate. file path Path to the PEM encoded server certificate. cipher:list The list of allowed ciphers, each separated with a colon. Available ciphers can be obtained using the "openssl ciphers" command. file path If you have set to true, you can create a certificate revocation list file to revoke access to particular client certificates. If you have done this, use crlfile to point to the PEM encoded revocation file. file path To allow the use of ephemeral DH key exchange, which provides forward security, the listener must load DH parameters. This can be specified with the dhparamfile option. The dhparamfile can be generated with the command e.g. openssl dhparam -out dhparam.pem 2048 file path Path to the PEM encoded keyfile. [ true | false ] By default an SSL/TLS enabled listener will operate in a similar fashion to a https enabled web server, in that the server has a certificate signed by a CA and the client will verify that it is a trusted certificate. The overall aim is encryption of the network traffic. By setting to true, a client connecting to this listener must provide a valid certificate in order for the network connection to proceed. This allows access to the broker to be controlled outside of the mechanisms provided by MQTT. engine A valid openssl engine id. These can be listed with openssl engine command. engine_kpass_sha1 SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password. [ pem | engine ] Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the private key has been created with it. Defaults to "pem", which means normal private key files are used. version Configure the version of the TLS protocol to be used for this listener. Possible values are tlsv1.3, tlsv1.2 and tlsv1.1. If left unset, the default of allowing all of TLS v1.3, v1.2 and v1.1 is used. [ true | false ] If is true, you may set to true to use the CN value from the client certificate as a username. If this is true, the option will not be used for this listener. This takes priority over if both are set to true. See also [ true | false ] If is true, you may set to true to use the complete subject value from the client certificate as a username. If this is true, the option will not be used for this listener. The subject will be generated in a form similar to . See also Pre-shared-key based SSL/TLS Support The following options are available for all listeners to configure pre-shared-key based SSL support. See also "Certificate based SSL/TLS support". cipher:list When using PSK, the encryption ciphers used will be chosen from the list of available PSK ciphers. If you want to control which ciphers are available, use this option. The list of available ciphers can be optained using the "openssl ciphers" command and should be provided in the same format as the output of that command. hint The option enables pre-shared-key support for this listener and also acts as an identifier for this listener. The hint is sent to clients and may be used locally to aid authentication. The hint is a free form string that doesn't have much meaning in itself, so feel free to be creative. If this option is provided, see to define the pre-shared keys to be used or create a security plugin to handle them. version Configure the version of the TLS protocol to be used for this listener. Possible values are tlsv1.3, tlsv1.2 and tlsv1.1. If left unset, the default of allowing all of TLS v1.3, v1.2 and v1.1 is used. [ true | false ] Set to have the psk identity sent by the client used as its username. The username will be checked as normal, so or another means of authentication checking must be used. No password will be used. Configuring Bridges Multiple bridges (connections to other brokers) can be configured using the following variables. Bridges cannot currently be reloaded on reload signal. address[:port] [address[:port]] address[:port] [address[:port]] Specify the address and optionally the port of the bridge to connect to. This must be given for each bridge connection. If the port is not specified, the default of 1883 is used. If you use an IPv6 address, then the port is not optional. Multiple host addresses can be specified on the address config. See the option for more details on the behaviour of bridges with multiple addresses. [ true | false ] If a bridge has topics that have "out" direction, the default behaviour is to send an unsubscribe request to the remote broker on that topic. This means that changing a topic direction from "in" to "out" will not keep receiving incoming messages. Sending these unsubscribe requests is not always desirable, setting to false will disable sending the unsubscribe request. Defaults to true. version Set the version of the MQTT protocol to use with for this bridge. Can be one of mqttv31 or mqttv311. Defaults to mqttv31. [ true | false ] Set the clean session option for this bridge. Setting to false (the default), means that all subscriptions on the remote broker are kept in case of the network connection dropping. If set to true, all subscriptions and messages on the remote broker will be cleaned up if the connection drops. Note that setting to true may cause a large amount of retained messages to be sent each time the bridge reconnects. If you are using bridges with set to false (the default), then you may get unexpected behaviour from incoming topics if you change what topics you are subscribing to. This is because the remote broker keeps the subscription for the old topic. If you have this problem, connect your bridge with set to true, then reconnect with cleansession set to false as normal. name This variable marks the start of a new bridge connection. It is also used to give the bridge a name which is used as the client id on the remote broker. seconds Set the number of seconds after which the bridge should send a ping if no other traffic has occurred. Defaults to 60. A minimum value of 5 seconds is allowed. seconds Set the amount of time a bridge using the lazy start type must be idle before it will be stopped. Defaults to 60 seconds. id Set the clientid to use on the local broker. If not defined, this defaults to . If you are bridging a broker to itself, it is important that local_clientid and remote_clientid do not match. password Configure the password to be used when connecting this bridge to the local broker. This may be important when authentication and ACLs are being used. username Configure the username to be used when connecting this bridge to the local broker. This may be important when authentication and ACLs are being used. [ true | false ] If set to true, publish notification messages to the local and remote brokers giving information about the state of the bridge connection. Retained messages are published to the topic $SYS/broker/connection/<remote_clientid>/state unless otherwise set with s. If the message is 1 then the connection is active, or 0 if the connection has failed. Defaults to true. This uses the Last Will and Testament (LWT) feature. [ true | false ] If set to true, only publish notification messages to the local broker giving information about the state of the bridge connection. Defaults to false. topic Choose the topic on which notifications will be published for this bridge. If not set the messages will be sent on the topic $SYS/broker/connection/<remote_clientid>/state. id Set the client id for this bridge connection. If not defined, this defaults to 'name.hostname', where name is the connection name and hostname is the hostname of this computer. This replaces the old "clientid" option to avoid confusion with local/remote sides of the bridge. "clientid" remains valid for the time being. value Configure a password for the bridge. This is used for authentication purposes when connecting to a broker that supports MQTT v3.1 and up and requires a username and/or password to connect. This option is only valid if a remote_username is also supplied. This replaces the old "password" option to avoid confusion with local/remote sides of the bridge. "password" remains valid for the time being. name Configure a username for the bridge. This is used for authentication purposes when connecting to a broker that supports MQTT v3.1 and up and requires a username and/or password to connect. See also the option. This replaces the old "username" option to avoid confusion with local/remote sides of the bridge. "username" remains valid for the time being. base cap constant Set the amount of time a bridge using the automatic start type will wait until attempting to reconnect. This option can be configured to use a constant delay time in seconds, or to use a backoff mechanism based on "Decorrelated Jitter", which adds a degree of randomness to when the restart occurs, starting at the base and increasing up to the cap. Set a constant timeout of 20 seconds: restart_timeout 20 Set backoff with a base (start value) of 10 seconds and a cap (upper limit) of 60 seconds: restart_timeout 10 30 Defaults to jitter with a base of 5 seconds and cap of 30 seconds. [ true | false ] If the bridge has more than one address given in the address/addresses configuration, the round_robin option defines the behaviour of the bridge on a failure of the bridge connection. If round_robin is false, the default value, then the first address is treated as the main bridge connection. If the connection fails, the other secondary addresses will be attempted in turn. Whilst connected to a secondary bridge, the bridge will periodically attempt to reconnect to the main bridge until successful. If round_robin is true, then all addresses are treated as equals. If a connection fails, the next address will be tried and if successful will remain connected until it fails. [ automatic | lazy | once ] Set the start type of the bridge. This controls how the bridge starts and can be one of three types: automatic, lazy and once. Note that RSMB provides a fourth start type "manual" which isn't currently supported by mosquitto. automatic is the default start type and means that the bridge connection will be started automatically when the broker starts and also restarted after a short delay (30 seconds) if the connection fails. Bridges using the lazy start type will be started automatically when the number of queued messages exceeds the number set with the option. It will be stopped automatically after the time set by the parameter. Use this start type if you wish the connection to only be active when it is needed. A bridge using the once start type will be started automatically when the broker starts but will not be restarted if the connection fails. count Set the number of messages that need to be queued for a bridge with lazy start type to be restarted. Defaults to 10 messages. pattern [[[ out | in | both ] qos-level] local-prefix remote-prefix] Define a topic pattern to be shared between the two brokers. Any topics matching the pattern (which may include wildcards) are shared. The second parameter defines the direction that the messages will be shared in, so it is possible to import messages from a remote broker using in, export messages to a remote broker using out or share messages in both directions. If this parameter is not defined, the default of out is used. The QoS level defines the publish/subscribe QoS level used for this topic and defaults to 0. The local-prefix and remote-prefix options allow topics to be remapped when publishing to and receiving from remote brokers. This allows a topic tree from the local broker to be inserted into the topic tree of the remote broker at an appropriate place. For incoming topics, the bridge will prepend the pattern with the remote prefix and subscribe to the resulting topic on the remote broker. When a matching incoming message is received, the remote prefix will be removed from the topic and then the local prefix added. For outgoing topics, the bridge will prepend the pattern with the local prefix and subscribe to the resulting topic on the local broker. When an outgoing message is processed, the local prefix will be removed from the topic then the remote prefix added. When using topic mapping, an empty prefix can be defined using the place marker "". Using the empty marker for the topic itself is also valid. The table below defines what combination of empty or value is valid. The and show the resulting topics that would be used on the local and remote ends of the bridge. For example, for the first table row if you publish to on the local broker, then the remote broker will receive a message on the topic . Pattern Local Prefix Remote Prefix Validity Full Local Topic Full Remote Topic patternL/R/validL/patternR/pattern patternL/""validL/patternpattern pattern""R/validpatternR/pattern pattern""""valid (no remapping)patternpattern ""localremotevalid (remap single local topic to remote)localremote ""local""invalid """"remoteinvalid """"""invalid To remap an entire topic tree, use e.g.: topic # both 2 local/topic/ remote/topic/ This option can be specified multiple times per bridge. Care must be taken to ensure that loops are not created with this option. If you are experiencing high CPU load from a broker, it is possible that you have a loop where each broker is forever forwarding each other the same messages. See also the option if you have messages arriving on unexpected topics when using incoming topics. The configuration below connects a bridge to the broker at . It subscribes to the remote topic and republishes the messages received to the local topic connection test-mosquitto-org address test.mosquitto.org cleansession true topic clients/total in 0 test/mosquitto/org $SYS/broker/ [ true | false ] If try_private is set to true, the bridge will attempt to indicate to the remote broker that it is a bridge not an ordinary client. If successful, this means that loop detection will be more effective and that retained messages will be propagated correctly. Not all brokers support this feature so it may be necessary to set to false if your bridge does not connect properly. Defaults to true. SSL/TLS Support The following options are available for all bridges to configure SSL/TLS support. alpn Configure the application layer protocol negotiation option for the TLS session. Useful for brokers that support both websockets and MQTT on the same port. file path One of or must be provided to allow SSL/TLS support. bridge_cafile is used to define the path to a file containing the PEM encoded CA certificates that have signed the certificate for the remote broker. file path One of or must be provided to allow SSL/TLS support. bridge_capath is used to define the path to a directory containing the PEM encoded CA certificates that have signed the certificate for the remote broker. For bridge_capath to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to bridge_capath>" each time you add/remove a certificate. file path Path to the PEM encoded client certificate for this bridge, if required by the remote broker. identity Pre-shared-key encryption provides an alternative to certificate based encryption. A bridge can be configured to use PSK with the and options. This is the client identity used with PSK encryption. Only one of certificate and PSK based encryption can be used on one bridge at once. [ true | false ] When using certificate based TLS, the bridge will attempt to verify the hostname provided in the remote certificate matches the host/address being connected to. This may cause problems in testing scenarios, so may be set to false to disable the hostname verification. Setting this option to true means that a malicious third party could potentially inpersonate your server, so it should always be set to false in production environments. file path Path to the PEM encoded private key for this bridge, if required by the remote broker. key Pre-shared-key encryption provides an alternative to certificate based encryption. A bridge can be configured to use PSK with the and options. This is the pre-shared-key in hexadecimal format with no "0x". Only one of certificate and PSK based encryption can be used on one bridge at once. [ true | false ] When set to true, the bridge requires OCSP on the TLS connection it opens as client. version Configure the version of the TLS protocol to be used for this bridge. Possible values are tlsv1.3, tlsv1.2 and tlsv1.1. Defaults to tlsv1.2. The remote broker must support the same version of TLS for the connection to succeed. Files mosquitto.conf Bugs mosquitto bug information can be found at See Also mosquitto 8 mosquitto_passwd 1 mosquitto-tls 7 mqtt 7 limits.conf 5 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mosquitto_sub.1.xml0000664000175000017500000012321313626052637017200 0ustar rogerroger mosquitto_sub 1 Mosquitto Project Commands mosquitto_sub an MQTT version 5/3.1.1/3.1 client for subscribing to topics mosquitto_sub hostname port-number username password message-topic URL message-topic bind-address msg-count command identifier value client-id client-id-prefix keepalive-time message-QoS filter-out unsub-topic protocol-version message-processing-timeout socks-url topic payload qos file dir file file version protocol engine pem engine kpass-sha1 hex-key identity version mosquitto_sub Description mosquitto_sub is a simple MQTT version 5/3.1.1 client that will subscribe to topics and print the messages that it receives. In addition to subscribing to topics, mosquitto_sub can filter out received messages so they are not printed (see the option) or unsubscribe from topics (see the option). Unsubscribing from topics is useful for clients connecting with clean session set to false. Encrypted Connections mosquitto_sub supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup. To enable TLS connections when using x509 certificates, one of either or must be provided as an option. To enable TLS connections when using TLS-PSK, you must use the and the options. Options The options below may be given on the command line, but may also be placed in a config file located at or with one pair of per line. The values in the config file will be used as defaults and can be overridden by using the command line. The exceptions to this are and , which if given in the config file will not be overridden. Note also that currently some options cannot be negated, e.g. . Config file lines that have a as the first character are treated as comments and not processed any further. Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface. Disable the 'clean session' flag. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive. When the client reconnects, it will receive all of the queued messages. If using this option, the client id must be set manually with Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. See also Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. For to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a certificate. See also Define the path to a file containing a PEM encoded certificate for this client, if required by the server. See also . An openssl compatible list of TLS ciphers to support in the client. See ciphers1 for more information. Disconnect and exit the program immediately after the given count of messages have been received. This may be useful in shell scripts where on a single status value is required, for example. Combine with to print only the first set of fresh messages (i.e. that does not have the retained flag set), or with to filter which topics are processed. Enable debug messages. Use an MQTT v5 property with this publish. If you use this option, the client will be set to be an MQTT v5 client. This option has two forms: is the MQTT command/packet identifier and can be one of CONNECT, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL. The properties available for each command are listed in the Properties section. is the name of the property to add. This is as described in the specification, but with '-' as a word separator. For example: . More details are in the Properties section. is the value of the property to add, with a data type that is property specific. is only used for the property as the first of the two strings in the string pair. In that case, is the second of the strings in the pair. If this option is given, mosquitto_sub will exit immediately that all of its subscriptions have been acknowledged by the broker. In conjunction with this allows a durable client session to be initialised on the broker for future use without requiring any messages to be received. Specify output printing format. This option allows you to choose what information from each message is printed to the screen. See the Output Format section below for full details. This option overrides the option, but does not override the option. Display usage information. Specify the host to connect to. Defaults to localhost. The id to use for this client. If not given, a client id will be generated depending on the MQTT version being used. For v3.1.1/v3.1, the client generates a client id in the format , where the are replaced with random alphanumeric characters. For v5.0, the client sends a zero length client id, and the server will generate a client id for the client. This option cannot be used at the same time as the argument. Provide a prefix that the client id will be built from by appending the process id of the client. This is useful where the broker is using the clientid_prefixes option. Cannot be used at the same time as the argument. When using certificate based encryption, this option disables verification of the server hostname in the server certificate. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only. If you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption. The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. Defaults to 60 seconds. Define the path to a file containing a PEM encoded private key for this client, if required by the server. See also . Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the private key has been created with it. Defaults to "pem", which means normal private key files are used. See also . Specify specify user, password, hostname, port and topic at once as a URL. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883. Do not append an end of line character to the payload when printing. This allows streaming of payload data from multiple messages directly to another application unmodified. Only really makes sense when not using . Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used. Provide a password to be used for authenticating with the broker. Using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. See also the option. Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The must be of the form . The protocol prefix means that hostnames are resolved by the proxy. The symbols %25, %3A and %40 are URL decoded into %, : and @ respectively, if present in the username or password. If username is not given, then no authentication is attempted. If the port is not given, then the default of 1080 is used. More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl 1 . Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support. must also be provided to enable TLS-PSK. The client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so. Specify the quality of service desired for the incoming messages, from 0, 1 and 2. Defaults to 0. See mqtt7 for more information on QoS. The QoS is identical for all topics subscribed to in a single instance of mosquitto_sub. If this argument is given, no runtime errors will be printed. This excludes any error messages given in case of invalid user input (e.g. using without a port). If this argument is given, messages that are received that have the retain bit set will not be printed. Messages with retain set are "stale", in that it is not known when they were originally published. When subscribing to a wildcard topic there may be a large number of retained messages. This argument suppresses their display. If this argument is given, the when mosquitto_sub receives a message with the retained bit set, it will send a message to the broker to clear that retained message. This applies to all received messages except those that are filtered out by the option. This option still takes effect even if is used. See also the and options. Remove all retained messages on the server, assuming we have access to do so, and then exit: mosquitto_sub -t '#' --remove-retained --retained-only Remove a whole tree, with the exception of a single topic: mosquitto_sub -t 'bbc/#' -T bbc/bbc1 --remove-retained If this argument is given, only messages that are received that have the retain bit set will be printed. Messages with retain set are "stale", in that it is not known when they were originally published. With this argument in use, the receipt of the first non-stale message will cause the client to exit. See also the option. If this argument is given, the subscriptions will have the "retain as published" option set. This means that the retain flag on an incoming message will be exactly as set by the publishing client, rather than indicating whether the message is fresh/stale. This option is not valid for MQTT v3.1/v3.1.1 clients. Use SRV lookups to determine which host to connect to. Performs lookups to when used in conjunction with , otherwise uses . The MQTT topic to subscribe to. See mqtt7 for more information on MQTT topics. This option may be repeated to subscribe to multiple topics. Suppress printing of topics that match the filter. This allows subscribing to a wildcard topic and only printing a partial set of the wildcard hierarchy. For example, subscribe to the BBC tree, but suppress output from Radio 3: mosquitto_sub -t bbc/# -T bbc/radio3 This option may be repeated to filter out multiple topics or topic trees. Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets. A valid openssl engine id. These can be listed with openssl engine command. See also . SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password. See also . Choose which TLS protocol version to use when communicating with the broker. Valid options are , and . The default value is . Must match the protocol version used by the broker. Provide a username to be used for authenticating with the broker. See also the argument. A topic that will be unsubscribed from. This may be used on its own or in conjunction with the option and only makes sense when used in conjunction with . If used with then subscriptions will be processed before unsubscriptions. Note that it is only possible to unsubscribe from subscriptions that have previously been made. It is not possible to punch holes in wildcard subscriptions. For example, subscribing to and then unsubscribing from as shown below will still result in messages matching the being delivered to the client. mosquitto_sub -t sensors/# -U sensors/+/temperature -v Note also that because retained messages are published by the broker on receipt of a SUBSCRIBE command, subscribing and unsubscribing to the same topic may result in messages being received at the client. This option may be repeated to unsubscribe from multiple topics. Print received messages verbosely. With this argument, messages will be printed as "topic payload". When this argument is not given, the messages are printed as "payload". Specify which version of the MQTT protocol should be used when connecting to the remote broker. Can be , , , or the more verbose , , or . Defaults to . Provide a timeout as an integer number of seconds. mosquitto_sub will stop processing messages and disconnect after this number of seconds has passed. The timeout starts just after the client has connected to the broker. Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with . The QoS to use for the Will. Defaults to 0. This must be used in conjunction with . If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with . The topic on which to send a Will, in the event that the client disconnects unexpectedly. Output format There are three ways of formatting the output from mosquitto_sub. In all cases a new-line character is appended for each message received unless the argument is passed to mosquitto_sub. Payload-only is the default output format and will print the payload exactly as it is received. Verbose mode is activated with and prints the message topic and the payload, separated by a space. The final option is formatted output, which allows the user to define a custom output format. The behaviour is controlled with the option. The format string is a free text string where interpreted sequences are replaced by different parameters. The available interpreted sequences are described below. Three characters are used to start an interpreted sequence: , and . Sequences starting with are either parameters related to the MQTT message being printed, or are helper sequences to avoid the need to type long date format strings for example. Sequences starting with are passed to the strftime3 function (with the @ replaced with a % - note that only the character immediately after the @ is passed to strftime). This allows the construction of a wide variety of time based outputs. The output options for strftime vary from platform to platform, so please check what is available for your platform. mosquitto_sub does provide one extension to strftime which is , which can be used to obtain the number of nanoseconds passed in the current second. The resolution of this option varies depending on the platform. The final sequence character is , which is used to input some characters that would otherwise be difficult to enter. MQTT related parameters a literal %. the length of the payload in bytes. the message id (only relevant for messages with QoS>0). the payload raw bytes (may produce non-printable characters depending on the payload). the message QoS. the retained flag for the message. the message topic. the payload with each byte as a hexadecimal number (lower case). the payload with each byte as a hexadecimal number (upper case). Helpers ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100 JSON output of message parameters and timestamp, with a quoted and escaped payload. For example {"tst":1470825369,"topic":"greeting","qos":0,"retain":0,"payload":"hello world"} JSON output of message parameters and timestamp, with a non-quoted and non-escaped payload - this means the payload must itself be valid JSON. For example: {"tst":1470825369,"topic":"foo","qos":0,"retain":0,"payload":{"temperature":27.0,"humidity":57}}. ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100 Unix timestamp with nanoseconds, e.g. 1470818943.786368637 Time related parameters a literal @. pass the character represented by to the strftime function as . The options supported are platform dependent. the number of nanoseconds that have passed in the current second, with varying timing resolution depending on platform. Escape characters a literal \. a null character. Can be used to separate different parameters that may contain spaces (e.g. topic, payload) so that processing with tools such as xargs1 is easier. alert/bell. the escape sequence, which can be used with ANSI colour codes to provide coloured output for example. end of line. carriage return. horizontal tab. vertical tab. Wills mosquitto_sub can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt7 for more information. The minimum requirement for this is to use to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS 0. Use the , and arguments to modify the other will parameters. Properties The / option allows adding properties to different stages of the mosquitto_sub run. The properties supported for each command are as follows: Connect (binary data - note treated as a string in mosquitto_sub) (UTF-8 string pair) (32-bit unsigned integer) (16-bit unsigned integer) (8-bit unsigned integer) (8-bit unsigned integer) (32-bit unsigned integer) (16-bit unsigned integer) (UTF-8 string pair) Subscribe (UTF-8 string pair) Unsubscribe (UTF-8 string pair) Disconnect (32-bit unsigned integer) (UTF-8 string pair) Will properties (UTF-8 string) (binary data - note treated as a string in mosquitto_sub) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (UTF-8 string pair) (32-bit unsigned integer) Examples Note that these really are examples - the subscriptions will work if you run them as shown, but there must be something publishing messages on those topics for you to receive anything. Subscribe to temperature information on localhost with QoS 1: mosquitto_sub -t sensors/temperature -q 1 Subscribe to hard drive temperature updates on multiple machines/hard drives. This expects each machine to be publishing its hard drive temperature to sensors/machines/HOSTNAME/temperature/HD_NAME. mosquitto_sub -t sensors/machines/+/temperature/+ Subscribe to all broker status messages: mosquitto_sub -v -t \$SYS/# Specify the output format as "ISO-8601 date : topic : payload in hex" mosquitto_sub -F '@Y-@m-@dT@H:@M:@S@z : %t : %x' -t '#' Specify the output format as "seconds since epoch.nanoseconds : retained flag : qos : mid : payload length" mosquitto_sub -F '%@s.@N : %r : %q : %m : %l' -q 2 -t '#' Topic and payload output, but with colour where supported. mosquitto_sub -F '\e[92m%t \e[96m%p\e[0m' -q 2 -t '#' Files $XDG_CONFIG_HOME/mosquitto_sub $HOME/.config/mosquitto_sub Configuration file for default options. Bugs mosquitto bug information can be found at See Also mqtt 7 mosquitto_pub 1 mosquitto_rr 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/html.xsl0000664000175000017500000000122513626052637015074 0ustar rogerroger man.css ansi mosquitto-1.6.9/man/libmosquitto.3.meta0000664000175000017500000000015313626052637017143 0ustar rogerroger.. title: libmosquitto man page .. slug: libmosquitto-3 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/mosquitto_passwd.1.xml0000664000175000017500000001171713626052637017715 0ustar rogerroger mosquitto_passwd 1 Mosquitto Project Commands mosquitto_passwd manage password files for mosquitto mosquitto_passwd passwordfile username mosquitto_passwd passwordfile username password mosquitto_passwd passwordfile Description mosquitto_passwd is a tool for managing password files for the mosquitto MQTT broker. Usernames must not contain ":". Passwords are stored in a similar format to crypt3. Options Run in batch mode. This allows the password to be provided at the command line which can be convenient but should be used with care because the password will be visible on the command line and in command history. Create a new password file. If the file already exists, it will be overwritten. Delete the specified user from the password file. This option can be used to upgrade/convert a password file with plain text passwords into one using hashed passwords. It will modify the specified file. It does not detect whether passwords are already hashed, so using it on a password file that already contains hashed passwords will generate new hashes based on the old hashes and render the password file unusable. The password file to modify. The username to add/update/delete. The password to use when in batch mode. Examples Add a user to a new password file: mosquitto_passwd -c /etc/mosquitto/passwd ral Delete a user from a password file mosquitto_passwd -D /etc/mosquitto/passwd ral Bugs mosquitto bug information can be found at See Also mosquitto 8 mosquitto.conf 5 mqtt 7 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mqtt.70000664000175000017500000002053213626052637014457 0ustar rogerroger'\" t .\" Title: mqtt .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Conventions and miscellaneous .\" Source: Mosquitto Project .\" Language: English .\" .TH "MQTT" "7" "02/27/2020" "Mosquitto Project" "Conventions and miscellaneous" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mqtt \- MQ Telemetry Transport .SH "SYNOPSIS" .HP \w'\fBMQTT\fR\ 'u \fBMQTT\fR .SH "DESCRIPTION" .PP \fBMQTT\fR is a lightweight publish/subscribe messaging protocol\&. It is useful for use with low power sensors, but is applicable to many scenarios\&. .PP This manual describes some of the features of MQTT version 3\&.1\&.1/3\&.1, to assist end users in getting the most out of the protocol\&. For more complete information on MQTT, see http://mqtt\&.org/\&. .SH "PUBLISH/SUBSCRIBE" .PP The MQTT protocol is based on the principle of publishing messages and subscribing to topics, or "pub/sub"\&. Multiple clients connect to a broker and subscribe to topics that they are interested in\&. Clients also connect to the broker and publish messages to topics\&. Many clients may subscribe to the same topics and do with the information as they please\&. The broker and MQTT act as a simple, common interface for everything to connect to\&. This means that you if you have clients that dump subscribed messages to a database, to Twitter, Cosm or even a simple text file, then it becomes very simple to add new sensors or other data input to a database, Twitter or so on\&. .SH "TOPICS/SUBSCRIPTIONS" .PP Messages in MQTT are published on topics\&. There is no need to configure a topic, publishing on it is enough\&. Topics are treated as a hierarchy, using a slash (/) as a separator\&. This allows sensible arrangement of common themes to be created, much in the same way as a filesystem\&. For example, multiple computers may all publish their hard drive temperature information on the following topic, with their own computer and hard drive name being replaced as appropriate: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} sensors/COMPUTER_NAME/temperature/HARDDRIVE_NAME .RE .PP Clients can receive messages by creating subscriptions\&. A subscription may be to an explicit topic, in which case only messages to that topic will be received, or it may include wildcards\&. Two wildcards are available, \fB+\fR or \fB#\fR\&. .PP \fB+\fR can be used as a wildcard for a single level of hierarchy\&. It could be used with the topic above to get information on all computers and hard drives as follows: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} sensors/+/temperature/+ .RE .PP As another example, for a topic of "a/b/c/d", the following example subscriptions will match: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/b/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/+/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/+/+/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/+/+/+ .RE .PP The following subscriptions will not match: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} b/+/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/+/+ .RE .PP \fB#\fR can be used as a wildcard for all remaining levels of hierarchy\&. This means that it must be the final character in a subscription\&. With a topic of "a/b/c/d", the following example subscriptions will match: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c/d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} # .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/# .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/# .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} a/b/c/# .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} +/b/c/# .RE .PP Zero length topic levels are valid, which can lead to some slightly non\-obvious behaviour\&. For example, a topic of "a//topic" would correctly match against a subscription of "a/+/topic"\&. Likewise, zero length topic levels can exist at both the beginning and the end of a topic string, so "/a/topic" would match against a subscription of "+/a/topic", "#" or "/#", and a topic "a/topic/" would match against a subscription of "a/topic/+" or "a/topic/#"\&. .SH "QUALITY OF SERVICE" .PP MQTT defines three levels of Quality of Service (QoS)\&. The QoS defines how hard the broker/client will try to ensure that a message is received\&. Messages may be sent at any QoS level, and clients may attempt to subscribe to topics at any QoS level\&. This means that the client chooses the maximum QoS it will receive\&. For example, if a message is published at QoS 2 and a client is subscribed with QoS 0, the message will be delivered to that client with QoS 0\&. If a second client is also subscribed to the same topic, but with QoS 2, then it will receive the same message but with QoS 2\&. For a second example, if a client is subscribed with QoS 2 and a message is published on QoS 0, the client will receive it on QoS 0\&. .PP Higher levels of QoS are more reliable, but involve higher latency and have higher bandwidth requirements\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} 0: The broker/client will deliver the message once, with no confirmation\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} 1: The broker/client will deliver the message at least once, with confirmation required\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} 2: The broker/client will deliver the message exactly once by using a four step handshake\&. .RE .SH "RETAINED MESSAGES" .PP All messages may be set to be retained\&. This means that the broker will keep the message even after sending it to all current subscribers\&. If a new subscription is made that matches the topic of the retained message, then the message will be sent to the client\&. This is useful as a "last known good" mechanism\&. If a topic is only updated infrequently, then without a retained message, a newly subscribed client may have to wait a long time to receive an update\&. With a retained message, the client will receive an instant update\&. .SH "CLEAN SESSION / DURABLE CONNECTIONS" .PP On connection, a client sets the "clean session" flag, which is sometimes also known as the "clean start" flag\&. If clean session is set to false, then the connection is treated as durable\&. This means that when the client disconnects, any subscriptions it has will remain and any subsequent QoS 1 or 2 messages will be stored until it connects again in the future\&. If clean session is true, then all subscriptions will be removed for the client when it disconnects\&. .SH "WILLS" .PP When a client connects to a broker, it may inform the broker that it has a will\&. This is a message that it wishes the broker to send when the client disconnects unexpectedly\&. The will message has a topic, QoS and retain status just the same as any other message\&. .SH "SEE ALSO" \fBmosquitto\fR(8), \fBmosquitto_pub\fR(1), \fBmosquitto_sub\fR(1) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/mosquitto.conf.5.meta0000664000175000017500000000015713626052637017406 0ustar rogerroger.. title: mosquitto.conf man page .. slug: mosquitto-conf-5 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/mosquitto.8.xml0000664000175000017500000005130313626052637016336 0ustar rogerroger mosquitto 8 Mosquitto Project System management commands mosquitto an MQTT broker mosquitto -c config file -d --daemon -p port number -v Description mosquitto is a broker for the MQTT protocol version 3.1.1/3.1. Options Load configuration from a file. If not given, the default values as described in mosquitto.conf5 are used. Run mosquitto in the background as a daemon. All other behaviour remains the same. Listen on the port specified instead of the default 1883. This acts in addition to the port setting in the config file. May be specified multiple times to open multiple sockets listening on different ports. This socket will be bound to all network interfaces. Use verbose logging. This is equivalent to setting to in the configuration file. This overrides and logging options given in the configuration file. Configuration The broker can be configured using a configuration file as described in mosquitto.conf5 and this is the main point of information for mosquitto. The files required for SSL/TLS support are described in mosquitto-tls7. Broker Status Clients can find information about the broker by subscribing to topics in the $SYS hierarchy as follows. Topics marked as static are only sent once per client on subscription. All other topics are updated every seconds. If is 0, then updates are not sent. Note that if you are using a command line client to interact with the $SYS topics and your shell interprets $ as an environment variable, you need to place the topic in single quotes '$SYS/...' or to escape the dollar symbol: \$SYS/... otherwise the $SYS will be treated as an environment variable. The total number of bytes received since the broker started. The total number of bytes sent since the broker started. (deprecated) The number of currently connected clients. The number of disconnected persistent clients that have been expired and removed through the persistent_client_expiration option. (deprecated) The total number of persistent clients (with clean session disabled) that are registered at the broker but are currently disconnected. The maximum number of clients that have been connected to the broker at the same time. The total number of active and inactive clients currently connected and registered on the broker. When bridges are configured to/from the broker, common practice is to provide a status topic that indicates the state of the connection. This is provided within $SYS/broker/connection/ by default. If the value of the topic is 1 the connection is active, if 0 then it is not active. See the Bridges section below for more information on bridges. The current size of the heap memory in use by mosquitto. Note that this topic may be unavailable depending on compile time options. The largest amount of heap memory used by mosquitto. Note that this topic may be unavailable depending on compile time options. The moving average of the number of CONNECT packets received by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of connections received in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of bytes received by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of bytes received in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of bytes sent by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of bytes sent in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of all types of MQTT messages received by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of messages received in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of all types of MQTT messages sent by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of messages send in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of publish messages dropped by the broker over different time intervals. This shows the rate at which durable clients that are disconnected are losing messages. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of messages dropped in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of publish messages received by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of publish messages received in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of publish messages sent by the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of publish messages sent in 1 minute, averaged over 1, 5 or 15 minutes. The moving average of the number of socket connections opened to the broker over different time intervals. The final "+" of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of socket connections in 1 minute, averaged over 1, 5 or 15 minutes. The number of messages with QoS>0 that are awaiting acknowledgments. The total number of messages of any type received since the broker started. The total number of messages of any type sent since the broker started. The total number of publish messages that have been dropped due to inflight/queuing limits. See the max_inflight_messages and max_queued_messages options in mosquitto.conf5 for more information. The total number of PUBLISH messages received since the broker started. The total number of PUBLISH messages sent since the broker started. The total number of retained messages active on the broker. (deprecated) The number of messages currently held in the message store. This includes retained messages and messages queued for durable clients. The number of bytes currently held by message payloads in the message store. This includes retained messages and messages queued for durable clients. The total number of subscriptions active on the broker. The version of the broker. Static. Wildcard Topic Subscriptions In addition to allowing clients to subscribe to specific topics, mosquitto also allows the use of two wildcards in subscriptions. is the wildcard used to match a single level of hierarchy. For example, for a topic of "a/b/c/d", the following example subscriptions will match: a/b/c/d +/b/c/d a/+/c/d a/+/+/d +/+/+/+ The following subscriptions will not match: a/b/c b/+/c/d +/+/+ The second wildcard is and is used to match all subsequent levels of hierarchy. With a topic of "a/b/c/d", the following example subscriptions will match: a/b/c/d # a/# a/b/# a/b/c/# +/b/c/# The $SYS hierarchy does not match a subscription of "#". If you want to observe the entire $SYS hierarchy, subscribe to $SYS/#. Note that the wildcards must be only ever used on their own, so a subscription of "a/b+/c" is not valid use of a wildcard. The wildcard must only ever be used as the final character of a subscription. Bridges Multiple brokers can be connected together with the bridging functionality. This is useful where it is desirable to share information between locations, but where not all of the information needs to be shared. An example could be where a number of users are running a broker to help record power usage and for a number of other reasons. The power usage could be shared through bridging all of the user brokers to a common broker, allowing the power usage of all users to be collected and compared. The other information would remain local to each broker. For information on configuring bridges, see mosquitto.conf5. Signals SIGHUP Upon receiving the SIGHUP signal, mosquitto will attempt to reload configuration file data, assuming that the argument was provided when mosquitto was started. Not all configuration parameters can be reloaded without restarting. See mosquitto.conf5 for details. SIGUSR1 Upon receiving the SIGUSR1 signal, mosquitto will write the persistence database to disk. This signal is only acted upon if persistence is enabled. SIGUSR2 The SIGUSR2 signal causes mosquitto to print out the current subscription tree, along with information about where retained messages exist. This is intended as a testing feature only and may be removed at any time. Files /etc/mosquitto/mosquitto.conf Configuration file. See mosquitto.conf5. /var/lib/mosquitto/mosquitto.db Persistent message data storage location if persist enabled. /etc/hosts.allow /etc/hosts.deny Host access control via tcp-wrappers as described in hosts_access5. Bugs mosquitto bug information can be found at See Also mqtt 7 mosquitto-tls 7 mosquitto.conf 5 hosts_access 5 mosquitto_passwd 1 mosquitto_pub 1 mosquitto_rr 1 mosquitto_sub 1 libmosquitto 3 Thanks Thanks to Andy Stanford-Clark for being one of the people who came up with MQTT in the first place. Thanks to Andy and Nicholas O'Leary for providing clarifications of the protocol. Thanks also to everybody at the Ubuntu UK Podcast and Linux Outlaws for organising OggCamp, where Andy gave a talk that inspired mosquitto. Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mosquitto_rr.1.meta0000664000175000017500000000015313626052637017155 0ustar rogerroger.. title: mosquitto_rr man page .. slug: mosquitto_rr-1 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/mosquitto_sub.10000664000175000017500000007453613626052637016416 0ustar rogerroger'\" t .\" Title: mosquitto_sub .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_SUB" "1" "02/27/2020" "Mosquitto Project" "Commands" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto_sub \- an MQTT version 5/3\&.1\&.1/3\&.1 client for subscribing to topics .SH "SYNOPSIS" .HP \w'\fBmosquitto_sub\fR\ 'u \fBmosquitto_sub\fR {[\fB\-h\fR\ \fIhostname\fR]\ [\fB\-p\fR\ \fIport\-number\fR]\ [\fB\-u\fR\ \fIusername\fR]\ [\fB\-P\fR\ \fIpassword\fR]\ \fB\-t\fR\ \fImessage\-topic\fR... | \fB\-L\fR\ \fIURL\fR\ [\fB\-t\fR\ \fImessage\-topic\fR...] } [\fB\-A\fR\ \fIbind\-address\fR] [\fB\-c\fR] [\fB\-C\fR\ \fImsg\-count\fR] [\fB\-d\fR] [\fB\-D\fR\ \fIcommand\fR\ \fIidentifier\fR\ \fIvalue\fR] [\fB\-E\fR] [\fB\-i\fR\ \fIclient\-id\fR] [\fB\-I\fR\ \fIclient\-id\-prefix\fR] [\fB\-k\fR\ \fIkeepalive\-time\fR] [\fB\-N\fR] [\fB\-q\fR\ \fImessage\-QoS\fR] [\fB\-\-remove\-retained\fR] [\fB\-R\fR | \fB\-\-retained\-only\fR] [\fB\-\-retain\-as\-published\fR] [\fB\-S\fR] [\fB\-T\fR\ \fIfilter\-out\fR...] [\fB\-U\fR\ \fIunsub\-topic\fR...] [\fB\-v\fR] [\fB\-V\fR\ \fIprotocol\-version\fR] [\fB\-W\fR\ \fImessage\-processing\-timeout\fR] [\fB\-\-proxy\fR\ \fIsocks\-url\fR] [\fB\-\-quiet\fR] [\fB\-\-will\-topic\fR\ \fItopic\fR\ [\fB\-\-will\-payload\fR\ \fIpayload\fR]\ [\fB\-\-will\-qos\fR\ \fIqos\fR]\ [\fB\-\-will\-retain\fR]] [[{\fB\-\-cafile\fR\ \fIfile\fR\ |\ \fB\-\-capath\fR\ \fIdir\fR}\ [\fB\-\-cert\fR\ \fIfile\fR]\ [\fB\-\-key\fR\ \fIfile\fR]\ [\fB\-\-tls\-version\fR\ \fIversion\fR]\ [\fB\-\-tls\-alpn\fR\ \fIprotocol\fR]\ [\fB\-\-tls\-engine\fR\ \fIengine\fR]\ [\fB\-\-keyform\fR\ {\fIpem\fR\ |\ \fIengine\fR}]\ [\fB\-\-tls\-engine\-kpass\-sha1\fR\ \fIkpass\-sha1\fR]\ [\fB\-\-insecure\fR]] | [\fB\-\-psk\fR\ \fIhex\-key\fR\ \fB\-\-psk\-identity\fR\ \fIidentity\fR\ [\fB\-\-tls\-version\fR\ \fIversion\fR]]] .HP \w'\fBmosquitto_sub\fR\ 'u \fBmosquitto_sub\fR [\fB\-\-help\fR] .SH "DESCRIPTION" .PP \fBmosquitto_sub\fR is a simple MQTT version 5/3\&.1\&.1 client that will subscribe to topics and print the messages that it receives\&. .PP In addition to subscribing to topics, \fBmosquitto_sub\fR can filter out received messages so they are not printed (see the \fB\-T\fR option) or unsubscribe from topics (see the \fB\-U\fR option)\&. Unsubscribing from topics is useful for clients connecting with clean session set to false\&. .SH "ENCRYPTED CONNECTIONS" .PP \fBmosquitto_sub\fR supports TLS encrypted connections\&. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup\&. .PP To enable TLS connections when using x509 certificates, one of either \fB\-\-cafile\fR or \fB\-\-capath\fR must be provided as an option\&. .PP To enable TLS connections when using TLS\-PSK, you must use the \fB\-\-psk\fR and the \fB\-\-psk\-identity\fR options\&. .SH "OPTIONS" .PP The options below may be given on the command line, but may also be placed in a config file located at \fB$XDG_CONFIG_HOME/mosquitto_sub\fR or \fB$HOME/\&.config/mosquitto_sub\fR with one pair of \fB\-option \fR\fB\fIvalue\fR\fR per line\&. The values in the config file will be used as defaults and can be overridden by using the command line\&. The exceptions to this are \fB\-t\fR and \fB\-T\fR, which if given in the config file will not be overridden\&. Note also that currently some options cannot be negated, e\&.g\&. \fB\-S\fR\&. Config file lines that have a \fB#\fR as the first character are treated as comments and not processed any further\&. .PP \fB\-A\fR .RS 4 Bind the outgoing connection to a local ip address/hostname\&. Use this argument if you need to restrict network communication to a particular interface\&. .RE .PP \fB\-c\fR, \fB\-\-disable\-clean\-session\fR .RS 4 Disable the \*(Aqclean session\*(Aq flag\&. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive\&. When the client reconnects, it will receive all of the queued messages\&. .sp If using this option, the client id must be set manually with \fB\-\-id\fR .RE .PP \fB\-\-cafile\fR .RS 4 Define the path to a file containing PEM encoded CA certificates that are trusted\&. Used to enable SSL communication\&. .sp See also \fB\-\-capath\fR .RE .PP \fB\-\-capath\fR .RS 4 Define the path to a directory containing PEM encoded CA certificates that are trusted\&. Used to enable SSL communication\&. .sp For \fB\-\-capath\fR to work correctly, the certificate files must have "\&.crt" as the file ending and you must run "openssl rehash " each time you add/remove a certificate\&. .sp See also \fB\-\-cafile\fR .RE .PP \fB\-\-cert\fR .RS 4 Define the path to a file containing a PEM encoded certificate for this client, if required by the server\&. .sp See also \fB\-\-key\fR\&. .RE .PP \fB\-\-ciphers\fR .RS 4 An openssl compatible list of TLS ciphers to support in the client\&. See \fBciphers\fR(1) for more information\&. .RE .PP \fB\-C\fR .RS 4 Disconnect and exit the program immediately after the given count of messages have been received\&. This may be useful in shell scripts where on a single status value is required, for example\&. .sp Combine with \fB\-R\fR to print only the first set of fresh messages (i\&.e\&. that does not have the retained flag set), or with \fB\-T\fR to filter which topics are processed\&. .RE .PP \fB\-d\fR, \fB\-\-debug\fR .RS 4 Enable debug messages\&. .RE .PP \fB\-D\fR, \fB\-\-property\fR .RS 4 Use an MQTT v5 property with this publish\&. If you use this option, the client will be set to be an MQTT v5 client\&. This option has two forms: .sp \fB\-D command identifier value\fR .sp \fB\-D command identifier name value\fR .sp \fBcommand\fR is the MQTT command/packet identifier and can be one of CONNECT, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL\&. The properties available for each command are listed in the Properties section\&. .sp \fBidentifier\fR is the name of the property to add\&. This is as described in the specification, but with \*(Aq\-\*(Aq as a word separator\&. For example: \fBpayload\-format\-indicator\fR\&. More details are in the Properties section\&. .sp \fBvalue\fR is the value of the property to add, with a data type that is property specific\&. .sp \fBname\fR is only used for the \fBuser\-property\fR property as the first of the two strings in the string pair\&. In that case, \fBvalue\fR is the second of the strings in the pair\&. .RE .PP \fB\-E\fR .RS 4 If this option is given, \fBmosquitto_sub\fR will exit immediately that all of its subscriptions have been acknowledged by the broker\&. In conjunction with \fB\-c\fR this allows a durable client session to be initialised on the broker for future use without requiring any messages to be received\&. .RE .PP \fB\-F\fR .RS 4 Specify output printing format\&. This option allows you to choose what information from each message is printed to the screen\&. See the Output Format section below for full details\&. .sp This option overrides the \fB\-v\fR option, but does not override the \fB\-N\fR option\&. .RE .PP \fB\-\-help\fR .RS 4 Display usage information\&. .RE .PP \fB\-h\fR, \fB\-\-host\fR .RS 4 Specify the host to connect to\&. Defaults to localhost\&. .RE .PP \fB\-i\fR, \fB\-\-id\fR .RS 4 The id to use for this client\&. If not given, a client id will be generated depending on the MQTT version being used\&. For v3\&.1\&.1/v3\&.1, the client generates a client id in the format \fBmosq\-XXXXXXXXXXXXXXXXXX\fR, where the \fBX\fR are replaced with random alphanumeric characters\&. For v5\&.0, the client sends a zero length client id, and the server will generate a client id for the client\&. .sp This option cannot be used at the same time as the \fB\-\-id\-prefix\fR argument\&. .RE .PP \fB\-I\fR, \fB\-\-id\-prefix\fR .RS 4 Provide a prefix that the client id will be built from by appending the process id of the client\&. This is useful where the broker is using the clientid_prefixes option\&. Cannot be used at the same time as the \fB\-\-id\fR argument\&. .RE .PP \fB\-\-insecure\fR .RS 4 When using certificate based encryption, this option disables verification of the server hostname in the server certificate\&. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example\&. Use this option in testing \fIonly\fR\&. If you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption\&. .RE .PP \fB\-k\fR, \fB\-\-keepalive\fR .RS 4 The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning\&. Defaults to 60 seconds\&. .RE .PP \fB\-\-key\fR .RS 4 Define the path to a file containing a PEM encoded private key for this client, if required by the server\&. .sp See also \fB\-\-cert\fR\&. .RE .PP \fB\-\-keyform\fR .RS 4 Specifies the type of private key in use when making TLS connections\&.\&. This can be "pem" or "engine"\&. This parameter is useful when a TPM module is being used and the private key has been created with it\&. Defaults to "pem", which means normal private key files are used\&. .sp See also \fB\-\-tls\-engine\fR\&. .RE .PP \fB\-L\fR, \fB\-\-url\fR .RS 4 Specify specify user, password, hostname, port and topic at once as a URL\&. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic .sp If the scheme is mqtt:// then the port defaults to 1883\&. If the scheme is mqtts:// then the port defaults to 8883\&. .RE .PP \fB\-N\fR .RS 4 Do not append an end of line character to the payload when printing\&. This allows streaming of payload data from multiple messages directly to another application unmodified\&. Only really makes sense when not using \fB\-v\fR\&. .RE .PP \fB\-p\fR, \fB\-\-port\fR .RS 4 Connect to the port specified\&. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used\&. .RE .PP \fB\-P\fR, \fB\-\-pw\fR .RS 4 Provide a password to be used for authenticating with the broker\&. Using this argument without also specifying a username is invalid when using MQTT v3\&.1 or v3\&.1\&.1\&. See also the \fB\-\-username\fR option\&. .RE .PP \fB\-\-proxy\fR .RS 4 Specify a SOCKS5 proxy to connect through\&. "None" and "username" authentication types are supported\&. The \fBsocks\-url\fR must be of the form \fBsocks5h://[username[:password]@]host[:port]\fR\&. The protocol prefix \fBsocks5h\fR means that hostnames are resolved by the proxy\&. The symbols %25, %3A and %40 are URL decoded into %, : and @ respectively, if present in the username or password\&. .sp If username is not given, then no authentication is attempted\&. If the port is not given, then the default of 1080 is used\&. .sp More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in \fBcurl\fR(1)\&. .RE .PP \fB\-\-psk\fR .RS 4 Provide the hexadecimal (no leading 0x) pre\-shared\-key matching the one used on the broker to use TLS\-PSK encryption support\&. \fB\-\-psk\-identity\fR must also be provided to enable TLS\-PSK\&. .RE .PP \fB\-\-psk\-identity\fR .RS 4 The client identity to use with TLS\-PSK support\&. This may be used instead of a username if the broker is configured to do so\&. .RE .PP \fB\-q\fR, \fB\-\-qos\fR .RS 4 Specify the quality of service desired for the incoming messages, from 0, 1 and 2\&. Defaults to 0\&. See \fBmqtt\fR(7) for more information on QoS\&. .sp The QoS is identical for all topics subscribed to in a single instance of mosquitto_sub\&. .RE .PP \fB\-\-quiet\fR .RS 4 If this argument is given, no runtime errors will be printed\&. This excludes any error messages given in case of invalid user input (e\&.g\&. using \fB\-\-port\fR without a port)\&. .RE .PP \fB\-R\fR .RS 4 If this argument is given, messages that are received that have the retain bit set will not be printed\&. Messages with retain set are "stale", in that it is not known when they were originally published\&. When subscribing to a wildcard topic there may be a large number of retained messages\&. This argument suppresses their display\&. .RE .PP \fB\-\-remove\-retained\fR .RS 4 If this argument is given, the when mosquitto_sub receives a message with the retained bit set, it will send a message to the broker to clear that retained message\&. This applies to all received messages except those that are filtered out by the \fB\-T\fR option\&. This option still takes effect even if \fB\-R\fR is used\&. See also the \fB\-\-retain\-as\-published\fR and \fB\-\-retained\-only\fR options\&. .PP \fBExample\ \&1.\ \&\fR Remove all retained messages on the server, assuming we have access to do so, and then exit: .sp .if n \{\ .RS 4 .\} .nf mosquitto_sub \-t \*(Aq#\*(Aq \-\-remove\-retained \-\-retained\-only .fi .if n \{\ .RE .\} .PP \fBExample\ \&2.\ \&\fR Remove a whole tree, with the exception of a single topic: .sp .if n \{\ .RS 4 .\} .nf mosquitto_sub \-t \*(Aqbbc/#\*(Aq \-T bbc/bbc1 \-\-remove\-retained .fi .if n \{\ .RE .\} .RE .PP \fB\-\-retained\-only\fR .RS 4 If this argument is given, only messages that are received that have the retain bit set will be printed\&. Messages with retain set are "stale", in that it is not known when they were originally published\&. With this argument in use, the receipt of the first non\-stale message will cause the client to exit\&. See also the \fB\-\-retain\-as\-published\fR option\&. .RE .PP \fB\-\-retain\-as\-published\fR .RS 4 If this argument is given, the subscriptions will have the "retain as published" option set\&. This means that the retain flag on an incoming message will be exactly as set by the publishing client, rather than indicating whether the message is fresh/stale\&. .sp This option is not valid for MQTT v3\&.1/v3\&.1\&.1 clients\&. .RE .PP \fB\-S\fR .RS 4 Use SRV lookups to determine which host to connect to\&. Performs lookups to \fB_mqtt\&._tcp\&.\fR when used in conjunction with \fB\-h\fR, otherwise uses \fB_mqtt\&._tcp\&.\fR\&. .RE .PP \fB\-t\fR, \fB\-\-topic\fR .RS 4 The MQTT topic to subscribe to\&. See \fBmqtt\fR(7) for more information on MQTT topics\&. .sp This option may be repeated to subscribe to multiple topics\&. .RE .PP \fB\-T\fR, \fB\-\-filter\-out\fR .RS 4 Suppress printing of topics that match the filter\&. This allows subscribing to a wildcard topic and only printing a partial set of the wildcard hierarchy\&. .sp For example, subscribe to the BBC tree, but suppress output from Radio 3: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-t bbc/# \-T bbc/radio3 .RE .sp This option may be repeated to filter out multiple topics or topic trees\&. .RE .PP \fB\-\-tls\-alpn\fR .RS 4 Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e\&.g\&. MQTT and WebSockets\&. .RE .PP \fB\-\-tls\-engine\fR .RS 4 A valid openssl engine id\&. These can be listed with openssl engine command\&. .sp See also \fB\-\-keyform\fR\&. .RE .PP \fB\-\-tls\-engine\-kpass\-sha1\fR .RS 4 SHA1 of the private key password when using an TLS engine\&. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed\&. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password\&. .sp See also \fB\-\-tls\-engine\fR\&. .RE .PP \fB\-\-tls\-version\fR .RS 4 Choose which TLS protocol version to use when communicating with the broker\&. Valid options are \fBtlsv1\&.3\fR, \fBtlsv1\&.2\fR and \fBtlsv1\&.1\fR\&. The default value is \fBtlsv1\&.2\fR\&. Must match the protocol version used by the broker\&. .RE .PP \fB\-u\fR, \fB\-\-username\fR .RS 4 Provide a username to be used for authenticating with the broker\&. See also the \fB\-\-pw\fR argument\&. .RE .PP \fB\-U\fR, \fB\-\-unsubscribe\fR .RS 4 A topic that will be unsubscribed from\&. This may be used on its own or in conjunction with the \fB\-\-topic\fR option and only makes sense when used in conjunction with \fB\-\-clean\-session\fR\&. .sp If used with \fB\-\-topic\fR then subscriptions will be processed before unsubscriptions\&. .sp Note that it is only possible to unsubscribe from subscriptions that have previously been made\&. It is not possible to punch holes in wildcard subscriptions\&. For example, subscribing to \fBsensors/#\fR and then unsubscribing from \fBsensors/+/temperature\fR as shown below will still result in messages matching the \fBsensors/+/temperature\fR being delivered to the client\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-t sensors/# \-U sensors/+/temperature \-v .RE .sp Note also that because retained messages are published by the broker on receipt of a SUBSCRIBE command, subscribing and unsubscribing to the same topic may result in messages being received at the client\&. .sp This option may be repeated to unsubscribe from multiple topics\&. .RE .PP \fB\-v\fR, \fB\-\-verbose\fR .RS 4 Print received messages verbosely\&. With this argument, messages will be printed as "topic payload"\&. When this argument is not given, the messages are printed as "payload"\&. .RE .PP \fB\-V\fR, \fB\-\-protocol\-version\fR .RS 4 Specify which version of the MQTT protocol should be used when connecting to the remote broker\&. Can be \fB5\fR, \fB311\fR, \fB31\fR, or the more verbose \fBmqttv5\fR, \fBmqttv311\fR, or \fBmqttv31\fR\&. Defaults to \fB311\fR\&. .RE .PP \fB\-W\fR .RS 4 Provide a timeout as an integer number of seconds\&. mosquitto_sub will stop processing messages and disconnect after this number of seconds has passed\&. The timeout starts just after the client has connected to the broker\&. .RE .PP \fB\-\-will\-payload\fR .RS 4 Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-qos\fR .RS 4 The QoS to use for the Will\&. Defaults to 0\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-retain\fR .RS 4 If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-topic\fR .RS 4 The topic on which to send a Will, in the event that the client disconnects unexpectedly\&. .RE .SH "OUTPUT FORMAT" .PP There are three ways of formatting the output from mosquitto_sub\&. In all cases a new\-line character is appended for each message received unless the \fB\-N\fR argument is passed to mosquitto_sub\&. .PP Payload\-only is the default output format and will print the payload exactly as it is received\&. .PP Verbose mode is activated with \fB\-v\fR and prints the message topic and the payload, separated by a space\&. .PP The final option is formatted output, which allows the user to define a custom output format\&. The behaviour is controlled with the \fB\-F format\-string\fR option\&. The format string is a free text string where interpreted sequences are replaced by different parameters\&. The available interpreted sequences are described below\&. .PP Three characters are used to start an interpreted sequence: \fB%\fR, \fB@\fR and \fB\e\fR\&. Sequences starting with \fB%\fR are either parameters related to the MQTT message being printed, or are helper sequences to avoid the need to type long date format strings for example\&. Sequences starting with \fB@\fR are passed to the \fBstrftime\fR(3) function (with the @ replaced with a % \- note that only the character immediately after the @ is passed to strftime)\&. This allows the construction of a wide variety of time based outputs\&. The output options for strftime vary from platform to platform, so please check what is available for your platform\&. mosquitto_sub does provide one extension to strftime which is \fB@N\fR, which can be used to obtain the number of nanoseconds passed in the current second\&. The resolution of this option varies depending on the platform\&. The final sequence character is \fB\e\fR, which is used to input some characters that would otherwise be difficult to enter\&. .SS "MQTT related parameters" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%%\fR a literal %\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%l\fR the length of the payload in bytes\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%m\fR the message id (only relevant for messages with QoS>0)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%p\fR the payload raw bytes (may produce non\-printable characters depending on the payload)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%q\fR the message QoS\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%r\fR the retained flag for the message\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%t\fR the message topic\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%x\fR the payload with each byte as a hexadecimal number (lower case)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%X\fR the payload with each byte as a hexadecimal number (upper case)\&. .RE .SS "Helpers" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%I\fR ISO\-8601 format date and time, e\&.g\&. 2016\-08\-10T09:47:38+0100 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%j\fR JSON output of message parameters and timestamp, with a quoted and escaped payload\&. For example {"tst":1470825369,"topic":"greeting","qos":0,"retain":0,"payload":"hello world"} .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%J\fR JSON output of message parameters and timestamp, with a non\-quoted and non\-escaped payload \- this means the payload must itself be valid JSON\&. For example: {"tst":1470825369,"topic":"foo","qos":0,"retain":0,"payload":{"temperature":27\&.0,"humidity":57}}\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%I\fR ISO\-8601 format date and time, e\&.g\&. 2016\-08\-10T09:47:38+0100 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%U\fR Unix timestamp with nanoseconds, e\&.g\&. 1470818943\&.786368637 .RE .SS "Time related parameters" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB@@\fR a literal @\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB@X\fR pass the character represented by \fBX\fR to the strftime function as \fB%X\fR\&. The options supported are platform dependent\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB@N\fR the number of nanoseconds that have passed in the current second, with varying timing resolution depending on platform\&. .RE .SS "Escape characters" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\e\e\fR a literal \e\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\e0\fR a null character\&. Can be used to separate different parameters that may contain spaces (e\&.g\&. topic, payload) so that processing with tools such as \fBxargs\fR(1) is easier\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\ea\fR alert/bell\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\ee\fR the escape sequence, which can be used with ANSI colour codes to provide coloured output for example\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\en\fR end of line\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\er\fR carriage return\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\et\fR horizontal tab\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\ev\fR vertical tab\&. .RE .SH "WILLS" .PP mosquitto_sub can register a message with the broker that will be sent out if it disconnects unexpectedly\&. See \fBmqtt\fR(7) for more information\&. .PP The minimum requirement for this is to use \fB\-\-will\-topic\fR to specify which topic the will should be sent out on\&. This will result in a non\-retained, zero length message with QoS 0\&. .PP Use the \fB\-\-will\-retain\fR, \fB\-\-will\-payload\fR and \fB\-\-will\-qos\fR arguments to modify the other will parameters\&. .SH "PROPERTIES" .PP The \fB\-D\fR / \fB\-\-property\fR option allows adding properties to different stages of the mosquitto_sub run\&. The properties supported for each command are as follows: .SS "Connect" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBauthentication\-data\fR (binary data \- note treated as a string in mosquitto_sub) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBauthentication\-method\fR (UTF\-8 string pair) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmaximum\-packet\-size\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBreceive\-maximum\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBrequest\-problem\-information\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBrequest\-response\-information\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBsession\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBtopic\-alias\-maximum\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Subscribe" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Unsubscribe" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Disconnect" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBsession\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Will properties" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcontent\-type\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcorrelation\-data\fR (binary data \- note treated as a string in mosquitto_sub) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmessage\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBpayload\-format\-indicator\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBresponse\-topic\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBwill\-delay\-interval\fR (32\-bit unsigned integer) .RE .SH "EXAMPLES" .PP Note that these really are examples \- the subscriptions will work if you run them as shown, but there must be something publishing messages on those topics for you to receive anything\&. .PP Subscribe to temperature information on localhost with QoS 1: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-t sensors/temperature \-q 1 .RE .PP Subscribe to hard drive temperature updates on multiple machines/hard drives\&. This expects each machine to be publishing its hard drive temperature to sensors/machines/HOSTNAME/temperature/HD_NAME\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-t sensors/machines/+/temperature/+ .RE .PP Subscribe to all broker status messages: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-v \-t \e$SYS/# .RE .PP Specify the output format as "ISO\-8601 date : topic : payload in hex" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-F \*(Aq@Y\-@m\-@dT@H:@M:@S@z : %t : %x\*(Aq \-t \*(Aq#\*(Aq .RE .PP Specify the output format as "seconds since epoch\&.nanoseconds : retained flag : qos : mid : payload length" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-F \*(Aq%@s\&.@N : %r : %q : %m : %l\*(Aq \-q 2 \-t \*(Aq#\*(Aq .RE .PP Topic and payload output, but with colour where supported\&. .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_sub \-F \*(Aq\ee[92m%t \ee[96m%p\ee[0m\*(Aq \-q 2 \-t \*(Aq#\*(Aq .RE .SH "FILES" .PP $XDG_CONFIG_HOME/mosquitto_sub, $HOME/\&.config/mosquitto_sub .RS 4 Configuration file for default options\&. .RE .SH "BUGS" .PP \fBmosquitto\fR bug information can be found at \m[blue]\fB\%https://github.com/eclipse/mosquitto/issues\fR\m[] .SH "SEE ALSO" \fBmqtt\fR(7), \fBmosquitto_pub\fR(1), \fBmosquitto_rr\fR(1), \fBmosquitto\fR(8), \fBlibmosquitto\fR(3), \fBmosquitto-tls\fR(7) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/mosquitto_rr.1.xml0000664000175000017500000010660613626052637017041 0ustar rogerroger mosquitto_rr 1 Mosquitto Project Commands mosquitto_rr an MQTT version 5/3.1.1 client for request/response messaging mosquitto_rr hostname port-number username password message-topic URL message-topic response-topic file message bind-address command identifier value client-id client-id-prefix keepalive-time message-QoS protocol-version message-processing-timeout socks-url topic payload qos file dir file file ciphers version protocol engine pem engine kpass-sha1 hex-key identity ciphers version mosquitto_rr Description mosquitto_rr is an MQTT version 5/3.1.1 client that can be used to publish a request message and wait for a response. When using MQTT v5, which is the default, mosquitto_rr will use the Request-Response feature. Encrypted Connections mosquitto_rr supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup. To enable TLS connections when using x509 certificates, one of either or must be provided as an option. To enable TLS connections when using TLS-PSK, you must use the and the options. Options The options below may be given on the command line, but may also be placed in a config file located at or with one pair of per line. The values in the config file will be used as defaults and can be overridden by using the command line. The exceptions to this is , which if given in the config file will not be overridden. Note also that currently some options cannot be negated, e.g. . Config file lines that have a as the first character are treated as comments and not processed any further. Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface. Disable the 'clean session' flag. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive. When the client reconnects, it will receive all of the queued messages. If using this option, the client id must be set manually with Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. See also Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. For to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a certificate. See also Define the path to a file containing a PEM encoded certificate for this client, if required by the server. See also . An openssl compatible list of TLS ciphers to support in the client. See ciphers1 for more information. Enable debug messages. Use an MQTT v5 property with this publish. If you use this option, the client will be set to be an MQTT v5 client. This option has two forms: is the MQTT command/packet identifier and can be one of CONNECT, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL. The properties available for each command are listed in the Properties section. is the name of the property to add. This is as described in the specification, but with '-' as a word separator. For example: . More details are in the Properties section. is the value of the property to add, with a data type that is property specific. is only used for the property as the first of the two strings in the string pair. In that case, is the second of the strings in the pair. Send the contents of a file as the request message. Specify output printing format. This option allows you to choose what information from each message is printed to the screen. See the Output Format section below for full details. This option overrides the option, but does not override the option. Display usage information. Specify the host to connect to. Defaults to localhost. The id to use for this client. If not given, a client id will be generated depending on the MQTT version being used. For v3.1.1/v3.1, the client generates a client id in the format , where the are replaced with random alphanumeric characters. For v5.0, the client sends a zero length client id, and the server will generate a client id for the client. This option cannot be used at the same time as the argument. Provide a prefix that the client id will be built from by appending the process id of the client. This is useful where the broker is using the clientid_prefixes option. Cannot be used at the same time as the argument. When using certificate based encryption, this option disables verification of the server hostname in the server certificate. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only. If you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption. The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. Defaults to 60 seconds. Define the path to a file containing a PEM encoded private key for this client, if required by the server. See also . Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the private key has been created with it. Defaults to "pem", which means normal private key files are used. See also . Specify specify user, password, hostname, port and topic at once as a URL. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883. Send a single request message from the command line. Do not append an end of line character to the payload when printing. This allows streaming of payload data from multiple messages directly to another application unmodified. Only really makes sense when not using . Send a null (zero length) request message. Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used. Provide a password to be used for authenticating with the broker. Using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. See also the option. Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The must be of the form . The protocol prefix means that hostnames are resolved by the proxy. The symbols %25, %3A and %40 are URL decoded into %, : and @ respectively, if present in the username or password. If username is not given, then no authentication is attempted. If the port is not given, then the default of 1080 is used. More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl 1 . Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support. must also be provided to enable TLS-PSK. The client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so. Specify the quality of service desired for the incoming messages, from 0, 1 and 2. Defaults to 0. See mqtt7 for more information on QoS. The QoS is identical for all topics subscribed to in a single instance of mosquitto_rr. If this argument is given, no runtime errors will be printed. This excludes any error messages given in case of invalid user input (e.g. using without a port). If this argument is given, messages that are received that have the retain bit set will not be printed. Messages with retain set are "stale", in that it is not known when they were originally published. When subscribing to a wildcard topic there may be a large number of retained messages. This argument suppresses their display. Use SRV lookups to determine which host to connect to. Performs lookups to when used in conjunction with , otherwise uses . Send a request message read from stdin, sending the entire content as a single message. The MQTT topic to subscribe to, where responses will be waited for. See mqtt7 for more information on MQTT topics. This option may be repeated to subscribe to multiple topics. Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets. A valid openssl engine id. These can be listed with openssl engine command. See also . SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password. See also . Choose which TLS protocol version to use when communicating with the broker. Valid options are , and . The default value is . Must match the protocol version used by the broker. Provide a username to be used for authenticating with the broker. See also the argument. Print received messages verbosely. With this argument, messages will be printed as "topic payload". When this argument is not given, the messages are printed as "payload". Specify which version of the MQTT protocol should be used when connecting to the rmeote broker. Can be , , , or the more verbose , , or . Defaults to . Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with . The QoS to use for the Will. Defaults to 0. This must be used in conjunction with . If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with . The topic on which to send a Will, in the event that the client disconnects unexpectedly. Output format There are three ways of formatting the output from mosquitto_rr. In all cases a new-line character is appended for each message received unless the argument is passed to mosquitto_rr. Payload-only is the default output format and will print the payload exactly as it is received. Verbose mode is activated with and prints the message topic and the payload, separated by a space. The final option is formatted output, which allows the user to define a custom output format. The behaviour is controlled with the option. The format string is a free text string where interpreted sequences are replaced by different parameters. The available interpreted sequences are described below. Three characters are used to start an interpreted sequence: , and . Sequences starting with are either parameters related to the MQTT message being printed, or are helper sequences to avoid the need to type long date format strings for example. Sequences starting with are passed to the strftime3 function (with the @ replaced with a % - note that only the character immediately after the @ is passed to strftime). This allows the construction of a wide variety of time based outputs. The output options for strftime vary from platform to platform, so please check what is available for your platform. mosquitto_rr does provide one extension to strftime which is , which can be used to obtain the number of nanoseconds passed in the current second. The resolution of this option varies depending on the platform. The final sequence character is , which is used to input some characters that would otherwise be difficult to enter. MQTT related parameters a literal %. the length of the payload in bytes. the message id (only relevant for messages with QoS>0). the payload raw bytes (may produce non-printable characters depending on the payload). the message QoS. the retained flag for the message. the message topic. the payload with each byte as a hexadecimal number (lower case). the payload with each byte as a hexadecimal number (upper case). Helpers ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100 JSON output of message parameters and timestamp, with a quoted and escaped payload. For example {"tst":1470825369,"topic":"greeting","qos":0,"retain":0,"payload":"hello world"} JSON output of message parameters and timestamp, with a non-quoted and non-escaped payload - this means the payload must itself be valid JSON. For example: {"tst":1470825369,"topic":"foo","qos":0,"retain":0,"payload":{"temperature":27.0,"humidity":57}}. ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100 Unix timestamp with nanoseconds, e.g. 1470818943.786368637 Time related parameters a literal @. pass the character represented by to the strftime function as . The options supported are platform dependent. the number of nanoseconds that have passed in the current second, with varying timing resolution depending on platform. Escape characters a literal \. a null character. Can be used to separate different parameters that may contain spaces (e.g. topic, payload) so that processing with tools such as xargs1 is easier. alert/bell. the escape sequence, which can be used with ANSI colour codes to provide coloured output for example. end of line. carriage return. horizontal tab. vertical tab. Wills mosquitto_rr can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt7 for more information. The minimum requirement for this is to use to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS 0. Use the , and arguments to modify the other will parameters. Properties The / option allows adding properties to different stages of the mosquitto_rr run. The properties supported for each command are as follows: Connect (binary data - note treated as a string in mosquitto_rr) (UTF-8 string pair) (32-bit unsigned integer) (16-bit unsigned integer) (8-bit unsigned integer) (8-bit unsigned integer) (32-bit unsigned integer) (16-bit unsigned integer) (UTF-8 string pair) Publish (UTF-8 string) (binary data - note treated as a string in mosquitto_rr) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (16-bit unsigned integer) (UTF-8 string pair) Subscribe (UTF-8 string pair) Unsubscribe (UTF-8 string pair) Disconnect (32-bit unsigned integer) (UTF-8 string pair) Will properties (UTF-8 string) (binary data - note treated as a string in mosquitto_pub) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (UTF-8 string pair) (32-bit unsigned integer) Files $XDG_CONFIG_HOME/mosquitto_rr $HOME/.config/mosquitto_rr Configuration file for default options. Bugs mosquitto bug information can be found at See Also mqtt 7 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mosquitto_pub.1.meta0000664000175000017500000000015513626052637017322 0ustar rogerroger.. title: mosquitto_pub man page .. slug: mosquitto_pub-1 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/mosquitto_rr.10000664000175000017500000006331113626052637016235 0ustar rogerroger'\" t .\" Title: mosquitto_rr .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_RR" "1" "02/27/2020" "Mosquitto Project" "Commands" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto_rr \- an MQTT version 5/3\&.1\&.1 client for request/response messaging .SH "SYNOPSIS" .HP \w'\fBmosquitto_rr\fR\ 'u \fBmosquitto_rr\fR {[\fB\-h\fR\ \fIhostname\fR]\ [\fB\-p\fR\ \fIport\-number\fR]\ [\fB\-u\fR\ \fIusername\fR]\ [\fB\-P\fR\ \fIpassword\fR]\ \fB\-t\fR\ \fImessage\-topic\fR... | \fB\-L\fR\ \fIURL\fR\ [\fB\-t\fR\ \fImessage\-topic\fR...] | [\fB\-e\fR\ \fIresponse\-topic\fR]} {\fB\-f\fR\ \fIfile\fR | \fB\-m\fR\ \fImessage\fR | \fB\-n\fR | \fB\-s\fR} [\fB\-A\fR\ \fIbind\-address\fR] [\fB\-c\fR] [\fB\-d\fR] [\fB\-D\fR\ \fIcommand\fR\ \fIidentifier\fR\ \fIvalue\fR] [\fB\-i\fR\ \fIclient\-id\fR] [\fB\-I\fR\ \fIclient\-id\-prefix\fR] [\fB\-k\fR\ \fIkeepalive\-time\fR] [\fB\-N\fR] [\fB\-q\fR\ \fImessage\-QoS\fR] [\fB\-R\fR] [\fB\-S\fR] [\fB\-v\fR] [\fB\-V\fR\ \fIprotocol\-version\fR] [\fB\-W\fR\ \fImessage\-processing\-timeout\fR] [\fB\-\-proxy\fR\ \fIsocks\-url\fR] [\fB\-\-quiet\fR] [\fB\-\-will\-topic\fR\ \fItopic\fR\ [\fB\-\-will\-payload\fR\ \fIpayload\fR]\ [\fB\-\-will\-qos\fR\ \fIqos\fR]\ [\fB\-\-will\-retain\fR]] [[{\fB\-\-cafile\fR\ \fIfile\fR\ |\ \fB\-\-capath\fR\ \fIdir\fR}\ [\fB\-\-cert\fR\ \fIfile\fR]\ [\fB\-\-key\fR\ \fIfile\fR]\ [\fB\-\-ciphers\fR\ \fIciphers\fR]\ [\fB\-\-tls\-version\fR\ \fIversion\fR]\ [\fB\-\-tls\-alpn\fR\ \fIprotocol\fR]\ [\fB\-\-tls\-engine\fR\ \fIengine\fR]\ [\fB\-\-keyform\fR\ {\fIpem\fR\ |\ \fIengine\fR}]\ [\fB\-\-tls\-engine\-kpass\-sha1\fR\ \fIkpass\-sha1\fR]\ [\fB\-\-insecure\fR]] | [\fB\-\-psk\fR\ \fIhex\-key\fR\ \fB\-\-psk\-identity\fR\ \fIidentity\fR\ [\fB\-\-ciphers\fR\ \fIciphers\fR]\ [\fB\-\-tls\-version\fR\ \fIversion\fR]]] .HP \w'\fBmosquitto_rr\fR\ 'u \fBmosquitto_rr\fR [\fB\-\-help\fR] .SH "DESCRIPTION" .PP \fBmosquitto_rr\fR is an MQTT version 5/3\&.1\&.1 client that can be used to publish a request message and wait for a response\&. When using MQTT v5, which is the default, \fBmosquitto_rr\fR will use the Request\-Response feature\&. .SH "ENCRYPTED CONNECTIONS" .PP \fBmosquitto_rr\fR supports TLS encrypted connections\&. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup\&. .PP To enable TLS connections when using x509 certificates, one of either \fB\-\-cafile\fR or \fB\-\-capath\fR must be provided as an option\&. .PP To enable TLS connections when using TLS\-PSK, you must use the \fB\-\-psk\fR and the \fB\-\-psk\-identity\fR options\&. .SH "OPTIONS" .PP The options below may be given on the command line, but may also be placed in a config file located at \fB$XDG_CONFIG_HOME/mosquitto_rr\fR or \fB$HOME/\&.config/mosquitto_rr\fR with one pair of \fB\-option \fR\fB\fIvalue\fR\fR per line\&. The values in the config file will be used as defaults and can be overridden by using the command line\&. The exceptions to this is \fB\-t\fR, which if given in the config file will not be overridden\&. Note also that currently some options cannot be negated, e\&.g\&. \fB\-S\fR\&. Config file lines that have a \fB#\fR as the first character are treated as comments and not processed any further\&. .PP \fB\-A\fR .RS 4 Bind the outgoing connection to a local ip address/hostname\&. Use this argument if you need to restrict network communication to a particular interface\&. .RE .PP \fB\-c\fR, \fB\-\-disable\-clean\-session\fR .RS 4 Disable the \*(Aqclean session\*(Aq flag\&. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive\&. When the client reconnects, it will receive all of the queued messages\&. .sp If using this option, the client id must be set manually with \fB\-\-id\fR .RE .PP \fB\-\-cafile\fR .RS 4 Define the path to a file containing PEM encoded CA certificates that are trusted\&. Used to enable SSL communication\&. .sp See also \fB\-\-capath\fR .RE .PP \fB\-\-capath\fR .RS 4 Define the path to a directory containing PEM encoded CA certificates that are trusted\&. Used to enable SSL communication\&. .sp For \fB\-\-capath\fR to work correctly, the certificate files must have "\&.crt" as the file ending and you must run "openssl rehash " each time you add/remove a certificate\&. .sp See also \fB\-\-cafile\fR .RE .PP \fB\-\-cert\fR .RS 4 Define the path to a file containing a PEM encoded certificate for this client, if required by the server\&. .sp See also \fB\-\-key\fR\&. .RE .PP \fB\-\-ciphers\fR .RS 4 An openssl compatible list of TLS ciphers to support in the client\&. See \fBciphers\fR(1) for more information\&. .RE .PP \fB\-d\fR, \fB\-\-debug\fR .RS 4 Enable debug messages\&. .RE .PP \fB\-D\fR, \fB\-\-property\fR .RS 4 Use an MQTT v5 property with this publish\&. If you use this option, the client will be set to be an MQTT v5 client\&. This option has two forms: .sp \fB\-D command identifier value\fR .sp \fB\-D command identifier name value\fR .sp \fBcommand\fR is the MQTT command/packet identifier and can be one of CONNECT, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL\&. The properties available for each command are listed in the Properties section\&. .sp \fBidentifier\fR is the name of the property to add\&. This is as described in the specification, but with \*(Aq\-\*(Aq as a word separator\&. For example: \fBpayload\-format\-indicator\fR\&. More details are in the Properties section\&. .sp \fBvalue\fR is the value of the property to add, with a data type that is property specific\&. .sp \fBname\fR is only used for the \fBuser\-property\fR property as the first of the two strings in the string pair\&. In that case, \fBvalue\fR is the second of the strings in the pair\&. .RE .PP \fB\-f\fR, \fB\-\-file\fR .RS 4 Send the contents of a file as the request message\&. .RE .PP \fB\-F\fR .RS 4 Specify output printing format\&. This option allows you to choose what information from each message is printed to the screen\&. See the Output Format section below for full details\&. .sp This option overrides the \fB\-v\fR option, but does not override the \fB\-N\fR option\&. .RE .PP \fB\-\-help\fR .RS 4 Display usage information\&. .RE .PP \fB\-h\fR, \fB\-\-host\fR .RS 4 Specify the host to connect to\&. Defaults to localhost\&. .RE .PP \fB\-i\fR, \fB\-\-id\fR .RS 4 The id to use for this client\&. If not given, a client id will be generated depending on the MQTT version being used\&. For v3\&.1\&.1/v3\&.1, the client generates a client id in the format \fBmosq\-XXXXXXXXXXXXXXXXXX\fR, where the \fBX\fR are replaced with random alphanumeric characters\&. For v5\&.0, the client sends a zero length client id, and the server will generate a client id for the client\&. .sp This option cannot be used at the same time as the \fB\-\-id\-prefix\fR argument\&. .RE .PP \fB\-I\fR, \fB\-\-id\-prefix\fR .RS 4 Provide a prefix that the client id will be built from by appending the process id of the client\&. This is useful where the broker is using the clientid_prefixes option\&. Cannot be used at the same time as the \fB\-\-id\fR argument\&. .RE .PP \fB\-\-insecure\fR .RS 4 When using certificate based encryption, this option disables verification of the server hostname in the server certificate\&. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example\&. Use this option in testing \fIonly\fR\&. If you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption\&. .RE .PP \fB\-k\fR, \fB\-\-keepalive\fR .RS 4 The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning\&. Defaults to 60 seconds\&. .RE .PP \fB\-\-key\fR .RS 4 Define the path to a file containing a PEM encoded private key for this client, if required by the server\&. .sp See also \fB\-\-cert\fR\&. .RE .PP \fB\-\-keyform\fR .RS 4 Specifies the type of private key in use when making TLS connections\&.\&. This can be "pem" or "engine"\&. This parameter is useful when a TPM module is being used and the private key has been created with it\&. Defaults to "pem", which means normal private key files are used\&. .sp See also \fB\-\-tls\-engine\fR\&. .RE .PP \fB\-L\fR, \fB\-\-url\fR .RS 4 Specify specify user, password, hostname, port and topic at once as a URL\&. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic .sp If the scheme is mqtt:// then the port defaults to 1883\&. If the scheme is mqtts:// then the port defaults to 8883\&. .RE .PP \fB\-m\fR, \fB\-\-message\fR .RS 4 Send a single request message from the command line\&. .RE .PP \fB\-N\fR .RS 4 Do not append an end of line character to the payload when printing\&. This allows streaming of payload data from multiple messages directly to another application unmodified\&. Only really makes sense when not using \fB\-v\fR\&. .RE .PP \fB\-n\fR, \fB\-\-null\-message\fR .RS 4 Send a null (zero length) request message\&. .RE .PP \fB\-p\fR, \fB\-\-port\fR .RS 4 Connect to the port specified\&. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used\&. .RE .PP \fB\-P\fR, \fB\-\-pw\fR .RS 4 Provide a password to be used for authenticating with the broker\&. Using this argument without also specifying a username is invalid when using MQTT v3\&.1 or v3\&.1\&.1\&. See also the \fB\-\-username\fR option\&. .RE .PP \fB\-\-proxy\fR .RS 4 Specify a SOCKS5 proxy to connect through\&. "None" and "username" authentication types are supported\&. The \fBsocks\-url\fR must be of the form \fBsocks5h://[username[:password]@]host[:port]\fR\&. The protocol prefix \fBsocks5h\fR means that hostnames are resolved by the proxy\&. The symbols %25, %3A and %40 are URL decoded into %, : and @ respectively, if present in the username or password\&. .sp If username is not given, then no authentication is attempted\&. If the port is not given, then the default of 1080 is used\&. .sp More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in \fBcurl\fR(1)\&. .RE .PP \fB\-\-psk\fR .RS 4 Provide the hexadecimal (no leading 0x) pre\-shared\-key matching the one used on the broker to use TLS\-PSK encryption support\&. \fB\-\-psk\-identity\fR must also be provided to enable TLS\-PSK\&. .RE .PP \fB\-\-psk\-identity\fR .RS 4 The client identity to use with TLS\-PSK support\&. This may be used instead of a username if the broker is configured to do so\&. .RE .PP \fB\-q\fR, \fB\-\-qos\fR .RS 4 Specify the quality of service desired for the incoming messages, from 0, 1 and 2\&. Defaults to 0\&. See \fBmqtt\fR(7) for more information on QoS\&. .sp The QoS is identical for all topics subscribed to in a single instance of mosquitto_rr\&. .RE .PP \fB\-\-quiet\fR .RS 4 If this argument is given, no runtime errors will be printed\&. This excludes any error messages given in case of invalid user input (e\&.g\&. using \fB\-\-port\fR without a port)\&. .RE .PP \fB\-R\fR .RS 4 If this argument is given, messages that are received that have the retain bit set will not be printed\&. Messages with retain set are "stale", in that it is not known when they were originally published\&. When subscribing to a wildcard topic there may be a large number of retained messages\&. This argument suppresses their display\&. .RE .PP \fB\-S\fR .RS 4 Use SRV lookups to determine which host to connect to\&. Performs lookups to \fB_mqtt\&._tcp\&.\fR when used in conjunction with \fB\-h\fR, otherwise uses \fB_mqtt\&._tcp\&.\fR\&. .RE .PP \fB\-s\fR, \fB\-\-stdin\-file\fR .RS 4 Send a request message read from stdin, sending the entire content as a single message\&. .RE .PP \fB\-t\fR, \fB\-\-topic\fR .RS 4 The MQTT topic to subscribe to, where responses will be waited for\&. See \fBmqtt\fR(7) for more information on MQTT topics\&. .sp This option may be repeated to subscribe to multiple topics\&. .RE .PP \fB\-\-tls\-alpn\fR .RS 4 Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e\&.g\&. MQTT and WebSockets\&. .RE .PP \fB\-\-tls\-engine\fR .RS 4 A valid openssl engine id\&. These can be listed with openssl engine command\&. .sp See also \fB\-\-keyform\fR\&. .RE .PP \fB\-\-tls\-engine\-kpass\-sha1\fR .RS 4 SHA1 of the private key password when using an TLS engine\&. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed\&. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password\&. .sp See also \fB\-\-tls\-engine\fR\&. .RE .PP \fB\-\-tls\-version\fR .RS 4 Choose which TLS protocol version to use when communicating with the broker\&. Valid options are \fBtlsv1\&.3\fR, \fBtlsv1\&.2\fR and \fBtlsv1\&.1\fR\&. The default value is \fBtlsv1\&.2\fR\&. Must match the protocol version used by the broker\&. .RE .PP \fB\-u\fR, \fB\-\-username\fR .RS 4 Provide a username to be used for authenticating with the broker\&. See also the \fB\-\-pw\fR argument\&. .RE .PP \fB\-v\fR, \fB\-\-verbose\fR .RS 4 Print received messages verbosely\&. With this argument, messages will be printed as "topic payload"\&. When this argument is not given, the messages are printed as "payload"\&. .RE .PP \fB\-V\fR, \fB\-\-protocol\-version\fR .RS 4 Specify which version of the MQTT protocol should be used when connecting to the rmeote broker\&. Can be \fB5\fR, \fB311\fR, \fB31\fR, or the more verbose \fBmqttv5\fR, \fBmqttv311\fR, or \fBmqttv31\fR\&. Defaults to \fB311\fR\&. .RE .PP \fB\-\-will\-payload\fR .RS 4 Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-qos\fR .RS 4 The QoS to use for the Will\&. Defaults to 0\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-retain\fR .RS 4 If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-topic\fR .RS 4 The topic on which to send a Will, in the event that the client disconnects unexpectedly\&. .RE .SH "OUTPUT FORMAT" .PP There are three ways of formatting the output from mosquitto_rr\&. In all cases a new\-line character is appended for each message received unless the \fB\-N\fR argument is passed to mosquitto_rr\&. .PP Payload\-only is the default output format and will print the payload exactly as it is received\&. .PP Verbose mode is activated with \fB\-v\fR and prints the message topic and the payload, separated by a space\&. .PP The final option is formatted output, which allows the user to define a custom output format\&. The behaviour is controlled with the \fB\-F format\-string\fR option\&. The format string is a free text string where interpreted sequences are replaced by different parameters\&. The available interpreted sequences are described below\&. .PP Three characters are used to start an interpreted sequence: \fB%\fR, \fB@\fR and \fB\e\fR\&. Sequences starting with \fB%\fR are either parameters related to the MQTT message being printed, or are helper sequences to avoid the need to type long date format strings for example\&. Sequences starting with \fB@\fR are passed to the \fBstrftime\fR(3) function (with the @ replaced with a % \- note that only the character immediately after the @ is passed to strftime)\&. This allows the construction of a wide variety of time based outputs\&. The output options for strftime vary from platform to platform, so please check what is available for your platform\&. mosquitto_rr does provide one extension to strftime which is \fB@N\fR, which can be used to obtain the number of nanoseconds passed in the current second\&. The resolution of this option varies depending on the platform\&. The final sequence character is \fB\e\fR, which is used to input some characters that would otherwise be difficult to enter\&. .SS "MQTT related parameters" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%%\fR a literal %\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%l\fR the length of the payload in bytes\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%m\fR the message id (only relevant for messages with QoS>0)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%p\fR the payload raw bytes (may produce non\-printable characters depending on the payload)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%q\fR the message QoS\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%r\fR the retained flag for the message\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%t\fR the message topic\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%x\fR the payload with each byte as a hexadecimal number (lower case)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%X\fR the payload with each byte as a hexadecimal number (upper case)\&. .RE .SS "Helpers" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%I\fR ISO\-8601 format date and time, e\&.g\&. 2016\-08\-10T09:47:38+0100 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%j\fR JSON output of message parameters and timestamp, with a quoted and escaped payload\&. For example {"tst":1470825369,"topic":"greeting","qos":0,"retain":0,"payload":"hello world"} .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%J\fR JSON output of message parameters and timestamp, with a non\-quoted and non\-escaped payload \- this means the payload must itself be valid JSON\&. For example: {"tst":1470825369,"topic":"foo","qos":0,"retain":0,"payload":{"temperature":27\&.0,"humidity":57}}\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%I\fR ISO\-8601 format date and time, e\&.g\&. 2016\-08\-10T09:47:38+0100 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%U\fR Unix timestamp with nanoseconds, e\&.g\&. 1470818943\&.786368637 .RE .SS "Time related parameters" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB@@\fR a literal @\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB@X\fR pass the character represented by \fBX\fR to the strftime function as \fB%X\fR\&. The options supported are platform dependent\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB@N\fR the number of nanoseconds that have passed in the current second, with varying timing resolution depending on platform\&. .RE .SS "Escape characters" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\e\e\fR a literal \e\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\e0\fR a null character\&. Can be used to separate different parameters that may contain spaces (e\&.g\&. topic, payload) so that processing with tools such as \fBxargs\fR(1) is easier\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\ea\fR alert/bell\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\ee\fR the escape sequence, which can be used with ANSI colour codes to provide coloured output for example\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\en\fR end of line\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\er\fR carriage return\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\et\fR horizontal tab\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB\ev\fR vertical tab\&. .RE .SH "WILLS" .PP mosquitto_rr can register a message with the broker that will be sent out if it disconnects unexpectedly\&. See \fBmqtt\fR(7) for more information\&. .PP The minimum requirement for this is to use \fB\-\-will\-topic\fR to specify which topic the will should be sent out on\&. This will result in a non\-retained, zero length message with QoS 0\&. .PP Use the \fB\-\-will\-retain\fR, \fB\-\-will\-payload\fR and \fB\-\-will\-qos\fR arguments to modify the other will parameters\&. .SH "PROPERTIES" .PP The \fB\-D\fR / \fB\-\-property\fR option allows adding properties to different stages of the mosquitto_rr run\&. The properties supported for each command are as follows: .SS "Connect" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBauthentication\-data\fR (binary data \- note treated as a string in mosquitto_rr) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBauthentication\-method\fR (UTF\-8 string pair) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmaximum\-packet\-size\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBreceive\-maximum\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBrequest\-problem\-information\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBrequest\-response\-information\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBsession\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBtopic\-alias\-maximum\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Publish" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcontent\-type\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcorrelation\-data\fR (binary data \- note treated as a string in mosquitto_rr) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmessage\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBpayload\-format\-indicator\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBresponse\-topic\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBtopic\-alias\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Subscribe" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Unsubscribe" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Disconnect" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBsession\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Will properties" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcontent\-type\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcorrelation\-data\fR (binary data \- note treated as a string in mosquitto_pub) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmessage\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBpayload\-format\-indicator\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBresponse\-topic\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBwill\-delay\-interval\fR (32\-bit unsigned integer) .RE .SH "FILES" .PP $XDG_CONFIG_HOME/mosquitto_rr, $HOME/\&.config/mosquitto_rr .RS 4 Configuration file for default options\&. .RE .SH "BUGS" .PP \fBmosquitto\fR bug information can be found at \m[blue]\fB\%https://github.com/eclipse/mosquitto/issues\fR\m[] .SH "SEE ALSO" \fBmqtt\fR(7), \fBmosquitto_pub\fR(1), \fBmosquitto_sub\fR(1), \fBmosquitto\fR(8), \fBlibmosquitto\fR(3), \fBmosquitto-tls\fR(7) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/mqtt.7.meta0000664000175000017500000000015713626052637015405 0ustar rogerroger.. title: MQTT man page .. slug: mqtt-7 .. category: man .. type: man .. pretty_url: False .. hide_title: True mosquitto-1.6.9/man/mosquitto.conf.50000664000175000017500000017304613626052637016471 0ustar rogerroger'\" t .\" Title: mosquitto.conf .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: File formats and conventions .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO\&.CONF" "5" "02/27/2020" "Mosquitto Project" "File formats and conventions" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto.conf \- the configuration file for mosquitto .SH "SYNOPSIS" .HP \w'\fBmosquitto\&.conf\fR\ 'u \fBmosquitto\&.conf\fR .SH "DESCRIPTION" .PP \fBmosquitto\&.conf\fR is the configuration file for mosquitto\&. This file can reside anywhere as long as mosquitto can read it\&. By default, mosquitto does not need a configuration file and will use the default values listed below\&. See \fBmosquitto\fR(8) for information on how to load a configuration file\&. .SH "FILE FORMAT" .PP All lines with a # as the very first character are treated as a comment\&. .PP Configuration lines start with a variable name\&. The variable value is separated from the name by a single space\&. .SH "AUTHENTICATION" .PP The authentication options described below allow a wide range of possibilities in conjunction with the listener options\&. This section aims to clarify the possibilities\&. .PP The simplest option is to have no authentication at all\&. This is the default if no other options are given\&. Unauthenticated encrypted support is provided by using the certificate based SSL/TLS based options cafile/capath, certfile and keyfile\&. .PP MQTT provides username/password authentication as part of the protocol\&. Use the password_file option to define the valid usernames and passwords\&. Be sure to use network encryption if you are using this option otherwise the username and password will be vulnerable to interception\&. Use the \fBper_listener_settings\fR to control whether passwords are required globally or on a per\-listener basis\&. .PP When using certificate based encryption there are three options that affect authentication\&. The first is require_certificate, which may be set to true or false\&. If false, the SSL/TLS component of the client will verify the server but there is no requirement for the client to provide anything for the server: authentication is limited to the MQTT built in username/password\&. If require_certificate is true, the client must provide a valid certificate in order to connect successfully\&. In this case, the second and third options, use_identity_as_username and use_subject_as_username, become relevant\&. If set to true, use_identity_as_username causes the Common Name (CN) from the client certificate to be used instead of the MQTT username for access control purposes\&. The password is not used because it is assumed that only authenticated clients have valid certificates\&. This means that any CA certificates you include in cafile or capath will be able to issue client certificates that are valid for connecting to your broker\&. If use_identity_as_username is false, the client must authenticate as normal (if required by password_file) through the MQTT options\&. The same principle applies for the use_subject_as_username option, but the entire certificate subject is used as the username instead of just the CN\&. .PP When using pre\-shared\-key based encryption through the psk_hint and psk_file options, the client must provide a valid identity and key in order to connect to the broker before any MQTT communication takes place\&. If use_identity_as_username is true, the PSK identity is used instead of the MQTT username for access control purposes\&. If use_identity_as_username is false, the client may still authenticate using the MQTT username/password if using the password_file option\&. .PP Both certificate and PSK based encryption are configured on a per\-listener basis\&. .PP Authentication plugins can be created to augment the password_file, acl_file and psk_file options with e\&.g\&. SQL based lookups\&. .PP It is possible to support multiple authentication schemes at once\&. A config could be created that had a listener for all of the different encryption options described above and hence a large number of ways of authenticating\&. .SH "GENERAL OPTIONS" .PP \fBacl_file\fR \fIfile path\fR .RS 4 Set the path to an access control list file\&. If defined, the contents of the file are used to control client access to topics on the broker\&. .sp If this parameter is defined then only the topics listed will have access\&. Topic access is added with lines of the format: .sp topic [read|write|readwrite] .sp The access type is controlled using "read", "write" or "readwrite"\&. This parameter is optional (unless includes a space character) \- if not given then the access is read/write\&. can contain the + or # wildcards as in subscriptions\&. .sp The first set of topics are applied to anonymous clients, assuming \fBallow_anonymous\fR is true\&. User specific topic ACLs are added after a user line as follows: .sp user .sp The username referred to here is the same as in \fBpassword_file\fR\&. It is not the clientid\&. .sp It is also possible to define ACLs based on pattern substitution within the topic\&. The form is the same as for the topic keyword, but using pattern as the keyword\&. .sp pattern [read|write|readwrite] .sp The patterns available for substition are: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} %c to match the client id of the client .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} %u to match the username of the client .RE .sp The substitution pattern must be the only text for that level of hierarchy\&. Pattern ACLs apply to all users even if the "user" keyword has previously been given\&. .sp Example: .sp pattern write sensor/%u/data .sp Allow access for bridge connection messages: .sp pattern write $SYS/broker/connection/%c/state .sp If the first character of a line of the ACL file is a # it is treated as a comment\&. .sp If \fBper_listener_settings\fR is \fItrue\fR, this option applies to the current listener being configured only\&. If \fBper_listener_settings\fR is \fIfalse\fR, this option applies to all listeners\&. .sp Reloaded on reload signal\&. The currently loaded ACLs will be freed and reloaded\&. Existing subscriptions will be affected after the reload\&. .RE .PP \fBallow_anonymous\fR [ true | false ] .RS 4 Boolean value that determines whether clients that connect without providing a username are allowed to connect\&. If set to \fIfalse\fR then another means of connection should be created to control authenticated client access\&. .sp Defaults to \fItrue\fR if no other security options are set\&. If \fBpassword_file\fR or \fBpsk_file\fR is set, or if an authentication plugin is loaded which implements username/password or TLS\-PSK checks, then \fBallow_anonymous\fR defaults to \fIfalse\fR\&. .sp If \fBper_listener_settings\fR is \fItrue\fR, this option applies to the current listener being configured only\&. If \fBper_listener_settings\fR is \fIfalse\fR, this option applies to all listeners\&. .sp Reloaded on reload signal\&. .RE .PP \fBallow_duplicate_messages\fR [ true | false ] .RS 4 If a client is subscribed to multiple subscriptions that overlap, e\&.g\&. foo/# and foo/+/baz , then MQTT expects that when the broker receives a message on a topic that matches both subscriptions, such as foo/bar/baz, then the client should only receive the message once\&. .sp Mosquitto keeps track of which clients a message has been sent to in order to meet this requirement\&. This option allows this behaviour to be disabled, which may be useful if you have a large number of clients subscribed to the same set of topics and want to minimise memory usage\&. .sp It can be safely set to \fItrue\fR if you know in advance that your clients will never have overlapping subscriptions, otherwise your clients must be able to correctly deal with duplicate messages even when then have QoS=2\&. .sp Defaults to \fItrue\fR\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBallow_zero_length_clientid\fR [ true | false ] .RS 4 MQTT 3\&.1\&.1 and MQTT 5 allow clients to connect with a zero length client id and have the broker generate a client id for them\&. Use this option to allow/disallow this behaviour\&. Defaults to true\&. .sp See also the \fBauto_id_prefix\fR option\&. .sp If \fBper_listener_settings\fR is \fItrue\fR, this option applies to the current listener being configured only\&. If \fBper_listener_settings\fR is \fIfalse\fR, this option applies to all listeners\&. .sp Reloaded on reload signal\&. .RE .PP \fBauth_opt_*\fR \fIvalue\fR .RS 4 Options to be passed to the auth plugin\&. See the specific plugin instructions\&. .sp Applies to the current authentication plugin being configured\&. .RE .PP \fBauth_plugin\fR \fIfile path\fR .RS 4 Specify an external module to use for authentication and access control\&. This allows custom username/password and access control functions to be created\&. .sp Can be specified multiple times to load multiple plugins\&. The plugins will be processed in the order that they are specified\&. .sp If \fBpassword_file\fR, or \fBacl_file\fR are used in the config file alongsize \fBauth_plugin\fR, the plugin checks will run after the built in checks\&. .sp Not currently reloaded on reload signal\&. .RE .PP \fBauth_plugin_deny_special_chars\fR [ true | false ] .RS 4 If \fItrue\fR then before an ACL check is made, the username/client id of the client needing the check is searched for the presence of either a \*(Aq+\*(Aq or \*(Aq#\*(Aq character\&. If either of these characters is found in either the username or client id, then the ACL check is denied before it is sent to the plugin\&. .sp This check prevents the case where a malicious user could circumvent an ACL check by using one of these characters as their username or client id\&. This is the same issue as was reported with mosquitto itself as CVE\-2017\-7650\&. .sp If you are entirely sure that the plugin you are using is not vulnerable to this attack (i\&.e\&. if you never use usernames or client ids in topics) then you can disable this extra check and hence have all ACL checks delivered to your plugin by setting this option to \fIfalse\fR\&. .sp Defaults to \fItrue\fR\&. .sp Applies to the current authentication plugin being configured\&. .sp Not currently reloaded on reload signal\&. .RE .PP \fBauto_id_prefix\fR \fIprefix\fR .RS 4 If \fBallow_zero_length_clientid\fR is \fItrue\fR, this option allows you to set a string that will be prefixed to the automatically generated client ids to aid visibility in logs\&. Defaults to \fBauto\-\fR\&. .sp If \fBper_listener_settings\fR is \fItrue\fR, this option applies to the current listener being configured only\&. If \fBper_listener_settings\fR is \fIfalse\fR, this option applies to all listeners\&. .sp Reloaded on reload signal\&. .RE .PP \fBautosave_interval\fR \fIseconds\fR .RS 4 The number of seconds that mosquitto will wait between each time it saves the in\-memory database to disk\&. If set to 0, the in\-memory database will only be saved when mosquitto exits or when receiving the SIGUSR1 signal\&. Note that this setting only has an effect if persistence is enabled\&. Defaults to 1800 seconds (30 minutes)\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBautosave_on_changes\fR [ true | false ] .RS 4 If \fItrue\fR, mosquitto will count the number of subscription changes, retained messages received and queued messages and if the total exceeds \fBautosave_interval\fR then the in\-memory database will be saved to disk\&. If \fIfalse\fR, mosquitto will save the in\-memory database to disk by treating \fBautosave_interval\fR as a time in seconds\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBcheck_retain_source\fR [ true | false ] .RS 4 This option affects the scenario when a client subscribes to a topic that has retained messages\&. It is possible that the client that published the retained message to the topic had access at the time they published, but that access has been subsequently removed\&. If \fBcheck_retain_source\fR is set to true, the default, the source of a retained message will be checked for access rights before it is republished\&. When set to false, no check will be made and the retained message will always be published\&. .sp This option applies globally, regardless of the \fBper_listener_settings\fR option\&. .RE .PP \fBclientid_prefixes\fR \fIprefix\fR .RS 4 If defined, only clients that have a clientid with a prefix that matches clientid_prefixes will be allowed to connect to the broker\&. For example, setting "secure\-" here would mean a client "secure\-client" could connect but another with clientid "mqtt" couldn\*(Aqt\&. By default, all client ids are valid\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. Note that currently connected clients will be unaffected by any changes\&. .RE .PP \fBconnection_messages\fR [ true | false ] .RS 4 If set to \fItrue\fR, the log will include entries when clients connect and disconnect\&. If set to \fIfalse\fR, these entries will not appear\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBinclude_dir\fR \fIdir\fR .RS 4 External configuration files may be included by using the include_dir option\&. This defines a directory that will be searched for config files\&. All files that end in \*(Aq\&.conf\*(Aq will be loaded as a configuration file\&. It is best to have this as the last option in the main file\&. This option will only be processed from the main configuration file\&. The directory specified must not contain the main configuration file\&. .sp The configuration files in \fBinclude_dir\fR are loaded in case sensitive alphabetical order, with the upper case of each letter ordered before the lower case of the same letter\&. .PP \fBExample\ \&Load Order for include_dir.\ \&\fR Given the files \fIb\&.conf\fR, \fIA\&.conf\fR, \fI01\&.conf\fR, \fIa\&.conf\fR, \fIB\&.conf\fR, and \fI00\&.conf\fR inside \fBinclude_dir\fR, the config files would be loaded in this order: .sp .if n \{\ .RS 4 .\} .nf 00\&.conf 01\&.conf A\&.conf a\&.conf B\&.conf b\&.conf .fi .if n \{\ .RE .\} If this option is used multiple times, then each \fBinclude_dir\fR option is processed completely in the order that they are written in the main configuration file\&. .PP \fBExample\ \&Load Order for Multiple include_dir.\ \&\fR Assuming a directory \fIone\&.d\fR containing files \fIB\&.conf\fR and \fIC\&.conf\fR, and a second directory \fItwo\&.d\fR containing files \fIA\&.conf\fR and \fID\&.conf\fR, and a config: .sp .if n \{\ .RS 4 .\} .nf include_dir one\&.d include_dir two\&.d .fi .if n \{\ .RE .\} .sp Then the config files would be loaded in this order: .sp .if n \{\ .RS 4 .\} .nf # files from one\&.d B\&.conf C\&.conf # files from two\&.d A\&.conf D\&.conf .fi .if n \{\ .RE .\} .RE .PP \fBlog_dest\fR \fIdestinations\fR .RS 4 Send log messages to a particular destination\&. Possible destinations are: \fBstdout\fR \fBstderr\fR \fBsyslog\fR \fBtopic\fR\&. .sp \fBstdout\fR and \fBstderr\fR log to the console on the named output\&. .sp \fBsyslog\fR uses the userspace syslog facility which usually ends up in /var/log/messages or similar and topic logs to the broker topic \*(Aq$SYS/broker/log/\*(Aq, where severity is one of D, E, W, N, I, M which are debug, error, warning, notice, information and message\&. Message type severity is used by the subscribe and unsubscribe log_type options and publishes log messages at $SYS/broker/log/M/subscribe and $SYS/broker/log/M/unsubscribe\&. .sp The \fBfile\fR destination requires an additional parameter which is the file to be logged to, e\&.g\&. "log_dest file /var/log/mosquitto\&.log"\&. The file will be closed and reopened when the broker receives a HUP signal\&. Only a single file destination may be configured\&. .sp Use "log_dest none" if you wish to disable logging\&. Defaults to stderr\&. This option may be specified multiple times\&. .sp Note that if the broker is running as a Windows service it will default to "log_dest none" and neither stdout nor stderr logging is available\&. .sp Reloaded on reload signal\&. .RE .PP \fBlog_facility\fR \fIlocal facility\fR .RS 4 If using syslog logging (not on Windows), messages will be logged to the "daemon" facility by default\&. Use the \fBlog_facility\fR option to choose which of local0 to local7 to log to instead\&. The option value should be an integer value, e\&.g\&. "log_facility 5" to use local5\&. .RE .PP \fBlog_timestamp\fR [ true | false ] .RS 4 Boolean value, if set to \fItrue\fR a timestamp value will be added to each log entry\&. The default is \fItrue\fR\&. .sp Reloaded on reload signal\&. .RE .PP \fBlog_timestamp_format\fR \fIformat\fR .RS 4 Set the format of the log timestamp\&. If left unset, this is the number of seconds since the Unix epoch\&. This option is a free text string which will be passed to the strftime function as the format specifier\&. To get an ISO 8601 datetime, for example: .sp .if n \{\ .RS 4 .\} .nf log_timestamp_format %Y\-%m\-%dT%H:%M:%S .fi .if n \{\ .RE .\} .sp Reloaded on reload signal\&. .RE .PP \fBlog_type\fR \fItypes\fR .RS 4 Choose types of messages to log\&. Possible types are: \fIdebug\fR, \fIerror\fR, \fIwarning\fR, \fInotice\fR, \fIinformation\fR, \fIsubscribe\fR, \fIunsubscribe\fR, \fIwebsockets\fR, \fInone\fR, \fIall\fR\&. .sp Defaults to \fIerror\fR, \fIwarning\fR, \fInotice \fRand \fIinformation\fR\&. This option may be specified multiple times\&. Note that the \fIdebug \fRtype (used for decoding incoming/outgoing network packets) is never logged in topics\&. .sp Reloaded on reload signal\&. .RE .PP \fBmax_inflight_bytes\fR \fIcount\fR .RS 4 Outgoing QoS 1 and 2 messages will be allowed in flight until this byte limit is reached\&. This allows control of outgoing message rate based on message size rather than message count\&. If the limit is set to 100, messages of over 100 bytes are still allowed, but only a single message can be in flight at once\&. Defaults to 0\&. (No limit)\&. .sp See also the \fBmax_inflight_messages\fR option\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBmax_inflight_messages\fR \fIcount\fR .RS 4 The maximum number of outgoing QoS 1 or 2 messages that can be in the process of being transmitted simultaneously\&. This includes messages currently going through handshakes and messages that are being retried\&. Defaults to 20\&. Set to 0 for no maximum\&. If set to 1, this will guarantee in\-order delivery of messages\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBmax_keepalive\fR \fIvalue\fR .RS 4 For MQTT v5 clients, it is possible to have the server send a "server keepalive" value that will override the keepalive value set by the client\&. This is intended to be used as a mechanism to say that the server will disconnect the client earlier than it anticipated, and that the client should use the new keepalive value\&. The max_keepalive option allows you to specify that clients may only connect with keepalive less than or equal to this value, otherwise they will be sent a server keepalive telling them to use max_keepalive\&. This only applies to MQTT v5 clients\&. The maximum value allowable, and default value, is 65535\&. Do not set below 10 seconds\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBmax_packet_size\fR \fIvalue\fR .RS 4 For MQTT v5 clients, it is possible to have the server send a "maximum packet size" value that will instruct the client it will not accept MQTT packets with size greater than \fBvalue\fR bytes\&. This applies to the full MQTT packet, not just the payload\&. Setting this option to a positive value will set the maximum packet size to that number of bytes\&. If a client sends a packet which is larger than this value, it will be disconnected\&. This applies to all clients regardless of the protocol version they are using, but v3\&.1\&.1 and earlier clients will of course not have received the maximum packet size information\&. Defaults to no limit\&. .sp This option applies to all clients, not just those using MQTT v5, but it is not possible to notify clients using MQTT v3\&.1\&.1 or MQTT v3\&.1 of the limit\&. .sp Setting below 20 bytes is forbidden because it is likely to interfere with normal client operation even with small payloads\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBmax_queued_bytes\fR \fIcount\fR .RS 4 The number of outgoing QoS 1 and 2 messages above those currently in\-flight will be queued (per client) by the broker\&. Once this limit has been reached, subsequent messages will be silently dropped\&. This is an important option if you are sending messages at a high rate and/or have clients who are slow to respond or may be offline for extended periods of time\&. Defaults to 0\&. (No maximum)\&. .sp See also the \fBmax_queued_messages\fR option\&. If both max_queued_messages and max_queued_bytes are specified, packets will be queued until the first limit is reached\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBmax_queued_messages\fR \fIcount\fR .RS 4 The maximum number of QoS 1 or 2 messages to hold in the queue (per client) above those messages that are currently in flight\&. Defaults to 100\&. Set to 0 for no maximum (not recommended)\&. See also the \fBqueue_qos0_messages\fR and \fBmax_queued_bytes\fR options\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBmemory_limit\fR \fIlimit\fR .RS 4 This option sets the maximum number of heap memory bytes that the broker will allocate, and hence sets a hard limit on memory use by the broker\&. Memory requests that exceed this value will be denied\&. The effect will vary depending on what has been denied\&. If an incoming message is being processed, then the message will be dropped and the publishing client will be disconnected\&. If an outgoing message is being sent, then the individual message will be dropped and the receiving client will be disconnected\&. Defaults to no limit\&. .sp This option is only available if memory tracking support is compiled in\&. .sp Reloaded on reload signal\&. Setting to a lower value and reloading will not result in memory being freed\&. .RE .PP \fBmessage_size_limit\fR \fIlimit\fR .RS 4 This option sets the maximum publish payload size that the broker will allow\&. Received messages that exceed this size will not be accepted by the broker\&. This means that the message will not be forwarded on to subscribing clients, but the QoS flow will be completed for QoS 1 or QoS 2 messages\&. MQTT v5 clients using QoS 1 or QoS 2 will receive a PUBACK or PUBREC with the "implementation specific error" reason code\&. .sp The default value is 0, which means that all valid MQTT messages are accepted\&. MQTT imposes a maximum payload size of 268435455 bytes\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBpassword_file\fR \fIfile path\fR .RS 4 Set the path to a password file\&. If defined, the contents of the file are used to control client access to the broker\&. The file can be created using the \fBmosquitto_passwd\fR(1) utility\&. If mosquitto is compiled without TLS support (it is recommended that TLS support is included), then the password file should be a text file with each line in the format "username:password", where the colon and password are optional but recommended\&. If \fBallow_anonymous\fR is set to \fIfalse\fR, only users defined in this file will be able to connect\&. Setting \fBallow_anonymous\fR to \fItrue\fR when \fIpassword_file\fRis defined is valid and could be used with acl_file to have e\&.g\&. read only guest/anonymous accounts and defined users that can publish\&. .sp If \fBper_listener_settings\fR is \fItrue\fR, this option applies to the current listener being configured only\&. If \fBper_listener_settings\fR is \fIfalse\fR, this option applies to all listeners\&. .sp Reloaded on reload signal\&. The currently loaded username and password data will be freed and reloaded\&. Clients that are already connected will not be affected\&. .sp See also \fBmosquitto_passwd\fR(1)\&. .RE .PP \fBper_listener_settings\fR [ true | false ] .RS 4 If \fItrue\fR, then authentication and access control settings will be controlled on a per\-listener basis\&. The following options are affected: .sp \fBpassword_file\fR, \fBacl_file\fR, \fBpsk_file\fR, \fBallow_anonymous\fR, \fBallow_zero_length_clientid\fR, \fBauth_plugin\fR, \fBauth_opt_*\fR, \fBauto_id_prefix\fR\&. .sp Note that if set to true, then a durable client (i\&.e\&. with clean session set to false) that has disconnected will use the ACL settings defined for the listener that it was most recently connected to\&. .sp The default behaviour is for this to be set to \fIfalse\fR, which maintains the settings behaviour from previous versions of mosquitto\&. .sp Reloaded on reload signal\&. .RE .PP \fBpersistence\fR [ true | false ] .RS 4 If \fItrue\fR, connection, subscription and message data will be written to the disk in mosquitto\&.db at the location dictated by persistence_location\&. When mosquitto is restarted, it will reload the information stored in mosquitto\&.db\&. The data will be written to disk when mosquitto closes and also at periodic intervals as defined by autosave_interval\&. Writing of the persistence database may also be forced by sending mosquitto the SIGUSR1 signal\&. If \fIfalse\fR, the data will be stored in memory only\&. Defaults to \fIfalse\fR\&. .sp The persistence file may change its format in a new version\&. The broker can currently read all old formats, but will only save in the latest format\&. It should always be safe to upgrade, but cautious users may wish to take a copy of the persistence file before installing a new version so that they can roll back to an earlier version if necessary\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBpersistence_file\fR \fIfile name\fR .RS 4 The filename to use for the persistent database\&. Defaults to mosquitto\&.db\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBpersistence_location\fR \fIpath\fR .RS 4 The path where the persistence database should be stored\&. Must end in a trailing slash\&. If not given, then the current directory is used\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBpersistent_client_expiration\fR \fIduration\fR .RS 4 This option allows persistent clients (those with clean session set to false) to be removed if they do not reconnect within a certain time frame\&. This is a non\-standard option\&. As far as the MQTT spec is concerned, persistent clients persist forever\&. .sp Badly designed clients may set clean session to false whilst using a randomly generated client id\&. This leads to persistent clients that will never reconnect\&. This option allows these clients to be removed\&. .sp The expiration period should be an integer followed by one of h d w m y for hour, day, week, month and year respectively\&. For example: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} persistent_client_expiration 2m .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} persistent_client_expiration 14d .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} persistent_client_expiration 1y .RE .sp As this is a non\-standard option, the default if not set is to never expire persistent clients\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBpid_file\fR \fIfile path\fR .RS 4 Write a pid file to the file specified\&. If not given (the default), no pid file will be written\&. If the pid file cannot be written, mosquitto will exit\&. This option only has an effect is mosquitto is run in daemon mode\&. .sp If mosquitto is being automatically started by an init script it will usually be required to write a pid file\&. This should then be configured as e\&.g\&. /var/run/mosquitto\&.pid .sp Not reloaded on reload signal\&. .RE .PP \fBpsk_file\fR \fIfile path\fR .RS 4 Set the path to a pre\-shared\-key file\&. This option requires a listener to be have PSK support enabled\&. If defined, the contents of the file are used to control client access to the broker\&. Each line should be in the format "identity:key", where the key is a hexadecimal string with no leading "0x"\&. A client connecting to a listener that has PSK support enabled must provide a matching identity and PSK to allow the encrypted connection to proceed\&. .sp If \fBper_listener_settings\fR is \fItrue\fR, this option applies to the current listener being configured only\&. If \fBper_listener_settings\fR is \fIfalse\fR, this option applies to all listeners\&. .sp Reloaded on reload signal\&. The currently loaded identity and key data will be freed and reloaded\&. Clients that are already connected will not be affected\&. .RE .PP \fBqueue_qos0_messages\fR [ true | false ] .RS 4 Set to \fItrue\fR to queue messages with QoS 0 when a persistent client is disconnected\&. These messages are included in the limit imposed by max_queued_messages\&. Defaults to \fIfalse\fR\&. .sp Note that the MQTT v3\&.1\&.1 spec states that only QoS 1 and 2 messages should be saved in this situation so this is a non\-standard option\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBretain_available\fR [ true | false ] .RS 4 If set to false, then retained messages are not supported\&. Clients that send a message with the retain bit will be disconnected if this option is set to false\&. Defaults to true\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBretained_persistence\fR [ true | false ] .RS 4 This is a synonym of the \fBpersistence\fR option\&. .sp Reloaded on reload signal\&. .RE .PP \fBset_tcp_nodelay\fR [ true | false ] .RS 4 If set to true, the TCP_NODELAY option will be set on client sockets to disable Nagle\*(Aqs algorithm\&. This has the effect of reducing latency of some messages at potentially increasing the number of TCP packets being sent\&. Defaults to false\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBsys_interval\fR \fIseconds\fR .RS 4 The integer number of seconds between updates of the $SYS subscription hierarchy, which provides status information about the broker\&. If unset, defaults to 10 seconds\&. .sp Set to 0 to disable publishing the $SYS hierarchy completely\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBupgrade_outgoing_qos\fR [ true | false ] .RS 4 The MQTT specification requires that the QoS of a message delivered to a subscriber is never upgraded to match the QoS of the subscription\&. Enabling this option changes this behaviour\&. If \fBupgrade_outgoing_qos\fR is set \fItrue\fR, messages sent to a subscriber will always match the QoS of its subscription\&. This is a non\-standard option not provided for by the spec\&. Defaults to \fIfalse\fR\&. .sp This option applies globally\&. .sp Reloaded on reload signal\&. .RE .PP \fBuser\fR \fIusername\fR .RS 4 When run as root, change to this user and its primary group on startup\&. If mosquitto is unable to change to this user and group, it will exit with an error\&. The user specified must have read/write access to the persistence database if it is to be written, and read access to certificate, password, and ACL files\&. If run as a non\-root user, this setting has no effect\&. Defaults to mosquitto\&. .sp This setting has no effect on Windows and so you should run mosquitto as the user you wish it to run as\&. .sp Not reloaded on reload signal\&. .RE .SH "LISTENERS" .PP The network ports that mosquitto listens on can be controlled using listeners\&. The default listener options can be overridden and further listeners can be created\&. .SS "General Options" .PP \fBbind_address\fR \fIaddress\fR .RS 4 Listen for incoming network connections on the specified IP address/hostname only\&. This is useful to restrict access to certain network interfaces\&. To restrict access to mosquitto to the local host only, use "bind_address localhost"\&. This only applies to the default listener\&. Use the \fBlistener\fR option to control other listeners\&. .sp It is recommended to use an explicit \fBlistener\fR rather than rely on the implicit default listener options like this\&. .sp Not reloaded on reload signal\&. .RE .PP \fBbind_interface\fR \fIdevice\fR .RS 4 Listen for incoming network connections only on the specified interface\&. This is similar to the \fBbind_address\fR option but is useful when an interface has multiple addresses or the address may change\&. .sp It is valid to use this option together with \fBbind_address\fR for the default listener, or the \fIbind address/host\fR part of the \fBlistener\fR definition\&. Care should be taken to ensure that the address being bound to is on the interface being bound to\&. If you set the \fBbind_interface\fR to be \fIeth0\fR, and \fBbind_address\fR to \fI127\&.0\&.0\&.1\fR, then the broker will start correctly but you will be unable to connect\&. .sp This option is currently only available on Linux, and requires elevated privileges\&. .sp Not reloaded on reload signal\&. .RE .PP \fBhttp_dir\fR \fIdirectory\fR .RS 4 When a listener is using the websockets protocol, it is possible to serve http data as well\&. Set \fBhttp_dir\fR to a directory which contains the files you wish to serve\&. If this option is not specified, then no normal http connections will be possible\&. .sp Not reloaded on reload signal\&. .RE .PP \fBlistener\fR \fIport\fR \fI[bind address/host]\fR .RS 4 Listen for incoming network connection on the specified port\&. A second optional argument allows the listener to be bound to a specific ip address/hostname\&. If this variable is used and neither the global \fBbind_address\fR nor \fBport\fR options are used then the default listener will not be started\&. .sp The \fBbind address/host\fR option allows this listener to be bound to a specific IP address by passing an IP address or hostname\&. For websockets listeners, it is only possible to pass an IP address here\&. .sp This option may be specified multiple times\&. See also the \fBmount_point\fR option\&. .sp Not reloaded on reload signal\&. .RE .PP \fBmax_connections\fR \fIcount\fR .RS 4 Limit the total number of clients connected for the current listener\&. Set to \-1 to have "unlimited" connections\&. Note that other limits may be imposed that are outside the control of mosquitto\&. See e\&.g\&. \fBlimits.conf\fR(5)\&. .sp Not reloaded on reload signal\&. .RE .PP \fBmaximum_qos\fR \fIcount\fR .RS 4 Limit the QoS value allowed for clients connecting to this listener\&. Defaults to 2, which means any QoS can be used\&. Set to 0 or 1 to limit to those QoS values\&. This makes use of an MQTT v5 feature to notify clients of the limitation\&. MQTT v3\&.1\&.1 clients will not be aware of the limitation\&. Clients publshing to this listener with a too\-high QoS will be disconnected\&. .sp Not reloaded on reload signal\&. .RE .PP \fBmax_topic_alias\fR \fInumber\fR .RS 4 This option sets the maximum number topic aliases that an MQTT v5 client is allowed to create\&. This option applies per listener\&. Defaults to 10\&. Set to 0 to disallow topic aliases\&. The maximum value possible is 65535\&. .sp Not reloaded on reload signal\&. .RE .PP \fBmount_point\fR \fItopic prefix\fR .RS 4 This option is used with the listener option to isolate groups of clients\&. When a client connects to a listener which uses this option, the string argument is attached to the start of all topics for this client\&. This prefix is removed when any messages are sent to the client\&. This means a client connected to a listener with mount point \fIexample\fR can only see messages that are published in the topic hierarchy \fIexample\fR and below\&. .sp Not reloaded on reload signal\&. .RE .PP \fBport\fR \fIport number\fR .RS 4 Set the network port for the default listener to listen on\&. Defaults to 1883\&. .sp Not reloaded on reload signal\&. .sp It is recommended to use an explicit \fBlistener\fR rather than rely on the implicit default listener options like this\&. .RE .PP \fBprotocol\fR \fIvalue\fR .RS 4 Set the protocol to accept for the current listener\&. Can be \fBmqtt\fR, the default, or \fBwebsockets\fR if available\&. .sp Websockets support is currently disabled by default at compile time\&. Certificate based TLS may be used with websockets, except that only the \fBcafile\fR, \fBcertfile\fR, \fBkeyfile\fR and \fBciphers\fR options are supported\&. .sp Not reloaded on reload signal\&. .RE .PP \fBsocket_domain\fR [ ipv4 | ipv6 ] .RS 4 By default, a listener will attempt to listen on all supported IP protocol versions\&. If you do not have an IPv4 or IPv6 interface you may wish to disable support for either of those protocol versions\&. In particular, note that due to the limitations of the websockets library, it will only ever attempt to open IPv6 sockets if IPv6 support is compiled in, and so will fail if IPv6 is not available\&. .sp Set to \fBipv4\fR to force the listener to only use IPv4, or set to \fBipv6\fR to force the listener to only use IPv6\&. If you want support for both IPv4 and IPv6, then do not use the \fBsocket_domain\fR option\&. .sp Not reloaded on reload signal\&. .RE .PP \fBuse_username_as_clientid\fR [ true | false ] .RS 4 Set \fBuse_username_as_clientid\fR to true to replace the clientid that a client connected with with its username\&. This allows authentication to be tied to the clientid, which means that it is possible to prevent one client disconnecting another by using the same clientid\&. Defaults to false\&. .sp If a client connects with no username it will be disconnected as not authorised when this option is set to true\&. Do not use in conjunction with \fBclientid_prefixes\fR\&. .sp See also \fBuse_identity_as_username\fR\&. .sp Not reloaded on reload signal\&. .RE .PP \fBwebsockets_log_level\fR \fIlevel\fR .RS 4 Change the websockets logging level\&. This is a global option, it is not possible to set per listener\&. This is an integer that is interpreted by libwebsockets as a bit mask for its lws_log_levels enum\&. See the libwebsockets documentation for more details\&. .sp To use this option, \fBlog_type websockets\fR must also be enabled\&. Defaults to 0\&. .RE .PP \fBwebsockets_headers_size\fR \fIsize\fR .RS 4 Change the websockets headers size\&. This is a global option, it is not possible to set per listener\&. This option sets the size of the buffer used in the libwebsockets library when reading HTTP headers\&. If you are passing large header data such as cookies then you may need to increase this value\&. If left unset, or set to 0, then the default of 1024 bytes will be used\&. .RE .SS "Certificate based SSL/TLS Support" .PP The following options are available for all listeners to configure certificate based SSL support\&. See also "Pre\-shared\-key based SSL/TLS support"\&. .PP \fBcafile\fR \fIfile path\fR .RS 4 At least one of \fBcafile\fR or \fBcapath\fR must be provided to enable SSL support\&. .sp \fBcafile\fR is used to define the path to a file containing the PEM encoded CA certificates that are trusted\&. .RE .PP \fBcapath\fR \fIdirectory path\fR .RS 4 At least one of \fBcafile\fR or \fBcapath\fR must be provided to enable SSL support\&. .sp \fBcapath\fR is used to define a directory that contains PEM encoded CA certificates that are trusted\&. For \fBcapath\fR to work correctly, the certificates files must have "\&.pem" as the file ending and you must run "openssl rehash " each time you add/remove a certificate\&. .RE .PP \fBcertfile\fR \fIfile path\fR .RS 4 Path to the PEM encoded server certificate\&. .RE .PP \fBciphers\fR \fIcipher:list\fR .RS 4 The list of allowed ciphers, each separated with a colon\&. Available ciphers can be obtained using the "openssl ciphers" command\&. .RE .PP \fBcrlfile\fR \fIfile path\fR .RS 4 If you have \fBrequire_certificate\fR set to \fItrue\fR, you can create a certificate revocation list file to revoke access to particular client certificates\&. If you have done this, use crlfile to point to the PEM encoded revocation file\&. .RE .PP \fBdhparamfile\fR \fIfile path\fR .RS 4 To allow the use of ephemeral DH key exchange, which provides forward security, the listener must load DH parameters\&. This can be specified with the dhparamfile option\&. The dhparamfile can be generated with the command e\&.g\&. .sp .if n \{\ .RS 4 .\} .nf openssl dhparam \-out dhparam\&.pem 2048 .fi .if n \{\ .RE .\} .RE .PP \fBkeyfile\fR \fIfile path\fR .RS 4 Path to the PEM encoded keyfile\&. .RE .PP \fBrequire_certificate\fR [ true | false ] .RS 4 By default an SSL/TLS enabled listener will operate in a similar fashion to a https enabled web server, in that the server has a certificate signed by a CA and the client will verify that it is a trusted certificate\&. The overall aim is encryption of the network traffic\&. By setting \fBrequire_certificate\fR to \fItrue\fR, a client connecting to this listener must provide a valid certificate in order for the network connection to proceed\&. This allows access to the broker to be controlled outside of the mechanisms provided by MQTT\&. .RE .PP \fBtls_engine\fR \fIengine\fR .RS 4 A valid openssl engine id\&. These can be listed with openssl engine command\&. .RE .PP \fBtls_engine_kpass_sha1\fR \fIengine_kpass_sha1\fR .RS 4 SHA1 of the private key password when using an TLS engine\&. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed\&. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password\&. .RE .PP \fBtls_keyform\fR [ pem | engine ] .RS 4 Specifies the type of private key in use when making TLS connections\&.\&. This can be "pem" or "engine"\&. This parameter is useful when a TPM module is being used and the private key has been created with it\&. Defaults to "pem", which means normal private key files are used\&. .RE .PP \fBtls_version\fR \fIversion\fR .RS 4 Configure the version of the TLS protocol to be used for this listener\&. Possible values are \fItlsv1\&.3\fR, \fItlsv1\&.2\fR and \fItlsv1\&.1\fR\&. If left unset, the default of allowing all of TLS v1\&.3, v1\&.2 and v1\&.1 is used\&. .RE .PP \fBuse_identity_as_username\fR [ true | false ] .RS 4 If \fBrequire_certificate\fR is \fItrue\fR, you may set \fBuse_identity_as_username\fR to \fItrue\fR to use the CN value from the client certificate as a username\&. If this is \fItrue\fR, the \fBpassword_file\fR option will not be used for this listener\&. .sp This takes priority over \fBuse_subject_as_username\fR if both are set to \fItrue\fR\&. .sp See also \fBuse_subject_as_username\fR .RE .PP \fBuse_subject_as_username\fR [ true | false ] .RS 4 If \fBrequire_certificate\fR is \fItrue\fR, you may set \fBuse_subject_as_username\fR to \fItrue\fR to use the complete subject value from the client certificate as a username\&. If this is \fItrue\fR, the \fBpassword_file\fR option will not be used for this listener\&. .sp The subject will be generated in a form similar to \fBCN=test client,OU=Production,O=Server,L=Nottingham,ST=Nottinghamshire,C=GB\fR\&. .sp See also \fBuse_identity_as_username\fR .RE .SS "Pre\-shared\-key based SSL/TLS Support" .PP The following options are available for all listeners to configure pre\-shared\-key based SSL support\&. See also "Certificate based SSL/TLS support"\&. .PP \fBciphers\fR \fIcipher:list\fR .RS 4 When using PSK, the encryption ciphers used will be chosen from the list of available PSK ciphers\&. If you want to control which ciphers are available, use this option\&. The list of available ciphers can be optained using the "openssl ciphers" command and should be provided in the same format as the output of that command\&. .RE .PP \fBpsk_hint\fR \fIhint\fR .RS 4 The \fBpsk_hint\fR option enables pre\-shared\-key support for this listener and also acts as an identifier for this listener\&. The hint is sent to clients and may be used locally to aid authentication\&. The hint is a free form string that doesn\*(Aqt have much meaning in itself, so feel free to be creative\&. .sp If this option is provided, see \fBpsk_file\fR to define the pre\-shared keys to be used or create a security plugin to handle them\&. .RE .PP \fBtls_version\fR \fIversion\fR .RS 4 Configure the version of the TLS protocol to be used for this listener\&. Possible values are \fItlsv1\&.3\fR, \fItlsv1\&.2\fR and \fItlsv1\&.1\fR\&. If left unset, the default of allowing all of TLS v1\&.3, v1\&.2 and v1\&.1 is used\&. .RE .PP \fBuse_identity_as_username\fR [ true | false ] .RS 4 Set \fBuse_identity_as_username\fR to have the psk identity sent by the client used as its username\&. The username will be checked as normal, so \fBpassword_file\fR or another means of authentication checking must be used\&. No password will be used\&. .RE .SH "CONFIGURING BRIDGES" .PP Multiple bridges (connections to other brokers) can be configured using the following variables\&. .PP Bridges cannot currently be reloaded on reload signal\&. .PP \fBaddress\fR \fIaddress[:port]\fR \fI[address[:port]]\fR, \fBaddresses\fR \fIaddress[:port]\fR \fI[address[:port]]\fR .RS 4 Specify the address and optionally the port of the bridge to connect to\&. This must be given for each bridge connection\&. If the port is not specified, the default of 1883 is used\&. .sp If you use an IPv6 address, then the port is not optional\&. .sp Multiple host addresses can be specified on the address config\&. See the \fBround_robin\fR option for more details on the behaviour of bridges with multiple addresses\&. .RE .PP \fBbridge_attempt_unsubscribe\fR [ true | false ] .RS 4 If a bridge has topics that have "out" direction, the default behaviour is to send an unsubscribe request to the remote broker on that topic\&. This means that changing a topic direction from "in" to "out" will not keep receiving incoming messages\&. Sending these unsubscribe requests is not always desirable, setting \fBbridge_attempt_unsubscribe\fR to \fIfalse\fR will disable sending the unsubscribe request\&. Defaults to \fItrue\fR\&. .RE .PP \fBbridge_protocol_version\fR \fIversion\fR .RS 4 Set the version of the MQTT protocol to use with for this bridge\&. Can be one of \fImqttv31\fR or \fImqttv311\fR\&. Defaults to \fImqttv31\fR\&. .RE .PP \fBcleansession\fR [ true | false ] .RS 4 Set the clean session option for this bridge\&. Setting to \fIfalse\fR (the default), means that all subscriptions on the remote broker are kept in case of the network connection dropping\&. If set to \fItrue\fR, all subscriptions and messages on the remote broker will be cleaned up if the connection drops\&. Note that setting to \fItrue\fR may cause a large amount of retained messages to be sent each time the bridge reconnects\&. .sp If you are using bridges with \fBcleansession\fR set to \fIfalse\fR (the default), then you may get unexpected behaviour from incoming topics if you change what topics you are subscribing to\&. This is because the remote broker keeps the subscription for the old topic\&. If you have this problem, connect your bridge with \fBcleansession\fR set to \fItrue\fR, then reconnect with cleansession set to \fIfalse\fR as normal\&. .RE .PP \fBconnection\fR \fIname\fR .RS 4 This variable marks the start of a new bridge connection\&. It is also used to give the bridge a name which is used as the client id on the remote broker\&. .RE .PP \fBkeepalive_interval\fR \fIseconds\fR .RS 4 Set the number of seconds after which the bridge should send a ping if no other traffic has occurred\&. Defaults to 60\&. A minimum value of 5 seconds is allowed\&. .RE .PP \fBidle_timeout\fR \fIseconds\fR .RS 4 Set the amount of time a bridge using the lazy start type must be idle before it will be stopped\&. Defaults to 60 seconds\&. .RE .PP \fBlocal_clientid\fR \fIid\fR .RS 4 Set the clientid to use on the local broker\&. If not defined, this defaults to \fBlocal\&.\fR\&. If you are bridging a broker to itself, it is important that local_clientid and remote_clientid do not match\&. .RE .PP \fBlocal_password\fR \fIpassword\fR .RS 4 Configure the password to be used when connecting this bridge to the local broker\&. This may be important when authentication and ACLs are being used\&. .RE .PP \fBlocal_username\fR \fIusername\fR .RS 4 Configure the username to be used when connecting this bridge to the local broker\&. This may be important when authentication and ACLs are being used\&. .RE .PP \fBnotifications\fR [ true | false ] .RS 4 If set to \fItrue\fR, publish notification messages to the local and remote brokers giving information about the state of the bridge connection\&. Retained messages are published to the topic $SYS/broker/connection//state unless otherwise set with \fBnotification_topic\fRs\&. If the message is 1 then the connection is active, or 0 if the connection has failed\&. Defaults to \fItrue\fR\&. .sp This uses the Last Will and Testament (LWT) feature\&. .RE .PP \fBnotifications_local_only\fR [ true | false ] .RS 4 If set to \fItrue\fR, only publish notification messages to the local broker giving information about the state of the bridge connection\&. Defaults to \fIfalse\fR\&. .RE .PP \fBnotification_topic\fR \fItopic\fR .RS 4 Choose the topic on which notifications will be published for this bridge\&. If not set the messages will be sent on the topic $SYS/broker/connection//state\&. .RE .PP \fBremote_clientid\fR \fIid\fR .RS 4 Set the client id for this bridge connection\&. If not defined, this defaults to \*(Aqname\&.hostname\*(Aq, where name is the connection name and hostname is the hostname of this computer\&. .sp This replaces the old "clientid" option to avoid confusion with local/remote sides of the bridge\&. "clientid" remains valid for the time being\&. .RE .PP \fBremote_password\fR \fIvalue\fR .RS 4 Configure a password for the bridge\&. This is used for authentication purposes when connecting to a broker that supports MQTT v3\&.1 and up and requires a username and/or password to connect\&. This option is only valid if a remote_username is also supplied\&. .sp This replaces the old "password" option to avoid confusion with local/remote sides of the bridge\&. "password" remains valid for the time being\&. .RE .PP \fBremote_username\fR \fIname\fR .RS 4 Configure a username for the bridge\&. This is used for authentication purposes when connecting to a broker that supports MQTT v3\&.1 and up and requires a username and/or password to connect\&. See also the \fBremote_password\fR option\&. .sp This replaces the old "username" option to avoid confusion with local/remote sides of the bridge\&. "username" remains valid for the time being\&. .RE .PP \fBrestart_timeout\fR \fIbase cap\fR, \fBrestart_timeout\fR \fIconstant\fR .RS 4 Set the amount of time a bridge using the automatic start type will wait until attempting to reconnect\&. .sp This option can be configured to use a constant delay time in seconds, or to use a backoff mechanism based on "Decorrelated Jitter", which adds a degree of randomness to when the restart occurs, starting at the base and increasing up to the cap\&. Set a constant timeout of 20 seconds: .sp .if n \{\ .RS 4 .\} .nf restart_timeout 20 .fi .if n \{\ .RE .\} .sp Set backoff with a base (start value) of 10 seconds and a cap (upper limit) of 60 seconds: .sp .if n \{\ .RS 4 .\} .nf restart_timeout 10 30 .fi .if n \{\ .RE .\} .sp Defaults to jitter with a base of 5 seconds and cap of 30 seconds\&. .RE .PP \fBround_robin\fR [ true | false ] .RS 4 If the bridge has more than one address given in the address/addresses configuration, the round_robin option defines the behaviour of the bridge on a failure of the bridge connection\&. If round_robin is \fIfalse\fR, the default value, then the first address is treated as the main bridge connection\&. If the connection fails, the other secondary addresses will be attempted in turn\&. Whilst connected to a secondary bridge, the bridge will periodically attempt to reconnect to the main bridge until successful\&. .sp If round_robin is \fItrue\fR, then all addresses are treated as equals\&. If a connection fails, the next address will be tried and if successful will remain connected until it fails\&. .RE .PP \fBstart_type\fR [ automatic | lazy | once ] .RS 4 Set the start type of the bridge\&. This controls how the bridge starts and can be one of three types: \fIautomatic\fR, \fIlazy \fRand \fIonce\fR\&. Note that RSMB provides a fourth start type "manual" which isn\*(Aqt currently supported by mosquitto\&. .sp \fIautomatic\fR is the default start type and means that the bridge connection will be started automatically when the broker starts and also restarted after a short delay (30 seconds) if the connection fails\&. .sp Bridges using the \fIlazy\fR start type will be started automatically when the number of queued messages exceeds the number set with the \fBthreshold\fR option\&. It will be stopped automatically after the time set by the \fBidle_timeout\fR parameter\&. Use this start type if you wish the connection to only be active when it is needed\&. .sp A bridge using the \fIonce\fR start type will be started automatically when the broker starts but will not be restarted if the connection fails\&. .RE .PP \fBthreshold\fR \fIcount\fR .RS 4 Set the number of messages that need to be queued for a bridge with lazy start type to be restarted\&. Defaults to 10 messages\&. .RE .PP \fBtopic\fR \fIpattern\fR [[[ out | in | both ] qos\-level] local\-prefix remote\-prefix] .RS 4 Define a topic pattern to be shared between the two brokers\&. Any topics matching the pattern (which may include wildcards) are shared\&. The second parameter defines the direction that the messages will be shared in, so it is possible to import messages from a remote broker using \fIin\fR, export messages to a remote broker using \fIout\fR or share messages in both directions\&. If this parameter is not defined, the default of \fIout\fR is used\&. The QoS level defines the publish/subscribe QoS level used for this topic and defaults to 0\&. .sp The \fIlocal\-prefix\fR and \fIremote\-prefix\fR options allow topics to be remapped when publishing to and receiving from remote brokers\&. This allows a topic tree from the local broker to be inserted into the topic tree of the remote broker at an appropriate place\&. .sp For incoming topics, the bridge will prepend the pattern with the remote prefix and subscribe to the resulting topic on the remote broker\&. When a matching incoming message is received, the remote prefix will be removed from the topic and then the local prefix added\&. .sp For outgoing topics, the bridge will prepend the pattern with the local prefix and subscribe to the resulting topic on the local broker\&. When an outgoing message is processed, the local prefix will be removed from the topic then the remote prefix added\&. .sp When using topic mapping, an empty prefix can be defined using the place marker \fI""\fR\&. Using the empty marker for the topic itself is also valid\&. The table below defines what combination of empty or value is valid\&. The \fBFull Local Topic\fR and \fBFull Remote Topic\fR show the resulting topics that would be used on the local and remote ends of the bridge\&. For example, for the first table row if you publish to \fBL/topic\fR on the local broker, then the remote broker will receive a message on the topic \fBR/topic\fR\&. .TS allbox tab(:); lB lB lB lB lB lB. T{ \fIPattern\fR T}:T{ \fILocal Prefix\fR T}:T{ \fIRemote Prefix\fR T}:T{ \fIValidity\fR T}:T{ \fIFull Local Topic\fR T}:T{ \fIFull Remote Topic\fR T} .T& l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l l. T{ pattern T}:T{ L/ T}:T{ R/ T}:T{ valid T}:T{ L/pattern T}:T{ R/pattern T} T{ pattern T}:T{ L/ T}:T{ "" T}:T{ valid T}:T{ L/pattern T}:T{ pattern T} T{ pattern T}:T{ "" T}:T{ R/ T}:T{ valid T}:T{ pattern T}:T{ R/pattern T} T{ pattern T}:T{ "" T}:T{ "" T}:T{ valid (no remapping) T}:T{ pattern T}:T{ pattern T} T{ "" T}:T{ local T}:T{ remote T}:T{ valid (remap single local topic to remote) T}:T{ local T}:T{ remote T} T{ "" T}:T{ local T}:T{ "" T}:T{ invalid T}:T{ \ \& T}:T{ \ \& T} T{ "" T}:T{ "" T}:T{ remote T}:T{ invalid T}:T{ \ \& T}:T{ \ \& T} T{ "" T}:T{ "" T}:T{ "" T}:T{ invalid T}:T{ \ \& T}:T{ \ \& T} .TE .sp 1 To remap an entire topic tree, use e\&.g\&.: .sp .if n \{\ .RS 4 .\} .nf topic # both 2 local/topic/ remote/topic/ .fi .if n \{\ .RE .\} .sp This option can be specified multiple times per bridge\&. .sp Care must be taken to ensure that loops are not created with this option\&. If you are experiencing high CPU load from a broker, it is possible that you have a loop where each broker is forever forwarding each other the same messages\&. .sp See also the \fBcleansession\fR option if you have messages arriving on unexpected topics when using incoming topics\&. .PP \fBExample\ \&Bridge Topic Remapping.\ \&\fR The configuration below connects a bridge to the broker at \fBtest\&.mosquitto\&.org\fR\&. It subscribes to the remote topic \fB$SYS/broker/clients/total\fR and republishes the messages received to the local topic \fBtest/mosquitto/org/clients/total\fR .sp .if n \{\ .RS 4 .\} .nf connection test\-mosquitto\-org address test\&.mosquitto\&.org cleansession true topic clients/total in 0 test/mosquitto/org $SYS/broker/ .fi .if n \{\ .RE .\} .RE .PP \fBtry_private\fR [ true | false ] .RS 4 If try_private is set to \fItrue\fR, the bridge will attempt to indicate to the remote broker that it is a bridge not an ordinary client\&. If successful, this means that loop detection will be more effective and that retained messages will be propagated correctly\&. Not all brokers support this feature so it may be necessary to set \fBtry_private\fR to \fIfalse\fR if your bridge does not connect properly\&. .sp Defaults to \fItrue\fR\&. .RE .SS "SSL/TLS Support" .PP The following options are available for all bridges to configure SSL/TLS support\&. .PP \fBbridge_alpn\fR \fIalpn\fR .RS 4 Configure the application layer protocol negotiation option for the TLS session\&. Useful for brokers that support both websockets and MQTT on the same port\&. .RE .PP \fBbridge_cafile\fR \fIfile path\fR .RS 4 One of \fBbridge_cafile\fR or \fBbridge_capath\fR must be provided to allow SSL/TLS support\&. .sp bridge_cafile is used to define the path to a file containing the PEM encoded CA certificates that have signed the certificate for the remote broker\&. .RE .PP \fBbridge_capath\fR \fIfile path\fR .RS 4 One of \fBbridge_capath\fR or \fBbridge_cafile\fR must be provided to allow SSL/TLS support\&. .sp bridge_capath is used to define the path to a directory containing the PEM encoded CA certificates that have signed the certificate for the remote broker\&. For bridge_capath to work correctly, the certificate files must have "\&.crt" as the file ending and you must run "openssl rehash " each time you add/remove a certificate\&. .RE .PP \fBbridge_certfile\fR \fIfile path\fR .RS 4 Path to the PEM encoded client certificate for this bridge, if required by the remote broker\&. .RE .PP \fBbridge_identity\fR \fIidentity\fR .RS 4 Pre\-shared\-key encryption provides an alternative to certificate based encryption\&. A bridge can be configured to use PSK with the \fBbridge_identity\fR and \fBbridge_psk\fR options\&. This is the client identity used with PSK encryption\&. Only one of certificate and PSK based encryption can be used on one bridge at once\&. .RE .PP \fBbridge_insecure\fR [ true | false ] .RS 4 When using certificate based TLS, the bridge will attempt to verify the hostname provided in the remote certificate matches the host/address being connected to\&. This may cause problems in testing scenarios, so \fBbridge_insecure\fR may be set to \fIfalse\fR to disable the hostname verification\&. .sp Setting this option to \fItrue\fR means that a malicious third party could potentially inpersonate your server, so it should always be set to \fIfalse\fR in production environments\&. .RE .PP \fBbridge_keyfile\fR \fIfile path\fR .RS 4 Path to the PEM encoded private key for this bridge, if required by the remote broker\&. .RE .PP \fBbridge_psk\fR \fIkey\fR .RS 4 Pre\-shared\-key encryption provides an alternative to certificate based encryption\&. A bridge can be configured to use PSK with the \fBbridge_identity\fR and \fBbridge_psk\fR options\&. This is the pre\-shared\-key in hexadecimal format with no "0x"\&. Only one of certificate and PSK based encryption can be used on one bridge at once\&. .RE .PP \fBbridge_require_ocsp\fR [ true | false ] .RS 4 When set to true, the bridge requires OCSP on the TLS connection it opens as client\&. .RE .PP \fBbridge_tls_version\fR \fIversion\fR .RS 4 Configure the version of the TLS protocol to be used for this bridge\&. Possible values are \fItlsv1\&.3\fR, \fItlsv1\&.2\fR and \fItlsv1\&.1\fR\&. Defaults to \fItlsv1\&.2\fR\&. The remote broker must support the same version of TLS for the connection to succeed\&. .RE .SH "FILES" .PP mosquitto\&.conf .SH "BUGS" .PP \fBmosquitto\fR bug information can be found at \m[blue]\fB\%https://github.com/eclipse/mosquitto/issues\fR\m[] .SH "SEE ALSO" \fBmosquitto\fR(8), \fBmosquitto_passwd\fR(1), \fBmosquitto-tls\fR(7), \fBmqtt\fR(7), \fBlimits.conf\fR(5) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/libmosquitto.30000664000175000017500000000262013626052637016217 0ustar rogerroger'\" t .\" Title: libmosquitto .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Library calls .\" Source: Mosquitto Project .\" Language: English .\" .TH "LIBMOSQUITTO" "3" "02/27/2020" "Mosquitto Project" "Library calls" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" libmosquitto \- MQTT version 5\&.0/3\&.1\&.1 client library .SH "DOCUMENTATION" .PP See \m[blue]\fB\%https://mosquitto.org/api/\fR\m[] .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/manpage.xsl0000664000175000017500000000145113626052637015541 0ustar rogerroger 0 0 https://mosquitto.org/man/ ansi mosquitto-1.6.9/man/mosquitto-tls.7.xml0000664000175000017500000000775413626052637017150 0ustar rogerroger mosquitto-tls 7 Mosquitto Project Conventions and miscellaneous mosquitto-tls Configure SSL/TLS support for Mosquitto Description mosquitto provides SSL support for encrypted network connections and authentication. This manual describes how to create the files needed. It is important to use different certificate subject parameters for your CA, server and clients. If the certificates appear identical, even though generated separately, the broker/client will not be able to distinguish between them and you will experience difficult to diagnose errors. Generating certificates The sections below give the openssl commands that can be used to generate certificates, but without any context. The asciicast at https://asciinema.org/a/201826 gives a full run through of how to use those commands. Certificate Authority Generate a certificate authority certificate and key. openssl req -new -x509 -days <duration> -extensions v3_ca -keyout ca.key -out ca.crt Server Generate a server key. openssl genrsa -des3 -out server.key 2048 Generate a server key without encryption. openssl genrsa -out server.key 2048 Generate a certificate signing request to send to the CA. openssl req -out server.csr -key server.key -new When prompted for the CN (Common Name), please enter either your server (or broker) hostname or domain name. Send the CSR to the CA, or sign it with your CA key: openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days <duration> Client Generate a client key. openssl genrsa -des3 -out client.key 2048 Generate a certificate signing request to send to the CA. openssl req -out client.csr -key client.key -new Send the CSR to the CA, or sign it with your CA key: openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days <duration> See Also mosquitto 8 mosquitto-conf 5 Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mosquitto-tls.7.meta0000664000175000017500000000015513626052637017262 0ustar rogerroger.. title: mosquitto-tls man page .. slug: mosquitto-tls-7 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/mosquitto_pub.10000664000175000017500000005104413626052637016400 0ustar rogerroger'\" t .\" Title: mosquitto_pub .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_PUB" "1" "02/27/2020" "Mosquitto Project" "Commands" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto_pub \- an MQTT version 5/3\&.1\&.1/3\&.1 client for publishing simple messages .SH "SYNOPSIS" .HP \w'\fBmosquitto_pub\fR\ 'u \fBmosquitto_pub\fR {[\fB\-h\fR\ \fIhostname\fR]\ [\fB\-p\fR\ \fIport\-number\fR]\ [\fB\-u\fR\ \fIusername\fR]\ [\fB\-P\fR\ \fIpassword\fR]\ \fB\-t\fR\ \fImessage\-topic\fR... | \fB\-L\fR\ \fIURL\fR} [\fB\-A\fR\ \fIbind\-address\fR] [\fB\-c\fR] [\fB\-d\fR] [\fB\-D\fR\ \fIcommand\fR\ \fIidentifier\fR\ \fIvalue\fR] [\fB\-i\fR\ \fIclient\-id\fR] [\fB\-I\fR\ \fIclient\-id\-prefix\fR] [\fB\-k\fR\ \fIkeepalive\-time\fR] [\fB\-q\fR\ \fImessage\-QoS\fR] [\fB\-\-quiet\fR] [\fB\-r\fR] [\fB\-\-repeat\fR\ \fIcount\fR] [\fB\-\-repeat\-delay\fR\ \fIseconds\fR] [\fB\-S\fR] {\fB\-f\fR\ \fIfile\fR | \fB\-l\fR | \fB\-m\fR\ \fImessage\fR | \fB\-n\fR | \fB\-s\fR} [\fB\-\-will\-topic\fR\ \fItopic\fR\ [\fB\-\-will\-payload\fR\ \fIpayload\fR]\ [\fB\-\-will\-qos\fR\ \fIqos\fR]\ [\fB\-\-will\-retain\fR]] [[{\fB\-\-cafile\fR\ \fIfile\fR\ |\ \fB\-\-capath\fR\ \fIdir\fR}\ [\fB\-\-cert\fR\ \fIfile\fR]\ [\fB\-\-key\fR\ \fIfile\fR]\ [\fB\-\-ciphers\fR\ \fIciphers\fR]\ [\fB\-\-tls\-version\fR\ \fIversion\fR]\ [\fB\-\-tls\-alpn\fR\ \fIprotocol\fR]\ [\fB\-\-tls\-engine\fR\ \fIengine\fR]\ [\fB\-\-keyform\fR\ {\fIpem\fR\ |\ \fIengine\fR}]\ [\fB\-\-tls\-engine\-kpass\-sha1\fR\ \fIkpass\-sha1\fR]\ [\fB\-\-insecure\fR]] | [\fB\-\-psk\fR\ \fIhex\-key\fR\ \fB\-\-psk\-identity\fR\ \fIidentity\fR\ [\fB\-\-ciphers\fR\ \fIciphers\fR]\ [\fB\-\-tls\-version\fR\ \fIversion\fR]]] [\fB\-\-proxy\fR\ \fIsocks\-url\fR] [\fB\-V\fR\ \fIprotocol\-version\fR] .HP \w'\fBmosquitto_pub\fR\ 'u \fBmosquitto_pub\fR [\fB\-\-help\fR] .SH "DESCRIPTION" .PP \fBmosquitto_pub\fR is a simple MQTT version 5/3\&.1\&.1 client that will publish a single message on a topic and exit\&. .SH "ENCRYPTED CONNECTIONS" .PP \fBmosquitto_pub\fR supports TLS encrypted connections\&. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup\&. .PP To enable TLS connections when using x509 certificates, one of either \fB\-\-cafile\fR or \fB\-\-capath\fR must be provided as an option\&. .PP To enable TLS connections when using TLS\-PSK, you must use the \fB\-\-psk\fR and the \fB\-\-psk\-identity\fR options\&. .SH "OPTIONS" .PP The options below may be given on the command line, but may also be placed in a config file located at \fB$XDG_CONFIG_HOME/mosquitto_pub\fR or \fB$HOME/\&.config/mosquitto_pub\fR with one pair of \fB\-option \fR\fB\fIvalue\fR\fR per line\&. The values in the config file will be used as defaults and can be overridden by using the command line\&. The exceptions to this are the message type options, of which only one can be specified\&. Note also that currently some options cannot be negated, e\&.g\&. \fB\-S\fR\&. Config file lines that have a \fB#\fR as the first character are treated as comments and not processed any further\&. .PP \fB\-A\fR .RS 4 Bind the outgoing connection to a local ip address/hostname\&. Use this argument if you need to restrict network communication to a particular interface\&. .RE .PP \fB\-c\fR, \fB\-\-disable\-clean\-session\fR .RS 4 Disable the \*(Aqclean session\*(Aq flag\&. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive\&. When the client reconnects, it will receive all of the queued messages\&. .sp If using this option, the client id must be set manually with \fB\-\-id\fR .RE .PP \fB\-\-cafile\fR .RS 4 Define the path to a file containing PEM encoded CA certificates that are trusted\&. Used to enable SSL communication\&. .sp See also \fB\-\-capath\fR .RE .PP \fB\-\-capath\fR .RS 4 Define the path to a directory containing PEM encoded CA certificates that are trusted\&. Used to enable SSL communication\&. .sp For \fB\-\-capath\fR to work correctly, the certificate files must have "\&.crt" as the file ending and you must run "openssl rehash " each time you add/remove a certificate\&. .sp See also \fB\-\-cafile\fR .RE .PP \fB\-\-cert\fR .RS 4 Define the path to a file containing a PEM encoded certificate for this client, if required by the server\&. .sp See also \fB\-\-key\fR\&. .RE .PP \fB\-\-ciphers\fR .RS 4 An openssl compatible list of TLS ciphers to support in the client\&. See \fBciphers\fR(1) for more information\&. .RE .PP \fB\-d\fR, \fB\-\-debug\fR .RS 4 Enable debug messages\&. .RE .PP \fB\-D\fR, \fB\-\-property\fR .RS 4 Use an MQTT v5 property with this publish\&. If you use this option, the client will be set to be an MQTT v5 client\&. This option has two forms: .sp \fB\-D command identifier value\fR .sp \fB\-D command identifier name value\fR .sp \fBcommand\fR is the MQTT command/packet identifier and can be one of CONNECT, PUBLISH, PUBREL, DISCONNECT, AUTH, or WILL\&. The properties available for each command are listed in the Properties section\&. .sp \fBidentifier\fR is the name of the property to add\&. This is as described in the specification, but with \*(Aq\-\*(Aq as a word separator\&. For example: \fBpayload\-format\-indicator\fR\&. More details are in the Properties section\&. .sp \fBvalue\fR is the value of the property to add, with a data type that is property specific\&. .sp \fBname\fR is only used for the \fBuser\-property\fR property as the first of the two strings in the string pair\&. In that case, \fBvalue\fR is the second of the strings in the pair\&. .RE .PP \fB\-f\fR, \fB\-\-file\fR .RS 4 Send the contents of a file as the message\&. .RE .PP \fB\-\-help\fR .RS 4 Display usage information\&. .RE .PP \fB\-h\fR, \fB\-\-host\fR .RS 4 Specify the host to connect to\&. Defaults to localhost\&. .RE .PP \fB\-i\fR, \fB\-\-id\fR .RS 4 The id to use for this client\&. If not given, a client id will be generated depending on the MQTT version being used\&. For v3\&.1\&.1/v3\&.1, the client generates a client id in the format \fBmosq\-XXXXXXXXXXXXXXXXXX\fR, where the \fBX\fR are replaced with random alphanumeric characters\&. For v5\&.0, the client sends a zero length client id, and the server will generate a client id for the client\&. .sp This option cannot be used at the same time as the \fB\-\-id\-prefix\fR argument\&. .RE .PP \fB\-I\fR, \fB\-\-id\-prefix\fR .RS 4 Provide a prefix that the client id will be built from by appending the process id of the client\&. This is useful where the broker is using the clientid_prefixes option\&. Cannot be used at the same time as the \fB\-\-id\fR argument\&. .RE .PP \fB\-\-insecure\fR .RS 4 When using certificate based encryption, this option disables verification of the server hostname in the server certificate\&. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example\&. Use this option in testing \fIonly\fR\&. If you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption\&. .RE .PP \fB\-k\fR, \fB\-\-keepalive\fR .RS 4 The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning\&. Defaults to 60 seconds\&. .RE .PP \fB\-\-key\fR .RS 4 Define the path to a file containing a PEM encoded private key for this client, if required by the server\&. .sp See also \fB\-\-cert\fR\&. .RE .PP \fB\-\-keyform\fR .RS 4 Specifies the type of private key in use when making TLS connections\&.\&. This can be "pem" or "engine"\&. This parameter is useful when a TPM module is being used and the private key has been created with it\&. Defaults to "pem", which means normal private key files are used\&. .sp See also \fB\-\-tls\-engine\fR\&. .RE .PP \fB\-L\fR, \fB\-\-url\fR .RS 4 Specify specify user, password, hostname, port and topic at once as a URL\&. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic .sp If the scheme is mqtt:// then the port defaults to 1883\&. If the scheme is mqtts:// then the port defaults to 8883\&. .RE .PP \fB\-l\fR, \fB\-\-stdin\-line\fR .RS 4 Send messages read from stdin, splitting separate lines into separate messages\&. .RE .PP \fB\-m\fR, \fB\-\-message\fR .RS 4 Send a single message from the command line\&. .RE .PP \fB\-n\fR, \fB\-\-null\-message\fR .RS 4 Send a null (zero length) message\&. .RE .PP \fB\-p\fR, \fB\-\-port\fR .RS 4 Connect to the port specified\&. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used\&. .RE .PP \fB\-P\fR, \fB\-\-pw\fR .RS 4 Provide a password to be used for authenticating with the broker\&. Using this argument without also specifying a username is invalid when using MQTT v3\&.1 or v3\&.1\&.1\&. See also the \fB\-\-username\fR option\&. .RE .PP \fB\-\-proxy\fR .RS 4 Specify a SOCKS5 proxy to connect through\&. "None" and "username" authentication types are supported\&. The \fBsocks\-url\fR must be of the form \fBsocks5h://[username[:password]@]host[:port]\fR\&. The protocol prefix \fBsocks5h\fR means that hostnames are resolved by the proxy\&. The symbols %25, %3A and %40 are URL decoded into %, : and @ respectively, if present in the username or password\&. .sp If username is not given, then no authentication is attempted\&. If the port is not given, then the default of 1080 is used\&. .sp More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in \fBcurl\fR(1)\&. .RE .PP \fB\-\-psk\fR .RS 4 Provide the hexadecimal (no leading 0x) pre\-shared\-key matching the one used on the broker to use TLS\-PSK encryption support\&. \fB\-\-psk\-identity\fR must also be provided to enable TLS\-PSK\&. .RE .PP \fB\-\-psk\-identity\fR .RS 4 The client identity to use with TLS\-PSK support\&. This may be used instead of a username if the broker is configured to do so\&. .RE .PP \fB\-q\fR, \fB\-\-qos\fR .RS 4 Specify the quality of service to use for the message, from 0, 1 and 2\&. Defaults to 0\&. .RE .PP \fB\-\-quiet\fR .RS 4 If this argument is given, no runtime errors will be printed\&. This excludes any error messages given in case of invalid user input (e\&.g\&. using \fB\-\-port\fR without a port)\&. .RE .PP \fB\-r\fR, \fB\-\-retain\fR .RS 4 If retain is given, the message will be retained as a "last known good" value on the broker\&. See \fBmqtt\fR(7) for more information\&. .RE .PP \fB\-\-repeat\fR .RS 4 If the publish mode is\fB\-m\fR, \fB\-f\fR, or \fB\-s\fR (i\&.e\&. the modes where only a single message is sent), then \fB\-\-repeat\fR can be used to specify that the message will be published multiple times\&. .sp See also \fB\-\-repeat\-delay\fR\&. .RE .PP \fB\-\-repeat\-delay\fR .RS 4 If using \fB\-\-repeat\fR, then the default behaviour is to publish repeated messages as soon as the previous message is delivered\&. Use \fB\-\-repeat\-delay\fR to specify the number of seconds to wait after the previous message was delivered before publishing the next\&. Does not need to be an integer number of seconds\&. .sp Note that there is no guarantee as to the actual interval between messages, this option simply defines the minimum time from delivery of one message to the start of the publish of the next\&. .RE .PP \fB\-s\fR, \fB\-\-stdin\-file\fR .RS 4 Send a message read from stdin, sending the entire content as a single message\&. .RE .PP \fB\-S\fR .RS 4 Use SRV lookups to determine which host to connect to\&. Performs lookups to \fB_mqtt\&._tcp\&.\fR when used in conjunction with \fB\-h\fR, otherwise uses \fB_mqtt\&._tcp\&.\fR\&. .RE .PP \fB\-t\fR, \fB\-\-topic\fR .RS 4 The MQTT topic on which to publish the message\&. See \fBmqtt\fR(7) for more information on MQTT topics\&. .RE .PP \fB\-\-tls\-alpn\fR .RS 4 Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e\&.g\&. MQTT and WebSockets\&. .RE .PP \fB\-\-tls\-engine\fR .RS 4 A valid openssl engine id\&. These can be listed with openssl engine command\&. .sp See also \fB\-\-keyform\fR\&. .RE .PP \fB\-\-tls\-engine\-kpass\-sha1\fR .RS 4 SHA1 of the private key password when using an TLS engine\&. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed\&. This option allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password\&. .sp See also \fB\-\-tls\-engine\fR\&. .RE .PP \fB\-\-tls\-version\fR .RS 4 Choose which TLS protocol version to use when communicating with the broker\&. Valid options are \fBtlsv1\&.3\fR, \fBtlsv1\&.2\fR and \fBtlsv1\&.1\fR\&. The default value is \fBtlsv1\&.2\fR\&. Must match the protocol version used by the broker\&. .RE .PP \fB\-u\fR, \fB\-\-username\fR .RS 4 Provide a username to be used for authenticating with the broker\&. See also the \fB\-\-pw\fR argument\&. .RE .PP \fB\-V\fR, \fB\-\-protocol\-version\fR .RS 4 Specify which version of the MQTT protocol should be used when connecting to the rmeote broker\&. Can be \fB5\fR, \fB311\fR, \fB31\fR, or the more verbose \fBmqttv5\fR, \fBmqttv311\fR, or \fBmqttv31\fR\&. Defaults to \fB311\fR\&. .RE .PP \fB\-\-will\-payload\fR .RS 4 Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-qos\fR .RS 4 The QoS to use for the Will\&. Defaults to 0\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-retain\fR .RS 4 If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message\&. This must be used in conjunction with \fB\-\-will\-topic\fR\&. .RE .PP \fB\-\-will\-topic\fR .RS 4 The topic on which to send a Will, in the event that the client disconnects unexpectedly\&. .RE .SH "WILLS" .PP mosquitto_sub can register a message with the broker that will be sent out if it disconnects unexpectedly\&. See \fBmqtt\fR(7) for more information\&. .PP The minimum requirement for this is to use \fB\-\-will\-topic\fR to specify which topic the will should be sent out on\&. This will result in a non\-retained, zero length message with QoS 0\&. .PP Use the \fB\-\-will\-retain\fR, \fB\-\-will\-payload\fR and \fB\-\-will\-qos\fR arguments to modify the other will parameters\&. .SH "PROPERTIES" .PP The \fB\-D\fR / \fB\-\-property\fR option allows adding properties to different stages of the mosquitto_pub run\&. The properties supported for each command are as follows: .SS "Connect" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBauthentication\-data\fR (binary data \- note treated as a string in mosquitto_pub) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBauthentication\-method\fR (UTF\-8 string pair) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmaximum\-packet\-size\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBreceive\-maximum\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBrequest\-problem\-information\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBrequest\-response\-information\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBsession\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBtopic\-alias\-maximum\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Publish" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcontent\-type\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcorrelation\-data\fR (binary data \- note treated as a string in mosquitto_pub) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmessage\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBpayload\-format\-indicator\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBresponse\-topic\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBtopic\-alias\fR (16\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Disconnect" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBsession\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .SS "Will properties" .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcontent\-type\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBcorrelation\-data\fR (binary data \- note treated as a string in mosquitto_pub) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBmessage\-expiry\-interval\fR (32\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBpayload\-format\-indicator\fR (8\-bit unsigned integer) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBresponse\-topic\fR (UTF\-8 string) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBuser\-property\fR (UTF\-8 string pair) .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fBwill\-delay\-interval\fR (32\-bit unsigned integer) .RE .SH "EXAMPLES" .PP Publish temperature information to localhost with QoS 1: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_pub \-t sensors/temperature \-m 32 \-q 1 .RE .PP Publish timestamp and temperature information to a remote host on a non\-standard port and QoS 0: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_pub \-h 192\&.168\&.1\&.1 \-p 1885 \-t sensors/temperature \-m "1266193804 32" .RE .PP Publish light switch status\&. Message is set to retained because there may be a long period of time between light switch events: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_pub \-r \-t switches/kitchen_lights/status \-m "on" .RE .PP Send the contents of a file in two ways: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_pub \-t my/topic \-f \&./data .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_pub \-t my/topic \-s < \&./data .RE .PP Send parsed electricity usage data from a Current Cost meter, reading from stdin with one line/reading as one message: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} read_cc128\&.pl | mosquitto_pub \-t sensors/cc128 \-l .RE .SH "FILES" .PP $XDG_CONFIG_HOME/mosquitto_pub, $HOME/\&.config/mosquitto_pub .RS 4 Configuration file for default options\&. .RE .SH "BUGS" .PP \fBmosquitto\fR bug information can be found at \m[blue]\fB\%https://github.com/eclipse/mosquitto/issues\fR\m[] .SH "SEE ALSO" \fBmqtt\fR(7), \fBmosquitto_rr\fR(1), \fBmosquitto_sub\fR(1), \fBmosquitto\fR(8), \fBlibmosquitto\fR(3), \fBmosquitto-tls\fR(7) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/libmosquitto.3.xml0000664000175000017500000000136213626052637017020 0ustar rogerroger libmosquitto 3 Mosquitto Project Library calls libmosquitto MQTT version 5.0/3.1.1 client library Documentation See Author Roger Light roger@atchoo.org mosquitto-1.6.9/man/mosquitto_passwd.10000664000175000017500000000662713626052637017122 0ustar rogerroger'\" t .\" Title: mosquitto_passwd .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets v1.79.1 .\" Date: 02/27/2020 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_PASSWD" "1" "02/27/2020" "Mosquitto Project" "Commands" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" mosquitto_passwd \- manage password files for mosquitto .SH "SYNOPSIS" .HP \w'\fBmosquitto_passwd\fR\ 'u \fBmosquitto_passwd\fR [\fB\-c\fR | \fB\-D\fR] \fIpasswordfile\fR \fIusername\fR .HP \w'\fBmosquitto_passwd\fR\ 'u \fBmosquitto_passwd\fR \fB\-b\fR \fIpasswordfile\fR \fIusername\fR \fIpassword\fR .HP \w'\fBmosquitto_passwd\fR\ 'u \fBmosquitto_passwd\fR \fB\-U\fR \fIpasswordfile\fR .SH "DESCRIPTION" .PP \fBmosquitto_passwd\fR is a tool for managing password files for the mosquitto MQTT broker\&. .PP Usernames must not contain ":"\&. Passwords are stored in a similar format to \fBcrypt\fR(3)\&. .SH "OPTIONS" .PP \fB\-b\fR .RS 4 Run in batch mode\&. This allows the password to be provided at the command line which can be convenient but should be used with care because the password will be visible on the command line and in command history\&. .RE .PP \fB\-c\fR .RS 4 Create a new password file\&. If the file already exists, it will be overwritten\&. .RE .PP \fB\-D\fR .RS 4 Delete the specified user from the password file\&. .RE .PP \fB\-U\fR .RS 4 This option can be used to upgrade/convert a password file with plain text passwords into one using hashed passwords\&. It will modify the specified file\&. It does not detect whether passwords are already hashed, so using it on a password file that already contains hashed passwords will generate new hashes based on the old hashes and render the password file unusable\&. .RE .PP \fBpasswordfile\fR .RS 4 The password file to modify\&. .RE .PP \fBusername\fR .RS 4 The username to add/update/delete\&. .RE .PP \fBpassword\fR .RS 4 The password to use when in batch mode\&. .RE .SH "EXAMPLES" .PP Add a user to a new password file: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_passwd \-c /etc/mosquitto/passwd ral .RE .PP Delete a user from a password file .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_passwd \-D /etc/mosquitto/passwd ral .RE .SH "BUGS" .PP \fBmosquitto\fR bug information can be found at \m[blue]\fB\%https://github.com/eclipse/mosquitto/issues\fR\m[] .SH "SEE ALSO" \fBmosquitto\fR(8), \fBmosquitto.conf\fR(5), \fBmqtt\fR(7) .SH "AUTHOR" .PP Roger Light mosquitto-1.6.9/man/mosquitto_passwd.1.meta0000664000175000017500000000016313626052637020034 0ustar rogerroger.. title: mosquitto_passwd man page .. slug: mosquitto_passwd-1 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/man/Makefile0000664000175000017500000000576113626052637015051 0ustar rogerrogerinclude ../config.mk .PHONY : all clean install uninstall dist MANPAGES = \ libmosquitto.3 \ mosquitto-tls.7 \ mosquitto.8 \ mosquitto.conf.5 \ mosquitto_passwd.1 \ mosquitto_pub.1 \ mosquitto_rr.1 \ mosquitto_sub.1 \ mqtt.7 all : ${MANPAGES} clean : reallyclean : clean -rm -f *.orig -rm -f ${MANPAGES} dist : ${MANPAGES} install : $(INSTALL) -d "${DESTDIR}$(mandir)/man8" $(INSTALL) -m 644 mosquitto.8 "${DESTDIR}${mandir}/man8/mosquitto.8" $(INSTALL) -d "${DESTDIR}$(mandir)/man5" $(INSTALL) -m 644 mosquitto.conf.5 "${DESTDIR}${mandir}/man5/mosquitto.conf.5" $(INSTALL) -d "${DESTDIR}$(mandir)/man1" $(INSTALL) -m 644 mosquitto_passwd.1 "${DESTDIR}${mandir}/man1/mosquitto_passwd.1" $(INSTALL) -m 644 mosquitto_pub.1 "${DESTDIR}${mandir}/man1/mosquitto_pub.1" $(INSTALL) -m 644 mosquitto_sub.1 "${DESTDIR}${mandir}/man1/mosquitto_sub.1" $(INSTALL) -m 644 mosquitto_rr.1 "${DESTDIR}${mandir}/man1/mosquitto_rr.1" $(INSTALL) -d "${DESTDIR}$(mandir)/man7" $(INSTALL) -m 644 mqtt.7 "${DESTDIR}${mandir}/man7/mqtt.7" $(INSTALL) -m 644 mosquitto-tls.7 "${DESTDIR}${mandir}/man7/mosquitto-tls.7" $(INSTALL) -d "${DESTDIR}$(mandir)/man3" $(INSTALL) -m 644 libmosquitto.3 "${DESTDIR}${mandir}/man3/libmosquitto.3" uninstall : -rm -f "${DESTDIR}${mandir}/man8/mosquitto.8" -rm -f "${DESTDIR}${mandir}/man5/mosquitto.conf.5" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_passwd.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_pub.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_sub.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_rr.1" -rm -f "${DESTDIR}${mandir}/man7/mqtt.7" -rm -f "${DESTDIR}${mandir}/man7/mosquitto-tls.7" -rm -f "${DESTDIR}${mandir}/man3/libmosquitto.3" mosquitto.8 : mosquitto.8.xml $(XSLTPROC) $^ mosquitto.conf.5 : mosquitto.conf.5.xml manpage.xsl $(XSLTPROC) $< mosquitto_passwd.1 : mosquitto_passwd.1.xml $(XSLTPROC) $^ mosquitto_pub.1 : mosquitto_pub.1.xml $(XSLTPROC) $^ mosquitto_sub.1 : mosquitto_sub.1.xml $(XSLTPROC) $^ mosquitto_rr.1 : mosquitto_rr.1.xml $(XSLTPROC) $^ mqtt.7 : mqtt.7.xml $(XSLTPROC) $^ mosquitto-tls.7 : mosquitto-tls.7.xml $(XSLTPROC) $^ libmosquitto.3 : libmosquitto.3.xml $(XSLTPROC) $^ html : *.xml set -e; for m in *.xml; \ do \ hfile=$$(echo $${m} | sed -e 's#\(.*\)\.xml#\1#' | sed -e 's/\./-/g'); \ $(XSLTPROC) html.xsl $${m} > $${hfile}.html; \ done potgen : xml2po -o po/mosquitto/mosquitto.8.pot mosquitto.8.xml xml2po -o po/mosquitto.conf/mosquitto.conf.5.pot mosquitto.conf.5.xml xml2po -o po/mosquitto_passwd/mosquitto_passwd.1.pot mosquitto_passwd.1.xml xml2po -o po/mosquitto_pub/mosquitto_pub.1.pot mosquitto_pub.1.xml xml2po -o po/mosquitto_sub/mosquitto_sub.1.pot mosquitto_sub.1.xml xml2po -o po/mosquitto_sub/mosquitto_rr.1.pot mosquitto_rr.1.xml xml2po -o po/mqtt/mqtt.7.pot mqtt.7.xml xml2po -o po/mosquitto-tls/mosquitto-tls.7.pot mosquitto-tls.7.xml xml2po -o po/libmosquitto/libmosquitto.3.pot libmosquitto.3.xml # To merge new translations do: # /usr/bin/xml2po -p de.po chapter1.xml > chapter1.de.xml mosquitto-1.6.9/man/mosquitto.8.meta0000664000175000017500000000014513626052637016462 0ustar rogerroger.. title: Mosquitto man page .. slug: mosquitto-8 .. category: man .. type: man .. pretty_url: False mosquitto-1.6.9/LICENSE.txt0000664000175000017500000000023313626052637014446 0ustar rogerrogerThis project is dual licensed under the Eclipse Public License 1.0 and the Eclipse Distribution License 1.0 as described in the epl-v10 and edl-v10 files. mosquitto-1.6.9/installer/0000775000175000017500000000000013626052637014622 5ustar rogerrogermosquitto-1.6.9/installer/mosquitto.nsi0000664000175000017500000001105013626052637017376 0ustar rogerroger; NSIS installer script for mosquitto !include "MUI2.nsh" !include "nsDialogs.nsh" !include "LogicLib.nsh" ; For environment variable code !include "WinMessages.nsh" !define env_hklm 'HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"' Name "Eclipse Mosquitto" !define VERSION 1.6.9 OutFile "mosquitto-${VERSION}-install-windows-x86.exe" InstallDir "$PROGRAMFILES\mosquitto" ;-------------------------------- ; Installer pages !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_COMPONENTS !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH ;-------------------------------- ; Uninstaller pages !insertmacro MUI_UNPAGE_WELCOME !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_UNPAGE_FINISH ;-------------------------------- ; Languages !insertmacro MUI_LANGUAGE "English" ;-------------------------------- ; Installer sections Section "Files" SecInstall SectionIn RO SetOutPath "$INSTDIR" File "..\build\src\Release\mosquitto.exe" File "..\build\src\Release\mosquitto_passwd.exe" File "..\build\client\Release\mosquitto_pub.exe" File "..\build\client\Release\mosquitto_sub.exe" File "..\build\client\Release\mosquitto_rr.exe" File "..\build\lib\Release\mosquitto.dll" File "..\build\lib\cpp\Release\mosquittopp.dll" File "..\aclfile.example" File "..\ChangeLog.txt" File "..\mosquitto.conf" File "..\pwfile.example" File "..\readme.md" File "..\readme-windows.txt" ;File "C:\pthreads\Pre-built.2\dll\x86\pthreadVC2.dll" File "C:\OpenSSL-Win32\bin\libssl-1_1.dll" File "C:\OpenSSL-Win32\bin\libcrypto-1_1.dll" File "..\edl-v10" File "..\epl-v10" SetOutPath "$INSTDIR\devel" File "..\lib\mosquitto.h" File "..\build\lib\Release\mosquitto.lib" File "..\lib\cpp\mosquittopp.h" File "..\build\lib\cpp\Release\mosquittopp.lib" File "..\src\mosquitto_plugin.h" WriteUninstaller "$INSTDIR\Uninstall.exe" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "DisplayName" "Eclipse Mosquitto MQTT broker" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "UninstallString" "$\"$INSTDIR\Uninstall.exe$\"" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "QuietUninstallString" "$\"$INSTDIR\Uninstall.exe$\" /S" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "HelpLink" "https://mosquitto.org/" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "URLInfoAbout" "https://mosquitto.org/" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "DisplayVersion" "${VERSION}" WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "NoModify" "1" WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "NoRepair" "1" WriteRegExpandStr ${env_hklm} MOSQUITTO_DIR $INSTDIR SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000 SectionEnd Section "Service" SecService ExecWait '"$INSTDIR\mosquitto.exe" install' SectionEnd Section "Uninstall" ExecWait '"$INSTDIR\mosquitto.exe" uninstall' Delete "$INSTDIR\mosquitto.exe" Delete "$INSTDIR\mosquitto_passwd.exe" Delete "$INSTDIR\mosquitto_pub.exe" Delete "$INSTDIR\mosquitto_sub.exe" Delete "$INSTDIR\mosquitto_rr.exe" Delete "$INSTDIR\mosquitto.dll" Delete "$INSTDIR\mosquittopp.dll" Delete "$INSTDIR\aclfile.example" Delete "$INSTDIR\ChangeLog.txt" Delete "$INSTDIR\mosquitto.conf" Delete "$INSTDIR\pwfile.example" Delete "$INSTDIR\readme.txt" Delete "$INSTDIR\readme-windows.txt" ;Delete "$INSTDIR\pthreadVC2.dll" Delete "$INSTDIR\libssl-1_1.dll" Delete "$INSTDIR\libcrypto-1_1.dll" Delete "$INSTDIR\edl-v10" Delete "$INSTDIR\epl-v10" Delete "$INSTDIR\devel\mosquitto.h" Delete "$INSTDIR\devel\mosquitto.lib" Delete "$INSTDIR\devel\mosquittopp.h" Delete "$INSTDIR\devel\mosquittopp.lib" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\Uninstall.exe" RMDir "$INSTDIR" DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" DeleteRegValue ${env_hklm} MOSQUITTO_DIR SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000 SectionEnd LangString DESC_SecInstall ${LANG_ENGLISH} "The main installation." LangString DESC_SecService ${LANG_ENGLISH} "Install mosquitto as a Windows service?" !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN !insertmacro MUI_DESCRIPTION_TEXT ${SecInstall} $(DESC_SecInstall) !insertmacro MUI_DESCRIPTION_TEXT ${SecService} $(DESC_SecService) !insertmacro MUI_FUNCTION_DESCRIPTION_END mosquitto-1.6.9/installer/mosquitto64.nsi0000664000175000017500000001117213626052637017555 0ustar rogerroger; NSIS installer script for mosquitto !include "MUI2.nsh" !include "nsDialogs.nsh" !include "LogicLib.nsh" ; For environment variable code !include "WinMessages.nsh" !define env_hklm 'HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"' Name "Eclipse Mosquitto" !define VERSION 1.6.9 OutFile "mosquitto-${VERSION}-install-windows-x64.exe" !include "x64.nsh" InstallDir "$PROGRAMFILES64\mosquitto" ;-------------------------------- ; Installer pages !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_COMPONENTS !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH ;-------------------------------- ; Uninstaller pages !insertmacro MUI_UNPAGE_WELCOME !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_UNPAGE_FINISH ;-------------------------------- ; Languages !insertmacro MUI_LANGUAGE "English" ;-------------------------------- ; Installer sections Section "Files" SecInstall SectionIn RO SetOutPath "$INSTDIR" File "..\build64\src\Release\mosquitto.exe" File "..\build64\src\Release\mosquitto_passwd.exe" File "..\build64\client\Release\mosquitto_pub.exe" File "..\build64\client\Release\mosquitto_sub.exe" File "..\build64\client\Release\mosquitto_rr.exe" File "..\build64\lib\Release\mosquitto.dll" File "..\build64\lib\cpp\Release\mosquittopp.dll" File "..\aclfile.example" File "..\ChangeLog.txt" File "..\mosquitto.conf" File "..\pwfile.example" File "..\readme.md" File "..\readme-windows.txt" ;File "C:\pthreads\Pre-built.2\dll\x64\pthreadVC2.dll" File "C:\OpenSSL-Win64\bin\libssl-1_1-x64.dll" File "C:\OpenSSL-Win64\bin\libcrypto-1_1-x64.dll" File "..\edl-v10" File "..\epl-v10" SetOutPath "$INSTDIR\devel" File "..\lib\mosquitto.h" File "..\build64\lib\Release\mosquitto.lib" File "..\lib\cpp\mosquittopp.h" File "..\build64\lib\cpp\Release\mosquittopp.lib" File "..\src\mosquitto_plugin.h" WriteUninstaller "$INSTDIR\Uninstall.exe" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "DisplayName" "Eclipse Mosquitto MQTT broker (64 bit)" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "UninstallString" "$\"$INSTDIR\Uninstall.exe$\"" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "QuietUninstallString" "$\"$INSTDIR\Uninstall.exe$\" /S" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "HelpLink" "https://mosquitto.org/" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "URLInfoAbout" "https://mosquitto.org/" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "DisplayVersion" "${VERSION}" WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "NoModify" "1" WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" "NoRepair" "1" WriteRegExpandStr ${env_hklm} MOSQUITTO_DIR $INSTDIR SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000 SectionEnd Section "Service" SecService ExecWait '"$INSTDIR\mosquitto.exe" install' SectionEnd Section "Uninstall" ExecWait '"$INSTDIR\mosquitto.exe" uninstall' Delete "$INSTDIR\mosquitto.exe" Delete "$INSTDIR\mosquitto_passwd.exe" Delete "$INSTDIR\mosquitto_pub.exe" Delete "$INSTDIR\mosquitto_sub.exe" Delete "$INSTDIR\mosquitto_rr.exe" Delete "$INSTDIR\mosquitto.dll" Delete "$INSTDIR\mosquittopp.dll" Delete "$INSTDIR\aclfile.example" Delete "$INSTDIR\ChangeLog.txt" Delete "$INSTDIR\mosquitto.conf" Delete "$INSTDIR\pwfile.example" Delete "$INSTDIR\readme.txt" Delete "$INSTDIR\readme-windows.txt" ;Delete "$INSTDIR\pthreadVC2.dll" Delete "$INSTDIR\libssl-1_1-x64.dll" Delete "$INSTDIR\libcrypto-1_1-x64.dll" Delete "$INSTDIR\edl-v10" Delete "$INSTDIR\epl-v10" Delete "$INSTDIR\devel\mosquitto.h" Delete "$INSTDIR\devel\mosquitto.lib" Delete "$INSTDIR\devel\mosquittopp.h" Delete "$INSTDIR\devel\mosquittopp.lib" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\Uninstall.exe" RMDir "$INSTDIR" DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto64" DeleteRegValue ${env_hklm} MOSQUITTO_DIR SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000 SectionEnd LangString DESC_SecInstall ${LANG_ENGLISH} "The main installation." LangString DESC_SecService ${LANG_ENGLISH} "Install mosquitto as a Windows service?" !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN !insertmacro MUI_DESCRIPTION_TEXT ${SecInstall} $(DESC_SecInstall) !insertmacro MUI_DESCRIPTION_TEXT ${SecService} $(DESC_SecService) !insertmacro MUI_FUNCTION_DESCRIPTION_END mosquitto-1.6.9/src/0000775000175000017500000000000013626052637013414 5ustar rogerrogermosquitto-1.6.9/src/mosquitto_broker_internal.h0000664000175000017500000007145313626052637021103 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. Tatsuzo Osawa - Add epoll. */ #ifndef MOSQUITTO_BROKER_INTERNAL_H #define MOSQUITTO_BROKER_INTERNAL_H #include "config.h" #include #ifdef WITH_WEBSOCKETS # include # if defined(LWS_LIBRARY_VERSION_NUMBER) # define libwebsocket_callback_on_writable(A, B) lws_callback_on_writable((B)) # define libwebsocket_service(A, B) lws_service((A), (B)) # define libwebsocket_create_context(A) lws_create_context((A)) # define libwebsocket_context_destroy(A) lws_context_destroy((A)) # define libwebsocket_write(A, B, C, D) lws_write((A), (B), (C), (D)) # define libwebsocket_get_socket_fd(A) lws_get_socket_fd((A)) # define libwebsockets_return_http_status(A, B, C, D) lws_return_http_status((B), (C), (D)) # define libwebsockets_get_protocol(A) lws_get_protocol((A)) # define libwebsocket_context lws_context # define libwebsocket_protocols lws_protocols # define libwebsocket_callback_reasons lws_callback_reasons # define libwebsocket lws # else # define lws_pollfd pollfd # define lws_service_fd(A, B) libwebsocket_service_fd((A), (B)) # define lws_pollargs libwebsocket_pollargs # endif #endif #include "mosquitto_internal.h" #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" #include "tls_mosq.h" #include "uthash.h" #define uhpa_malloc(size) mosquitto__malloc(size) #define uhpa_free(ptr) mosquitto__free(ptr) #include "uhpa.h" #ifndef __GNUC__ #define __attribute__(attrib) #endif /* Log destinations */ #define MQTT3_LOG_NONE 0x00 #define MQTT3_LOG_SYSLOG 0x01 #define MQTT3_LOG_FILE 0x02 #define MQTT3_LOG_STDOUT 0x04 #define MQTT3_LOG_STDERR 0x08 #define MQTT3_LOG_TOPIC 0x10 #define MQTT3_LOG_ALL 0xFF #define WEBSOCKET_CLIENT -2 #define TOPIC_HIERARCHY_LIMIT 200 /* ======================================== * UHPA data types * ======================================== */ /* See uhpa.h * * The idea here is that there is potentially a lot of wasted space (and time) * in malloc calls for frequent, small heap allocations. This can happen if * small payloads are used by clients or if individual topic elements are * small. * * In both cases, a struct is used that includes a void* or char* pointer to * point to the dynamically allocated memory used. To allocate and store a * single byte needs the size of the pointer (8 bytes on a 64 bit * architecture), the malloc overhead and the memory allocated itself (which * will often be larger than the memory requested, on 64 bit Linux this can be * a minimum of 24 bytes). To allocate and store 1 byte of heap memory we need * in this example 32 bytes. * * UHPA uses a union to either store data in an array, or to allocate memory on * the heap, depending on the size of the data being stored (this does mean * that the size of the data must always be known). Setting the size of the * array changes the point at which heap allocation starts. Using the example * above, this means that an array size of 32 bytes should not result in any * wasted space, and should be quicker as well. Certainly in the case of topic * elements (e.g. "bar" out of "foo/bar/baz") it is likely that an array size * of 32 bytes will mean that the majority of heap allocations are removed. * * You can change the size of MOSQ_PAYLOAD_UNION_SIZE and * MOSQ_TOPIC_ELEMENT_UNION_SIZE to change the size of the uhpa array used for * the payload (i.e. the published part of a message) and for topic elements * (e.g. "foo", "bar" or "baz" in the topic "foo/bar/baz"), and so control the * heap allocation threshold for these data types. You should look at your * application to decide what values to set, but don't set them too high * otherwise your overall memory usage will increase. * * You could use something like heaptrack * http://milianw.de/blog/heaptrack-a-heap-memory-profiler-for-linux to * profile heap allocations. * * I would suggest that values for MOSQ_PAYLOAD_UNION_SIZE and * MOSQ_TOPIC_UNION_SIZE that are equivalent to * sizeof(void*)+malloc_usable_size(malloc(1)) are a safe value that should * reduce calls to malloc without increasing memory usage at all. */ #define MOSQ_PAYLOAD_UNION_SIZE 8 typedef union { void *ptr; char array[MOSQ_PAYLOAD_UNION_SIZE]; } mosquitto__payload_uhpa; #define UHPA_ALLOC_PAYLOAD(A) UHPA_ALLOC((A)->payload, (A)->payloadlen) #define UHPA_ACCESS_PAYLOAD(A) UHPA_ACCESS((A)->payload, (A)->payloadlen) #define UHPA_FREE_PAYLOAD(A) UHPA_FREE((A)->payload, (A)->payloadlen) #define UHPA_MOVE_PAYLOAD(DEST, SRC) UHPA_MOVE((DEST)->payload, (SRC)->payload, (SRC)->payloadlen) /* ======================================== * End UHPA data types * ======================================== */ typedef uint64_t dbid_t; typedef int (*FUNC_auth_plugin_init_v4)(void **, struct mosquitto_opt *, int); typedef int (*FUNC_auth_plugin_cleanup_v4)(void *, struct mosquitto_opt *, int); typedef int (*FUNC_auth_plugin_security_init_v4)(void *, struct mosquitto_opt *, int, bool); typedef int (*FUNC_auth_plugin_security_cleanup_v4)(void *, struct mosquitto_opt *, int, bool); typedef int (*FUNC_auth_plugin_acl_check_v4)(void *, int, struct mosquitto *, struct mosquitto_acl_msg *); typedef int (*FUNC_auth_plugin_unpwd_check_v4)(void *, struct mosquitto *, const char *, const char *); typedef int (*FUNC_auth_plugin_psk_key_get_v4)(void *, struct mosquitto *, const char *, const char *, char *, int); typedef int (*FUNC_auth_plugin_auth_start_v4)(void *, struct mosquitto *, const char *, bool, const void *, uint16_t, void **, uint16_t *); typedef int (*FUNC_auth_plugin_auth_continue_v4)(void *, struct mosquitto *, const char *, const void *, uint16_t, void **, uint16_t *); typedef int (*FUNC_auth_plugin_init_v3)(void **, struct mosquitto_opt *, int); typedef int (*FUNC_auth_plugin_cleanup_v3)(void *, struct mosquitto_opt *, int); typedef int (*FUNC_auth_plugin_security_init_v3)(void *, struct mosquitto_opt *, int, bool); typedef int (*FUNC_auth_plugin_security_cleanup_v3)(void *, struct mosquitto_opt *, int, bool); typedef int (*FUNC_auth_plugin_acl_check_v3)(void *, int, const struct mosquitto *, struct mosquitto_acl_msg *); typedef int (*FUNC_auth_plugin_unpwd_check_v3)(void *, const struct mosquitto *, const char *, const char *); typedef int (*FUNC_auth_plugin_psk_key_get_v3)(void *, const struct mosquitto *, const char *, const char *, char *, int); typedef int (*FUNC_auth_plugin_init_v2)(void **, struct mosquitto_auth_opt *, int); typedef int (*FUNC_auth_plugin_cleanup_v2)(void *, struct mosquitto_auth_opt *, int); typedef int (*FUNC_auth_plugin_security_init_v2)(void *, struct mosquitto_auth_opt *, int, bool); typedef int (*FUNC_auth_plugin_security_cleanup_v2)(void *, struct mosquitto_auth_opt *, int, bool); typedef int (*FUNC_auth_plugin_acl_check_v2)(void *, const char *, const char *, const char *, int); typedef int (*FUNC_auth_plugin_unpwd_check_v2)(void *, const char *, const char *); typedef int (*FUNC_auth_plugin_psk_key_get_v2)(void *, const char *, const char *, char *, int); enum mosquitto_msg_origin{ mosq_mo_client = 0, mosq_mo_broker = 1 }; struct mosquitto__auth_plugin{ void *lib; void *user_data; int (*plugin_version)(void); FUNC_auth_plugin_init_v4 plugin_init_v4; FUNC_auth_plugin_cleanup_v4 plugin_cleanup_v4; FUNC_auth_plugin_security_init_v4 security_init_v4; FUNC_auth_plugin_security_cleanup_v4 security_cleanup_v4; FUNC_auth_plugin_acl_check_v4 acl_check_v4; FUNC_auth_plugin_unpwd_check_v4 unpwd_check_v4; FUNC_auth_plugin_psk_key_get_v4 psk_key_get_v4; FUNC_auth_plugin_auth_start_v4 auth_start_v4; FUNC_auth_plugin_auth_continue_v4 auth_continue_v4; FUNC_auth_plugin_init_v3 plugin_init_v3; FUNC_auth_plugin_cleanup_v3 plugin_cleanup_v3; FUNC_auth_plugin_security_init_v3 security_init_v3; FUNC_auth_plugin_security_cleanup_v3 security_cleanup_v3; FUNC_auth_plugin_acl_check_v3 acl_check_v3; FUNC_auth_plugin_unpwd_check_v3 unpwd_check_v3; FUNC_auth_plugin_psk_key_get_v3 psk_key_get_v3; FUNC_auth_plugin_init_v2 plugin_init_v2; FUNC_auth_plugin_cleanup_v2 plugin_cleanup_v2; FUNC_auth_plugin_security_init_v2 security_init_v2; FUNC_auth_plugin_security_cleanup_v2 security_cleanup_v2; FUNC_auth_plugin_acl_check_v2 acl_check_v2; FUNC_auth_plugin_unpwd_check_v2 unpwd_check_v2; FUNC_auth_plugin_psk_key_get_v2 psk_key_get_v2; int version; }; struct mosquitto__auth_plugin_config { char *path; struct mosquitto_opt *options; int option_count; bool deny_special_chars; struct mosquitto__auth_plugin plugin; }; struct mosquitto__security_options { /* Any options that get added here also need considering * in config__read() with regards whether allow_anonymous * should be disabled when these options are set. */ struct mosquitto__acl_user *acl_list; struct mosquitto__acl *acl_patterns; char *password_file; char *psk_file; char *acl_file; struct mosquitto__auth_plugin_config *auth_plugin_configs; int auth_plugin_config_count; int8_t allow_anonymous; bool allow_zero_length_clientid; char *auto_id_prefix; int auto_id_prefix_len; }; struct mosquitto__listener { int fd; uint16_t port; char *host; char *bind_interface; int max_connections; char *mount_point; mosq_sock_t *socks; int sock_count; int client_count; enum mosquitto_protocol protocol; int socket_domain; bool use_username_as_clientid; uint8_t maximum_qos; uint16_t max_topic_alias; #ifdef WITH_TLS char *cafile; char *capath; char *certfile; char *keyfile; char *tls_engine; char *tls_engine_kpass_sha1; char *ciphers; char *psk_hint; SSL_CTX *ssl_ctx; char *crlfile; char *tls_version; char *dhparamfile; bool use_identity_as_username; bool use_subject_as_username; bool require_certificate; enum mosquitto__keyform tls_keyform; #endif #ifdef WITH_WEBSOCKETS struct libwebsocket_context *ws_context; char *http_dir; struct libwebsocket_protocols *ws_protocol; #endif struct mosquitto__security_options security_options; struct mosquitto__unpwd *unpwd; struct mosquitto__unpwd *psk_id; }; struct mosquitto__config { bool allow_duplicate_messages; int autosave_interval; bool autosave_on_changes; bool check_retain_source; char *clientid_prefixes; bool connection_messages; bool daemon; struct mosquitto__listener default_listener; struct mosquitto__listener *listeners; int listener_count; int log_dest; int log_facility; unsigned int log_type; bool log_timestamp; char *log_timestamp_format; char *log_file; FILE *log_fptr; uint16_t max_inflight_messages; uint16_t max_keepalive; uint32_t max_packet_size; uint32_t message_size_limit; bool persistence; char *persistence_location; char *persistence_file; char *persistence_filepath; time_t persistent_client_expiration; char *pid_file; bool queue_qos0_messages; bool per_listener_settings; bool retain_available; bool set_tcp_nodelay; int sys_interval; bool upgrade_outgoing_qos; char *user; #ifdef WITH_WEBSOCKETS int websockets_log_level; int websockets_headers_size; bool have_websockets_listener; #endif #ifdef WITH_BRIDGE struct mosquitto__bridge *bridges; int bridge_count; #endif struct mosquitto__security_options security_options; }; struct mosquitto__subleaf { struct mosquitto__subleaf *prev; struct mosquitto__subleaf *next; struct mosquitto *context; uint32_t identifier; uint8_t qos; bool no_local; bool retain_as_published; }; struct mosquitto__subshared_ref { struct mosquitto__subhier *hier; struct mosquitto__subshared *shared; }; struct mosquitto__subshared { UT_hash_handle hh; char *name; struct mosquitto__subleaf *subs; }; struct mosquitto__subhier { UT_hash_handle hh; struct mosquitto__subhier *parent; struct mosquitto__subhier *children; struct mosquitto__subleaf *subs; struct mosquitto__subshared *shared; struct mosquitto_msg_store *retained; char *topic; uint16_t topic_len; }; struct mosquitto_msg_store_load{ UT_hash_handle hh; dbid_t db_id; struct mosquitto_msg_store *store; }; struct mosquitto_msg_store{ struct mosquitto_msg_store *next; struct mosquitto_msg_store *prev; dbid_t db_id; char *source_id; char *source_username; struct mosquitto__listener *source_listener; char **dest_ids; int dest_id_count; int ref_count; char* topic; mosquitto_property *properties; mosquitto__payload_uhpa payload; time_t message_expiry_time; uint32_t payloadlen; uint16_t source_mid; uint16_t mid; uint8_t qos; bool retain; uint8_t origin; }; struct mosquitto_client_msg{ struct mosquitto_client_msg *prev; struct mosquitto_client_msg *next; struct mosquitto_msg_store *store; mosquitto_property *properties; time_t timestamp; uint16_t mid; uint8_t qos; bool retain; enum mosquitto_msg_direction direction; enum mosquitto_msg_state state; bool dup; }; struct mosquitto__unpwd{ char *username; char *password; #ifdef WITH_TLS unsigned int password_len; unsigned int salt_len; unsigned char *salt; #endif UT_hash_handle hh; }; struct mosquitto__acl{ struct mosquitto__acl *next; char *topic; int access; int ucount; int ccount; }; struct mosquitto__acl_user{ struct mosquitto__acl_user *next; char *username; struct mosquitto__acl *acl; }; struct mosquitto_db{ dbid_t last_db_id; struct mosquitto__subhier *subs; struct mosquitto__unpwd *unpwd; struct mosquitto__unpwd *psk_id; struct mosquitto *contexts_by_id; struct mosquitto *contexts_by_sock; struct mosquitto *contexts_for_free; #ifdef WITH_BRIDGE struct mosquitto **bridges; #endif struct clientid__index_hash *clientid_index_hash; struct mosquitto_msg_store *msg_store; struct mosquitto_msg_store_load *msg_store_load; #ifdef WITH_BRIDGE int bridge_count; #endif int msg_store_count; unsigned long msg_store_bytes; char *config_file; struct mosquitto__config *config; int auth_plugin_count; bool verbose; #ifdef WITH_SYS_TREE int subscription_count; int shared_subscription_count; int retained_count; #endif int persistence_changes; struct mosquitto *ll_for_free; #ifdef WITH_EPOLL int epollfd; #endif }; enum mosquitto__bridge_direction{ bd_out = 0, bd_in = 1, bd_both = 2 }; enum mosquitto_bridge_start_type{ bst_automatic = 0, bst_lazy = 1, bst_manual = 2, bst_once = 3 }; struct mosquitto__bridge_topic{ char *topic; int qos; enum mosquitto__bridge_direction direction; char *local_prefix; char *remote_prefix; char *local_topic; /* topic prefixed with local_prefix */ char *remote_topic; /* topic prefixed with remote_prefix */ }; struct bridge_address{ char *address; int port; }; struct mosquitto__bridge{ char *name; struct bridge_address *addresses; int cur_address; int address_count; time_t primary_retry; mosq_sock_t primary_retry_sock; bool round_robin; bool try_private; bool try_private_accepted; bool clean_start; int keepalive; struct mosquitto__bridge_topic *topics; int topic_count; bool topic_remapping; enum mosquitto__protocol protocol_version; time_t restart_t; char *remote_clientid; char *remote_username; char *remote_password; char *local_clientid; char *local_username; char *local_password; char *notification_topic; bool notifications; bool notifications_local_only; enum mosquitto_bridge_start_type start_type; int idle_timeout; int restart_timeout; int backoff_base; int backoff_cap; int threshold; bool lazy_reconnect; bool attempt_unsubscribe; bool initial_notification_done; #ifdef WITH_TLS bool tls_insecure; bool tls_ocsp_required; char *tls_cafile; char *tls_capath; char *tls_certfile; char *tls_keyfile; char *tls_version; char *tls_alpn; # ifdef FINAL_WITH_TLS_PSK char *tls_psk_identity; char *tls_psk; # endif #endif }; #ifdef WITH_WEBSOCKETS struct libws_mqtt_hack { char *http_dir; }; struct libws_mqtt_data { struct mosquitto *mosq; }; #endif #include /* ============================================================ * Main functions * ============================================================ */ int mosquitto_main_loop(struct mosquitto_db *db, mosq_sock_t *listensock, int listensock_count); struct mosquitto_db *mosquitto__get_db(void); /* ============================================================ * Config functions * ============================================================ */ /* Initialise config struct to default values. */ void config__init(struct mosquitto_db *db, struct mosquitto__config *config); /* Parse command line options into config. */ int config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]); /* Read configuration data from config->config_file into config. * If reload is true, don't process config options that shouldn't be reloaded (listeners etc) * Returns 0 on success, 1 if there is a configuration error or if a file cannot be opened. */ int config__read(struct mosquitto_db *db, struct mosquitto__config *config, bool reload); /* Free all config data. */ void config__cleanup(struct mosquitto__config *config); int config__get_dir_files(const char *include_dir, char ***files, int *file_count); int drop_privileges(struct mosquitto__config *config, bool temporary); int restore_privileges(void); /* ============================================================ * Server send functions * ============================================================ */ int send__connack(struct mosquitto_db *db, struct mosquitto *context, int ack, int reason_code, const mosquitto_property *properties); int send__suback(struct mosquitto *context, uint16_t mid, uint32_t payloadlen, const void *payload); int send__unsuback(struct mosquitto *context, uint16_t mid, int reason_code_count, uint8_t *reason_codes, const mosquitto_property *properties); int send__auth(struct mosquitto_db *db, struct mosquitto *context, int reason_code, const void *auth_data, uint16_t auth_data_len); /* ============================================================ * Network functions * ============================================================ */ void net__broker_init(void); void net__broker_cleanup(void); int net__socket_accept(struct mosquitto_db *db, mosq_sock_t listensock); int net__socket_listen(struct mosquitto__listener *listener); int net__socket_get_address(mosq_sock_t sock, char *buf, int len); int net__tls_load_verify(struct mosquitto__listener *listener); int net__tls_server_ctx(struct mosquitto__listener *listener); /* ============================================================ * Read handling functions * ============================================================ */ int handle__packet(struct mosquitto_db *db, struct mosquitto *context); int handle__connack(struct mosquitto_db *db, struct mosquitto *context); int handle__connect(struct mosquitto_db *db, struct mosquitto *context); int handle__disconnect(struct mosquitto_db *db, struct mosquitto *context); int handle__publish(struct mosquitto_db *db, struct mosquitto *context); int handle__subscribe(struct mosquitto_db *db, struct mosquitto *context); int handle__unsubscribe(struct mosquitto_db *db, struct mosquitto *context); int handle__auth(struct mosquitto_db *db, struct mosquitto *context); /* ============================================================ * Database handling * ============================================================ */ int db__open(struct mosquitto__config *config, struct mosquitto_db *db); int db__close(struct mosquitto_db *db); #ifdef WITH_PERSISTENCE int persist__backup(struct mosquitto_db *db, bool shutdown); int persist__restore(struct mosquitto_db *db); #endif void db__limits_set(unsigned long inflight_bytes, int queued, unsigned long queued_bytes); /* Return the number of in-flight messages in count. */ int db__message_count(int *count); int db__message_delete_outgoing(struct mosquitto_db *db, struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state expect_state, int qos); int db__message_insert(struct mosquitto_db *db, struct mosquitto *context, uint16_t mid, enum mosquitto_msg_direction dir, int qos, bool retain, struct mosquitto_msg_store *stored, mosquitto_property *properties); int db__message_release_incoming(struct mosquitto_db *db, struct mosquitto *context, uint16_t mid); int db__message_update_outgoing(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state state, int qos); int db__message_write(struct mosquitto_db *db, struct mosquitto *context); void db__message_dequeue_first(struct mosquitto *context, struct mosquitto_msg_data *msg_data); int db__messages_delete(struct mosquitto_db *db, struct mosquitto *context); int db__messages_easy_queue(struct mosquitto_db *db, struct mosquitto *context, const char *topic, int qos, uint32_t payloadlen, const void *payload, int retain, uint32_t message_expiry_interval, mosquitto_property **properties); int db__message_store(struct mosquitto_db *db, const struct mosquitto *source, uint16_t source_mid, char *topic, int qos, uint32_t payloadlen, mosquitto__payload_uhpa *payload, int retain, struct mosquitto_msg_store **stored, uint32_t message_expiry_interval, mosquitto_property *properties, dbid_t store_id, enum mosquitto_msg_origin origin); int db__message_store_find(struct mosquitto *context, uint16_t mid, struct mosquitto_msg_store **stored); void db__msg_store_add(struct mosquitto_db *db, struct mosquitto_msg_store *store); void db__msg_store_remove(struct mosquitto_db *db, struct mosquitto_msg_store *store); void db__msg_store_ref_inc(struct mosquitto_msg_store *store); void db__msg_store_ref_dec(struct mosquitto_db *db, struct mosquitto_msg_store **store); void db__msg_store_clean(struct mosquitto_db *db); void db__msg_store_compact(struct mosquitto_db *db); int db__message_reconnect_reset(struct mosquitto_db *db, struct mosquitto *context); void sys_tree__init(struct mosquitto_db *db); void sys_tree__update(struct mosquitto_db *db, int interval, time_t start_time); /* ============================================================ * Subscription functions * ============================================================ */ int sub__add(struct mosquitto_db *db, struct mosquitto *context, const char *sub, int qos, uint32_t identifier, int options, struct mosquitto__subhier **root); struct mosquitto__subhier *sub__add_hier_entry(struct mosquitto__subhier *parent, struct mosquitto__subhier **sibling, const char *topic, size_t len); int sub__remove(struct mosquitto_db *db, struct mosquitto *context, const char *sub, struct mosquitto__subhier *root, uint8_t *reason); void sub__tree_print(struct mosquitto__subhier *root, int level); int sub__clean_session(struct mosquitto_db *db, struct mosquitto *context); int sub__retain_queue(struct mosquitto_db *db, struct mosquitto *context, const char *sub, int sub_qos, uint32_t subscription_identifier); int sub__messages_queue(struct mosquitto_db *db, const char *source_id, const char *topic, int qos, int retain, struct mosquitto_msg_store **stored); /* ============================================================ * Context functions * ============================================================ */ struct mosquitto *context__init(struct mosquitto_db *db, mosq_sock_t sock); void context__cleanup(struct mosquitto_db *db, struct mosquitto *context, bool do_free); void context__disconnect(struct mosquitto_db *db, struct mosquitto *context); void context__add_to_disused(struct mosquitto_db *db, struct mosquitto *context); void context__free_disused(struct mosquitto_db *db); void context__send_will(struct mosquitto_db *db, struct mosquitto *context); void context__remove_from_by_id(struct mosquitto_db *db, struct mosquitto *context); int connect__on_authorised(struct mosquitto_db *db, struct mosquitto *context, void *auth_data_out, uint16_t auth_data_out_len); /* ============================================================ * Logging functions * ============================================================ */ int log__init(struct mosquitto__config *config); int log__close(struct mosquitto__config *config); int log__printf(struct mosquitto *mosq, int level, const char *fmt, ...) __attribute__((format(printf, 3, 4))); void log__internal(const char *fmt, ...) __attribute__((format(printf, 1, 2))); /* ============================================================ * Bridge functions * ============================================================ */ #ifdef WITH_BRIDGE int bridge__new(struct mosquitto_db *db, struct mosquitto__bridge *bridge); int bridge__connect(struct mosquitto_db *db, struct mosquitto *context); int bridge__connect_step1(struct mosquitto_db *db, struct mosquitto *context); int bridge__connect_step2(struct mosquitto_db *db, struct mosquitto *context); int bridge__connect_step3(struct mosquitto_db *db, struct mosquitto *context); void bridge__packet_cleanup(struct mosquitto *context); #endif /* ============================================================ * Property related functions * ============================================================ */ int property__process_connect(struct mosquitto *context, mosquitto_property **props); int property__process_will(struct mosquitto *context, struct mosquitto_message_all *msg, mosquitto_property **props); int property__process_disconnect(struct mosquitto *context, mosquitto_property **props); /* ============================================================ * Security related functions * ============================================================ */ int acl__find_acls(struct mosquitto_db *db, struct mosquitto *context); int mosquitto_security_module_init(struct mosquitto_db *db); int mosquitto_security_module_cleanup(struct mosquitto_db *db); int mosquitto_security_init(struct mosquitto_db *db, bool reload); int mosquitto_security_apply(struct mosquitto_db *db); int mosquitto_security_cleanup(struct mosquitto_db *db, bool reload); int mosquitto_acl_check(struct mosquitto_db *db, struct mosquitto *context, const char *topic, long payloadlen, void* payload, int qos, bool retain, int access); int mosquitto_unpwd_check(struct mosquitto_db *db, struct mosquitto *context, const char *username, const char *password); int mosquitto_psk_key_get(struct mosquitto_db *db, struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len); int mosquitto_security_init_default(struct mosquitto_db *db, bool reload); int mosquitto_security_apply_default(struct mosquitto_db *db); int mosquitto_security_cleanup_default(struct mosquitto_db *db, bool reload); int mosquitto_acl_check_default(struct mosquitto_db *db, struct mosquitto *context, const char *topic, int access); int mosquitto_unpwd_check_default(struct mosquitto_db *db, struct mosquitto *context, const char *username, const char *password); int mosquitto_psk_key_get_default(struct mosquitto_db *db, struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len); int mosquitto_security_auth_start(struct mosquitto_db *db, struct mosquitto *context, bool reauth, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len); int mosquitto_security_auth_continue(struct mosquitto_db *db, struct mosquitto *context, const void *data_in, uint16_t data_len, void **data_out, uint16_t *data_out_len); /* ============================================================ * Session expiry * ============================================================ */ int session_expiry__add(struct mosquitto_db *db, struct mosquitto *context); void session_expiry__remove(struct mosquitto *context); void session_expiry__remove_all(struct mosquitto_db *db); void session_expiry__check(struct mosquitto_db *db, time_t now); void session_expiry__send_all(struct mosquitto_db *db); /* ============================================================ * Window service and signal related functions * ============================================================ */ #if defined(WIN32) || defined(__CYGWIN__) void service_install(void); void service_uninstall(void); void service_run(void); DWORD WINAPI SigThreadProc(void* data); #endif /* ============================================================ * Websockets related functions * ============================================================ */ #ifdef WITH_WEBSOCKETS # if defined(LWS_LIBRARY_VERSION_NUMBER) struct lws_context *mosq_websockets_init(struct mosquitto__listener *listener, const struct mosquitto__config *conf); # else struct libwebsocket_context *mosq_websockets_init(struct mosquitto__listener *listener, const struct mosquitto__config *conf); # endif #endif void do_disconnect(struct mosquitto_db *db, struct mosquitto *context, int reason); /* ============================================================ * Will delay * ============================================================ */ int will_delay__add(struct mosquitto *context); void will_delay__check(struct mosquitto_db *db, time_t now); void will_delay__send_all(struct mosquitto_db *db); void will_delay__remove(struct mosquitto *mosq); #endif mosquitto-1.6.9/src/security_default.c0000664000175000017500000010314113626052637017133 0ustar rogerroger/* Copyright (c) 2011-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "send_mosq.h" #include "misc_mosq.h" #include "util_mosq.h" static int aclfile__parse(struct mosquitto_db *db, struct mosquitto__security_options *security_opts); static int unpwd__file_parse(struct mosquitto__unpwd **unpwd, const char *password_file); static int acl__cleanup(struct mosquitto_db *db, bool reload); static int unpwd__cleanup(struct mosquitto__unpwd **unpwd, bool reload); static int psk__file_parse(struct mosquitto_db *db, struct mosquitto__unpwd **psk_id, const char *psk_file); #ifdef WITH_TLS static int pw__digest(const char *password, const unsigned char *salt, unsigned int salt_len, unsigned char *hash, unsigned int *hash_len); static int base64__decode(char *in, unsigned char **decoded, unsigned int *decoded_len); static int mosquitto__memcmp_const(const void *ptr1, const void *b, size_t len); #endif int mosquitto_security_init_default(struct mosquitto_db *db, bool reload) { int rc; int i; char *pwf; char *pskf; UNUSED(reload); /* Load username/password data if required. */ if(db->config->per_listener_settings){ for(i=0; iconfig->listener_count; i++){ pwf = db->config->listeners[i].security_options.password_file; if(pwf){ rc = unpwd__file_parse(&db->config->listeners[i].unpwd, pwf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening password file \"%s\".", pwf); return rc; } } } }else{ if(db->config->security_options.password_file){ pwf = db->config->security_options.password_file; if(pwf){ rc = unpwd__file_parse(&db->unpwd, pwf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening password file \"%s\".", pwf); return rc; } } } } /* Load acl data if required. */ if(db->config->per_listener_settings){ for(i=0; iconfig->listener_count; i++){ if(db->config->listeners[i].security_options.acl_file){ rc = aclfile__parse(db, &db->config->listeners[i].security_options); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening acl file \"%s\".", db->config->listeners[i].security_options.acl_file); return rc; } } } }else{ if(db->config->security_options.acl_file){ rc = aclfile__parse(db, &db->config->security_options); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening acl file \"%s\".", db->config->security_options.acl_file); return rc; } } } /* Load psk data if required. */ if(db->config->per_listener_settings){ for(i=0; iconfig->listener_count; i++){ pskf = db->config->listeners[i].security_options.psk_file; if(pskf){ rc = psk__file_parse(db, &db->config->listeners[i].psk_id, pskf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening psk file \"%s\".", pskf); return rc; } } } }else{ char *pskf = db->config->security_options.psk_file; if(pskf){ rc = psk__file_parse(db, &db->psk_id, pskf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening psk file \"%s\".", pskf); return rc; } } } return MOSQ_ERR_SUCCESS; } int mosquitto_security_cleanup_default(struct mosquitto_db *db, bool reload) { int rc; int i; rc = acl__cleanup(db, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; rc = unpwd__cleanup(&db->unpwd, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; for(i=0; iconfig->listener_count; i++){ if(db->config->listeners[i].unpwd){ rc = unpwd__cleanup(&db->config->listeners[i].unpwd, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } } rc = unpwd__cleanup(&db->psk_id, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; for(i=0; iconfig->listener_count; i++){ if(db->config->listeners[i].psk_id){ rc = unpwd__cleanup(&db->config->listeners[i].psk_id, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } } return MOSQ_ERR_SUCCESS; } int add__acl(struct mosquitto__security_options *security_opts, const char *user, const char *topic, int access) { struct mosquitto__acl_user *acl_user=NULL, *user_tail; struct mosquitto__acl *acl, *acl_tail; char *local_topic; bool new_user = false; if(!security_opts || !topic) return MOSQ_ERR_INVAL; local_topic = mosquitto__strdup(topic); if(!local_topic){ return MOSQ_ERR_NOMEM; } if(security_opts->acl_list){ user_tail = security_opts->acl_list; while(user_tail){ if(user == NULL){ if(user_tail->username == NULL){ acl_user = user_tail; break; } }else if(user_tail->username && !strcmp(user_tail->username, user)){ acl_user = user_tail; break; } user_tail = user_tail->next; } } if(!acl_user){ acl_user = mosquitto__malloc(sizeof(struct mosquitto__acl_user)); if(!acl_user){ mosquitto__free(local_topic); return MOSQ_ERR_NOMEM; } new_user = true; if(user){ acl_user->username = mosquitto__strdup(user); if(!acl_user->username){ mosquitto__free(local_topic); mosquitto__free(acl_user); return MOSQ_ERR_NOMEM; } }else{ acl_user->username = NULL; } acl_user->next = NULL; acl_user->acl = NULL; } acl = mosquitto__malloc(sizeof(struct mosquitto__acl)); if(!acl){ mosquitto__free(local_topic); mosquitto__free(acl_user->username); mosquitto__free(acl_user); return MOSQ_ERR_NOMEM; } acl->access = access; acl->topic = local_topic; acl->next = NULL; acl->ccount = 0; acl->ucount = 0; /* Add acl to user acl list */ if(acl_user->acl){ acl_tail = acl_user->acl; while(acl_tail->next){ acl_tail = acl_tail->next; } acl_tail->next = acl; }else{ acl_user->acl = acl; } if(new_user){ /* Add to end of list */ if(security_opts->acl_list){ user_tail = security_opts->acl_list; while(user_tail->next){ user_tail = user_tail->next; } user_tail->next = acl_user; }else{ security_opts->acl_list = acl_user; } } return MOSQ_ERR_SUCCESS; } int add__acl_pattern(struct mosquitto__security_options *security_opts, const char *topic, int access) { struct mosquitto__acl *acl, *acl_tail; char *local_topic; char *s; if(!security_opts| !topic) return MOSQ_ERR_INVAL; local_topic = mosquitto__strdup(topic); if(!local_topic){ return MOSQ_ERR_NOMEM; } acl = mosquitto__malloc(sizeof(struct mosquitto__acl)); if(!acl){ mosquitto__free(local_topic); return MOSQ_ERR_NOMEM; } acl->access = access; acl->topic = local_topic; acl->next = NULL; acl->ccount = 0; s = local_topic; while(s){ s = strstr(s, "%c"); if(s){ acl->ccount++; s+=2; } } acl->ucount = 0; s = local_topic; while(s){ s = strstr(s, "%u"); if(s){ acl->ucount++; s+=2; } } if(acl->ccount == 0 && acl->ucount == 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: ACL pattern '%s' does not contain '%%c' or '%%u'.", topic); } if(security_opts->acl_patterns){ acl_tail = security_opts->acl_patterns; while(acl_tail->next){ acl_tail = acl_tail->next; } acl_tail->next = acl; }else{ security_opts->acl_patterns = acl; } return MOSQ_ERR_SUCCESS; } int mosquitto_acl_check_default(struct mosquitto_db *db, struct mosquitto *context, const char *topic, int access) { char *local_acl; struct mosquitto__acl *acl_root; bool result; int i; int len, tlen, clen, ulen; char *s; struct mosquitto__security_options *security_opts = NULL; if(!db || !context || !topic) return MOSQ_ERR_INVAL; if(context->bridge) return MOSQ_ERR_SUCCESS; if(db->config->per_listener_settings){ if(!context->listener) return MOSQ_ERR_ACL_DENIED; security_opts = &context->listener->security_options; }else{ security_opts = &db->config->security_options; } if(!security_opts->acl_file && !security_opts->acl_list && !security_opts->acl_patterns){ return MOSQ_ERR_PLUGIN_DEFER; } if(access == MOSQ_ACL_SUBSCRIBE) return MOSQ_ERR_SUCCESS; /* FIXME - implement ACL subscription strings. */ if(!context->acl_list && !security_opts->acl_patterns) return MOSQ_ERR_ACL_DENIED; if(context->acl_list){ acl_root = context->acl_list->acl; }else{ acl_root = NULL; } /* Loop through all ACLs for this client. */ while(acl_root){ /* Loop through the topic looking for matches to this ACL. */ /* If subscription starts with $, acl_root->topic must also start with $. */ if(topic[0] == '$' && acl_root->topic[0] != '$'){ acl_root = acl_root->next; continue; } mosquitto_topic_matches_sub(acl_root->topic, topic, &result); if(result){ if(access & acl_root->access){ /* And access is allowed. */ return MOSQ_ERR_SUCCESS; } } acl_root = acl_root->next; } acl_root = security_opts->acl_patterns; if(acl_root){ /* We are using pattern based acls. Check whether the username or * client id contains a + or # and if so deny access. * * Without this, a malicious client may configure its username/client * id to bypass ACL checks (or have a username/client id that cannot * publish or receive messages to its own place in the hierarchy). */ if(context->username && strpbrk(context->username, "+#")){ log__printf(NULL, MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous username \"%s\"", context->username); return MOSQ_ERR_ACL_DENIED; } if(context->id && strpbrk(context->id, "+#")){ log__printf(NULL, MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous client id \"%s\"", context->id); return MOSQ_ERR_ACL_DENIED; } } /* Loop through all pattern ACLs. */ if(!context->id) return MOSQ_ERR_ACL_DENIED; clen = strlen(context->id); while(acl_root){ tlen = strlen(acl_root->topic); if(acl_root->ucount && !context->username){ acl_root = acl_root->next; continue; } if(context->username){ ulen = strlen(context->username); len = tlen + acl_root->ccount*(clen-2) + acl_root->ucount*(ulen-2); }else{ ulen = 0; len = tlen + acl_root->ccount*(clen-2); } local_acl = mosquitto__malloc(len+1); if(!local_acl) return 1; // FIXME s = local_acl; for(i=0; itopic[i] == '%'){ if(acl_root->topic[i+1] == 'c'){ i++; strncpy(s, context->id, clen); s+=clen; continue; }else if(context->username && acl_root->topic[i+1] == 'u'){ i++; strncpy(s, context->username, ulen); s+=ulen; continue; } } s[0] = acl_root->topic[i]; s++; } local_acl[len] = '\0'; mosquitto_topic_matches_sub(local_acl, topic, &result); mosquitto__free(local_acl); if(result){ if(access & acl_root->access){ /* And access is allowed. */ return MOSQ_ERR_SUCCESS; } } acl_root = acl_root->next; } return MOSQ_ERR_ACL_DENIED; } static int aclfile__parse(struct mosquitto_db *db, struct mosquitto__security_options *security_opts) { FILE *aclfptr = NULL; char *token; char *user = NULL; char *topic; char *access_s; int access; int rc = MOSQ_ERR_SUCCESS; int slen; int topic_pattern; char *saveptr = NULL; char *buf = NULL; int buflen = 256; if(!db || !db->config) return MOSQ_ERR_INVAL; if(!security_opts) return MOSQ_ERR_INVAL; if(!security_opts->acl_file) return MOSQ_ERR_SUCCESS; buf = mosquitto__malloc(buflen); if(buf == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return 1; } aclfptr = mosquitto__fopen(security_opts->acl_file, "rt", false); if(!aclfptr){ mosquitto__free(buf); log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open acl_file \"%s\".", security_opts->acl_file); return 1; } // topic [read|write] // user while(fgets_extending(&buf, &buflen, aclfptr)){ slen = strlen(buf); while(slen > 0 && isspace(buf[slen-1])){ buf[slen-1] = '\0'; slen = strlen(buf); } if(buf[0] == '#'){ continue; } token = strtok_r(buf, " ", &saveptr); if(token){ if(!strcmp(token, "topic") || !strcmp(token, "pattern")){ if(!strcmp(token, "topic")){ topic_pattern = 0; }else{ topic_pattern = 1; } access_s = strtok_r(NULL, " ", &saveptr); if(!access_s){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty topic in acl_file \"%s\".", security_opts->acl_file); rc = MOSQ_ERR_INVAL; break; } token = strtok_r(NULL, "", &saveptr); if(token){ topic = misc__trimblanks(token); }else{ topic = access_s; access_s = NULL; } if(access_s){ if(!strcmp(access_s, "read")){ access = MOSQ_ACL_READ; }else if(!strcmp(access_s, "write")){ access = MOSQ_ACL_WRITE; }else if(!strcmp(access_s, "readwrite")){ access = MOSQ_ACL_READ | MOSQ_ACL_WRITE; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid topic access type \"%s\" in acl_file \"%s\".", access_s, security_opts->acl_file); rc = MOSQ_ERR_INVAL; break; } }else{ access = MOSQ_ACL_READ | MOSQ_ACL_WRITE; } rc = mosquitto_sub_topic_check(topic); if(rc != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid ACL topic \"%s\" in acl_file \"%s\".", topic, security_opts->acl_file); rc = MOSQ_ERR_INVAL; break; } if(topic_pattern == 0){ rc = add__acl(security_opts, user, topic, access); }else{ rc = add__acl_pattern(security_opts, topic, access); } if(rc){ break; } }else if(!strcmp(token, "user")){ token = strtok_r(NULL, "", &saveptr); if(token){ token = misc__trimblanks(token); if(slen == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Missing username in acl_file \"%s\".", security_opts->acl_file); rc = MOSQ_ERR_INVAL; break; } mosquitto__free(user); user = mosquitto__strdup(token); if(!user){ rc = MOSQ_ERR_NOMEM; break; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Missing username in acl_file \"%s\".", security_opts->acl_file); rc = MOSQ_ERR_INVAL; break; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid line in acl_file \"%s\": %s.", security_opts->acl_file, buf); rc = MOSQ_ERR_INVAL; break; } } } mosquitto__free(buf); mosquitto__free(user); fclose(aclfptr); return rc; } static void free__acl(struct mosquitto__acl *acl) { if(!acl) return; if(acl->next){ free__acl(acl->next); } mosquitto__free(acl->topic); mosquitto__free(acl); } static void acl__cleanup_single(struct mosquitto__security_options *security_opts) { struct mosquitto__acl_user *user_tail; while(security_opts->acl_list){ user_tail = security_opts->acl_list->next; free__acl(security_opts->acl_list->acl); mosquitto__free(security_opts->acl_list->username); mosquitto__free(security_opts->acl_list); security_opts->acl_list = user_tail; } if(security_opts->acl_patterns){ free__acl(security_opts->acl_patterns); security_opts->acl_patterns = NULL; } } static int acl__cleanup(struct mosquitto_db *db, bool reload) { struct mosquitto *context, *ctxt_tmp; int i; UNUSED(reload); if(!db) return MOSQ_ERR_INVAL; /* As we're freeing ACLs, we must clear context->acl_list to ensure no * invalid memory accesses take place later. * This *requires* the ACLs to be reapplied after acl__cleanup() * is called if we are reloading the config. If this is not done, all * access will be denied to currently connected clients. */ HASH_ITER(hh_id, db->contexts_by_id, context, ctxt_tmp){ context->acl_list = NULL; } if(db->config->per_listener_settings){ for(i=0; iconfig->listener_count; i++){ acl__cleanup_single(&db->config->listeners[i].security_options); } }else{ acl__cleanup_single(&db->config->security_options); } return MOSQ_ERR_SUCCESS; } int acl__find_acls(struct mosquitto_db *db, struct mosquitto *context) { struct mosquitto__acl_user *acl_tail; struct mosquitto__security_options *security_opts; /* Associate user with its ACL, assuming we have ACLs loaded. */ if(db->config->per_listener_settings){ if(!context->listener){ return MOSQ_ERR_INVAL; } security_opts = &context->listener->security_options; }else{ security_opts = &db->config->security_options; } if(security_opts->acl_list){ acl_tail = security_opts->acl_list; while(acl_tail){ if(context->username){ if(acl_tail->username && !strcmp(context->username, acl_tail->username)){ context->acl_list = acl_tail; break; } }else{ if(acl_tail->username == NULL){ context->acl_list = acl_tail; break; } } acl_tail = acl_tail->next; } }else{ context->acl_list = NULL; } return MOSQ_ERR_SUCCESS; } static int pwfile__parse(const char *file, struct mosquitto__unpwd **root) { FILE *pwfile; struct mosquitto__unpwd *unpwd; char *username, *password; char *saveptr = NULL; char *buf; int buflen = 256; buf = mosquitto__malloc(buflen); if(buf == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return 1; } pwfile = mosquitto__fopen(file, "rt", false); if(!pwfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open pwfile \"%s\".", file); mosquitto__free(buf); return 1; } while(!feof(pwfile)){ if(fgets_extending(&buf, &buflen, pwfile)){ if(buf[0] == '#') continue; if(!strchr(buf, ':')) continue; username = strtok_r(buf, ":", &saveptr); if(username){ unpwd = mosquitto__calloc(1, sizeof(struct mosquitto__unpwd)); if(!unpwd){ fclose(pwfile); mosquitto__free(buf); return MOSQ_ERR_NOMEM; } username = misc__trimblanks(username); if(strlen(username) > 65535){ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Invalid line in password file '%s', username too long.", file); mosquitto__free(unpwd); continue; } unpwd->username = mosquitto__strdup(username); if(!unpwd->username){ mosquitto__free(unpwd); mosquitto__free(buf); fclose(pwfile); return MOSQ_ERR_NOMEM; } password = strtok_r(NULL, ":", &saveptr); if(password){ password = misc__trimblanks(password); if(strlen(password) > 65535){ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Invalid line in password file '%s', password too long.", file); mosquitto__free(unpwd->username); mosquitto__free(unpwd); continue; } unpwd->password = mosquitto__strdup(password); if(!unpwd->password){ fclose(pwfile); mosquitto__free(unpwd->username); mosquitto__free(unpwd); mosquitto__free(buf); return MOSQ_ERR_NOMEM; } HASH_ADD_KEYPTR(hh, *root, unpwd->username, strlen(unpwd->username), unpwd); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Invalid line in password file '%s': %s", file, buf); mosquitto__free(unpwd->username); mosquitto__free(unpwd); } } } } fclose(pwfile); mosquitto__free(buf); return MOSQ_ERR_SUCCESS; } #ifdef WITH_TLS static void unpwd__free_item(struct mosquitto__unpwd **unpwd, struct mosquitto__unpwd *item) { mosquitto__free(item->username); mosquitto__free(item->password); mosquitto__free(item->salt); HASH_DEL(*unpwd, item); mosquitto__free(item); } static int unpwd__decode_passwords(struct mosquitto__unpwd **unpwd) { struct mosquitto__unpwd *u, *tmp; char *token; unsigned char *salt; unsigned int salt_len; unsigned char *password; unsigned int password_len; int rc; HASH_ITER(hh, *unpwd, u, tmp){ /* Need to decode password into hashed data + salt. */ if(u->password){ token = strtok(u->password, "$"); if(token && !strcmp(token, "6")){ token = strtok(NULL, "$"); if(token){ rc = base64__decode(token, &salt, &salt_len); if(rc == MOSQ_ERR_SUCCESS && salt_len == 12){ u->salt = salt; u->salt_len = salt_len; token = strtok(NULL, "$"); if(token){ rc = base64__decode(token, &password, &password_len); if(rc == MOSQ_ERR_SUCCESS && password_len == 64){ mosquitto__free(u->password); u->password = (char *)password; u->password_len = password_len; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to decode password for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to decode password salt for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Missing password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); } } return MOSQ_ERR_SUCCESS; } #endif static int unpwd__file_parse(struct mosquitto__unpwd **unpwd, const char *password_file) { int rc; if(!unpwd) return MOSQ_ERR_INVAL; if(!password_file) return MOSQ_ERR_SUCCESS; rc = pwfile__parse(password_file, unpwd); #ifdef WITH_TLS if(rc) return rc; rc = unpwd__decode_passwords(unpwd); #endif return rc; } static int psk__file_parse(struct mosquitto_db *db, struct mosquitto__unpwd **psk_id, const char *psk_file) { int rc; struct mosquitto__unpwd *u, *tmp; if(!db || !db->config || !psk_id) return MOSQ_ERR_INVAL; /* We haven't been asked to parse a psk file. */ if(!psk_file) return MOSQ_ERR_SUCCESS; rc = pwfile__parse(psk_file, psk_id); if(rc) return rc; HASH_ITER(hh, (*psk_id), u, tmp){ /* Check for hex only digits */ if(!u->password){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty psk for identity \"%s\".", u->username); return MOSQ_ERR_INVAL; } if(strspn(u->password, "0123456789abcdefABCDEF") < strlen(u->password)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: psk for identity \"%s\" contains non-hexadecimal characters.", u->username); return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } #ifdef WITH_TLS static int mosquitto__memcmp_const(const void *a, const void *b, size_t len) { size_t i; int rc = 0; if(!a || !b) return 1; for(i=0; iconfig->per_listener_settings){ if(context->bridge) return MOSQ_ERR_SUCCESS; if(!context->listener) return MOSQ_ERR_INVAL; if(context->listener->security_options.password_file == NULL) return MOSQ_ERR_PLUGIN_DEFER; unpwd_ref = context->listener->unpwd; }else{ if(db->config->security_options.password_file == NULL) return MOSQ_ERR_PLUGIN_DEFER; unpwd_ref = db->unpwd; } if(!username){ /* Check must be made only after checking unpwd_ref. * This is DENY here, because in MQTT v5 username can be missing when * password is present, but we don't support that. */ return MOSQ_ERR_AUTH; } HASH_ITER(hh, unpwd_ref, u, tmp){ if(!strcmp(u->username, username)){ if(u->password){ if(password){ #ifdef WITH_TLS rc = pw__digest(password, u->salt, u->salt_len, hash, &hash_len); if(rc == MOSQ_ERR_SUCCESS){ if(hash_len == u->password_len && !mosquitto__memcmp_const(u->password, hash, hash_len)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else{ return rc; } #else if(!strcmp(u->password, password)){ return MOSQ_ERR_SUCCESS; } #endif }else{ return MOSQ_ERR_AUTH; } }else{ return MOSQ_ERR_SUCCESS; } } } return MOSQ_ERR_AUTH; } static int unpwd__cleanup(struct mosquitto__unpwd **root, bool reload) { struct mosquitto__unpwd *u, *tmp; UNUSED(reload); if(!root) return MOSQ_ERR_INVAL; HASH_ITER(hh, *root, u, tmp){ HASH_DEL(*root, u); mosquitto__free(u->password); mosquitto__free(u->username); #ifdef WITH_TLS mosquitto__free(u->salt); #endif mosquitto__free(u); } *root = NULL; return MOSQ_ERR_SUCCESS; } #ifdef WITH_TLS static void security__disconnect_auth(struct mosquitto_db *db, struct mosquitto *context) { if(context->protocol == mosq_p_mqtt5){ send__disconnect(context, MQTT_RC_ADMINISTRATIVE_ACTION, NULL); } mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(db, context, MOSQ_ERR_AUTH); } #endif /* Apply security settings after a reload. * Includes: * - Disconnecting anonymous users if appropriate * - Disconnecting users with invalid passwords * - Reapplying ACLs */ int mosquitto_security_apply_default(struct mosquitto_db *db) { struct mosquitto *context, *ctxt_tmp; struct mosquitto__acl_user *acl_user_tail; bool allow_anonymous; struct mosquitto__security_options *security_opts = NULL; #ifdef WITH_TLS int i; X509 *client_cert = NULL; X509_NAME *name; X509_NAME_ENTRY *name_entry; ASN1_STRING *name_asn1 = NULL; struct mosquitto__listener *listener; #endif if(!db) return MOSQ_ERR_INVAL; #ifdef WITH_TLS for(i=0; iconfig->listener_count; i++){ listener = &db->config->listeners[i]; if(listener && listener->ssl_ctx && (listener->cafile || listener->capath) && listener->crlfile && listener->require_certificate){ if(net__tls_server_ctx(listener)){ return 1; } if(net__tls_load_verify(listener)){ return 1; } } } #endif HASH_ITER(hh_id, db->contexts_by_id, context, ctxt_tmp){ /* Check for anonymous clients when allow_anonymous is false */ if(db->config->per_listener_settings){ if(context->listener){ allow_anonymous = context->listener->security_options.allow_anonymous; }else{ /* Client not currently connected, so defer judgement until it does connect */ allow_anonymous = true; } }else{ allow_anonymous = db->config->security_options.allow_anonymous; } if(!allow_anonymous && !context->username){ mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(db, context, MOSQ_ERR_AUTH); continue; } /* Check for connected clients that are no longer authorised */ #ifdef WITH_TLS if(context->listener && context->listener->ssl_ctx && (context->listener->use_identity_as_username || context->listener->use_subject_as_username)){ /* Client must have either a valid certificate, or valid PSK used as a username. */ if(!context->ssl){ if(context->protocol == mosq_p_mqtt5){ send__disconnect(context, MQTT_RC_ADMINISTRATIVE_ACTION, NULL); } mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(db, context, MOSQ_ERR_AUTH); continue; } #ifdef FINAL_WITH_TLS_PSK if(context->listener->psk_hint){ /* Client should have provided an identity to get this far. */ if(!context->username){ security__disconnect_auth(db, context); continue; } }else #endif /* FINAL_WITH_TLS_PSK */ { /* Free existing credentials and then recover them. */ mosquitto__free(context->username); context->username = NULL; mosquitto__free(context->password); context->password = NULL; client_cert = SSL_get_peer_certificate(context->ssl); if(!client_cert){ security__disconnect_auth(db, context); continue; } name = X509_get_subject_name(client_cert); if(!name){ X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } if (context->listener->use_identity_as_username) { //use_identity_as_username i = X509_NAME_get_index_by_NID(name, NID_commonName, -1); if(i == -1){ X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } name_entry = X509_NAME_get_entry(name, i); if(name_entry){ name_asn1 = X509_NAME_ENTRY_get_data(name_entry); if (name_asn1 == NULL) { X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } #if OPENSSL_VERSION_NUMBER < 0x10100000L context->username = mosquitto__strdup((char *) ASN1_STRING_data(name_asn1)); #else context->username = mosquitto__strdup((char *) ASN1_STRING_get0_data(name_asn1)); #endif if(!context->username){ X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } /* Make sure there isn't an embedded NUL character in the CN */ if ((size_t)ASN1_STRING_length(name_asn1) != strlen(context->username)) { X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } } } else { // use_subject_as_username BIO *subject_bio = BIO_new(BIO_s_mem()); X509_NAME_print_ex(subject_bio, X509_get_subject_name(client_cert), 0, XN_FLAG_RFC2253); char *data_start = NULL; long name_length = BIO_get_mem_data(subject_bio, &data_start); char *subject = mosquitto__malloc(sizeof(char)*name_length+1); if(!subject){ BIO_free(subject_bio); X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } memcpy(subject, data_start, name_length); subject[name_length] = '\0'; BIO_free(subject_bio); context->username = subject; } if(!context->username){ X509_free(client_cert); client_cert = NULL; security__disconnect_auth(db, context); continue; } X509_free(client_cert); client_cert = NULL; } }else #endif { /* Username/password check only if the identity/subject check not used */ if(mosquitto_unpwd_check(db, context, context->username, context->password) != MOSQ_ERR_SUCCESS){ mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(db, context, MOSQ_ERR_AUTH); continue; } } /* Check for ACLs and apply to user. */ if(db->config->per_listener_settings){ if(context->listener){ security_opts = &context->listener->security_options; }else{ if(context->state != mosq_cs_active){ mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(db, context, MOSQ_ERR_AUTH); continue; } } }else{ security_opts = &db->config->security_options; } if(security_opts && security_opts->acl_list){ acl_user_tail = security_opts->acl_list; while(acl_user_tail){ if(acl_user_tail->username){ if(context->username){ if(!strcmp(acl_user_tail->username, context->username)){ context->acl_list = acl_user_tail; break; } } }else{ if(!context->username){ context->acl_list = acl_user_tail; break; } } acl_user_tail = acl_user_tail->next; } } } return MOSQ_ERR_SUCCESS; } int mosquitto_psk_key_get_default(struct mosquitto_db *db, struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len) { struct mosquitto__unpwd *u, *tmp; struct mosquitto__unpwd *psk_id_ref = NULL; if(!db || !hint || !identity || !key) return MOSQ_ERR_INVAL; if(db->config->per_listener_settings){ if(!context->listener) return MOSQ_ERR_INVAL; if(!context->listener->psk_id) return MOSQ_ERR_PLUGIN_DEFER; psk_id_ref = context->listener->psk_id; }else{ if(!db->psk_id) return MOSQ_ERR_PLUGIN_DEFER; psk_id_ref = db->psk_id; } if(!psk_id_ref) return MOSQ_ERR_PLUGIN_DEFER; HASH_ITER(hh, psk_id_ref, u, tmp){ if(!strcmp(u->username, identity)){ strncpy(key, u->password, max_key_len); return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_AUTH; } #ifdef WITH_TLS int pw__digest(const char *password, const unsigned char *salt, unsigned int salt_len, unsigned char *hash, unsigned int *hash_len) { const EVP_MD *digest; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_MD_CTX context; digest = EVP_get_digestbyname("sha512"); if(!digest){ // FIXME fprintf(stderr, "Error: Unable to create openssl digest.\n"); return 1; } EVP_MD_CTX_init(&context); EVP_DigestInit_ex(&context, digest, NULL); EVP_DigestUpdate(&context, password, strlen(password)); EVP_DigestUpdate(&context, salt, salt_len); /* hash is assumed to be EVP_MAX_MD_SIZE bytes long. */ EVP_DigestFinal_ex(&context, hash, hash_len); EVP_MD_CTX_cleanup(&context); #else EVP_MD_CTX *context; digest = EVP_get_digestbyname("sha512"); if(!digest){ // FIXME fprintf(stderr, "Error: Unable to create openssl digest.\n"); return 1; } context = EVP_MD_CTX_new(); EVP_DigestInit_ex(context, digest, NULL); EVP_DigestUpdate(context, password, strlen(password)); EVP_DigestUpdate(context, salt, salt_len); /* hash is assumed to be EVP_MAX_MD_SIZE bytes long. */ EVP_DigestFinal_ex(context, hash, hash_len); EVP_MD_CTX_free(context); #endif return MOSQ_ERR_SUCCESS; } int base64__decode(char *in, unsigned char **decoded, unsigned int *decoded_len) { BIO *bmem, *b64; int slen; slen = strlen(in); b64 = BIO_new(BIO_f_base64()); if(!b64){ return 1; } BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new(BIO_s_mem()); if(!bmem){ BIO_free_all(b64); return 1; } b64 = BIO_push(b64, bmem); BIO_write(bmem, in, slen); if(BIO_flush(bmem) != 1){ BIO_free_all(b64); return 1; } *decoded = mosquitto__calloc(slen, 1); if(!(*decoded)){ BIO_free_all(b64); return 1; } *decoded_len = BIO_read(b64, *decoded, slen); BIO_free_all(b64); if(*decoded_len <= 0){ mosquitto__free(*decoded); *decoded = NULL; *decoded_len = 0; return 1; } return 0; } #endif mosquitto-1.6.9/src/handle_subscribe.c0000664000175000017500000001315713626052637017063 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" int handle__subscribe(struct mosquitto_db *db, struct mosquitto *context) { int rc = 0; int rc2; uint16_t mid; char *sub; uint8_t subscription_options; uint32_t subscription_identifier = 0; uint8_t qos; uint8_t retain_handling = 0; uint8_t *payload = NULL, *tmp_payload; uint32_t payloadlen = 0; int len; int slen; char *sub_mount; mosquitto_property *properties = NULL; if(!context) return MOSQ_ERR_INVAL; if(context->state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received SUBSCRIBE from %s", context->id); if(context->protocol != mosq_p_mqtt31){ if((context->in_packet.command&0x0F) != 0x02){ return MOSQ_ERR_PROTOCOL; } } if(packet__read_uint16(&context->in_packet, &mid)) return 1; if(mid == 0) return MOSQ_ERR_PROTOCOL; if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_SUBSCRIBE, &context->in_packet, &properties); if(rc) return rc; if(mosquitto_property_read_varint(properties, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, &subscription_identifier, false)){ /* If the identifier was force set to 0, this is an error */ if(subscription_identifier == 0){ mosquitto_property_free_all(&properties); return MOSQ_ERR_PROTOCOL; } } mosquitto_property_free_all(&properties); /* Note - User Property not handled */ } while(context->in_packet.pos < context->in_packet.remaining_length){ sub = NULL; if(packet__read_string(&context->in_packet, &sub, &slen)){ mosquitto__free(payload); return 1; } if(sub){ if(!slen){ log__printf(NULL, MOSQ_LOG_INFO, "Empty subscription string from %s, disconnecting.", context->address); mosquitto__free(sub); mosquitto__free(payload); return 1; } if(mosquitto_sub_topic_check(sub)){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid subscription string from %s, disconnecting.", context->address); mosquitto__free(sub); mosquitto__free(payload); return 1; } if(packet__read_byte(&context->in_packet, &subscription_options)){ mosquitto__free(sub); mosquitto__free(payload); return 1; } if(context->protocol == mosq_p_mqtt31 || context->protocol == mosq_p_mqtt311){ qos = subscription_options; if(context->is_bridge){ subscription_options = MQTT_SUB_OPT_RETAIN_AS_PUBLISHED | MQTT_SUB_OPT_NO_LOCAL; } }else{ qos = subscription_options & 0x03; subscription_options &= 0xFC; retain_handling = (subscription_options & 0x30); if(retain_handling == 0x30 || (subscription_options & 0xC0) != 0){ return MOSQ_ERR_PROTOCOL; } } if(qos > 2){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid QoS in subscription command from %s, disconnecting.", context->address); mosquitto__free(sub); mosquitto__free(payload); return 1; } if(context->listener && context->listener->mount_point){ len = strlen(context->listener->mount_point) + slen + 1; sub_mount = mosquitto__malloc(len+1); if(!sub_mount){ mosquitto__free(sub); mosquitto__free(payload); return MOSQ_ERR_NOMEM; } snprintf(sub_mount, len, "%s%s", context->listener->mount_point, sub); sub_mount[len] = '\0'; mosquitto__free(sub); sub = sub_mount; } log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s (QoS %d)", sub, qos); if(context->protocol != mosq_p_mqtt31){ rc2 = mosquitto_acl_check(db, context, sub, 0, NULL, qos, false, MOSQ_ACL_SUBSCRIBE); switch(rc2){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_ACL_DENIED: qos = 0x80; break; default: mosquitto__free(sub); return rc2; } } if(qos != 0x80){ rc2 = sub__add(db, context, sub, qos, subscription_identifier, subscription_options, &db->subs); if(rc2 > 0){ mosquitto__free(sub); return rc2; } if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt31){ if(rc2 == MOSQ_ERR_SUCCESS || rc2 == MOSQ_ERR_SUB_EXISTS){ if(sub__retain_queue(db, context, sub, qos, 0)) rc = 1; } }else{ if((retain_handling == MQTT_SUB_OPT_SEND_RETAIN_ALWAYS) || (rc2 == MOSQ_ERR_SUCCESS && retain_handling == MQTT_SUB_OPT_SEND_RETAIN_NEW)){ if(sub__retain_queue(db, context, sub, qos, subscription_identifier)) rc = 1; } } log__printf(NULL, MOSQ_LOG_SUBSCRIBE, "%s %d %s", context->id, qos, sub); } mosquitto__free(sub); tmp_payload = mosquitto__realloc(payload, payloadlen + 1); if(tmp_payload){ payload = tmp_payload; payload[payloadlen] = qos; payloadlen++; }else{ mosquitto__free(payload); return MOSQ_ERR_NOMEM; } } } if(context->protocol != mosq_p_mqtt31){ if(payloadlen == 0){ /* No subscriptions specified, protocol error. */ return MOSQ_ERR_PROTOCOL; } } if(send__suback(context, mid, payloadlen, payload)) rc = 1; mosquitto__free(payload); #ifdef WITH_PERSISTENCE db->persistence_changes++; #endif return rc; } mosquitto-1.6.9/src/handle_connack.c0000664000175000017500000001160313626052637016510 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "send_mosq.h" #include "util_mosq.h" int handle__connack(struct mosquitto_db *db, struct mosquitto *context) { int rc; uint8_t connect_acknowledge; uint8_t reason_code; int i; char *notification_topic; int notification_topic_len; char notification_payload; mosquitto_property *properties = NULL; if(!context){ return MOSQ_ERR_INVAL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received CONNACK on connection %s.", context->id); if(packet__read_byte(&context->in_packet, &connect_acknowledge)) return 1; if(packet__read_byte(&context->in_packet, &reason_code)) return 1; if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_CONNACK, &context->in_packet, &properties); if(rc) return rc; mosquitto_property_free_all(&properties); } mosquitto_property_free_all(&properties); /* FIXME - TEMPORARY UNTIL PROPERTIES PROCESSED */ switch(reason_code){ case CONNACK_ACCEPTED: if(context->bridge){ if(context->bridge->notifications){ notification_payload = '1'; if(context->bridge->notification_topic){ if(!context->bridge->notifications_local_only){ if(send__real_publish(context, mosquitto__mid_generate(context), context->bridge->notification_topic, 1, ¬ification_payload, 1, true, 0, NULL, NULL, 0)){ return 1; } } db__messages_easy_queue(db, context, context->bridge->notification_topic, 1, 1, ¬ification_payload, 1, 0, NULL); }else{ notification_topic_len = strlen(context->bridge->remote_clientid)+strlen("$SYS/broker/connection//state"); notification_topic = mosquitto__malloc(sizeof(char)*(notification_topic_len+1)); if(!notification_topic) return MOSQ_ERR_NOMEM; snprintf(notification_topic, notification_topic_len+1, "$SYS/broker/connection/%s/state", context->bridge->remote_clientid); notification_payload = '1'; if(!context->bridge->notifications_local_only){ if(send__real_publish(context, mosquitto__mid_generate(context), notification_topic, 1, ¬ification_payload, 1, true, 0, NULL, NULL, 0)){ mosquitto__free(notification_topic); return 1; } } db__messages_easy_queue(db, context, notification_topic, 1, 1, ¬ification_payload, 1, 0, NULL); mosquitto__free(notification_topic); } } for(i=0; ibridge->topic_count; i++){ if(context->bridge->topics[i].direction == bd_in || context->bridge->topics[i].direction == bd_both){ if(send__subscribe(context, NULL, 1, &context->bridge->topics[i].remote_topic, context->bridge->topics[i].qos, NULL)){ return 1; } }else{ if(context->bridge->attempt_unsubscribe){ if(send__unsubscribe(context, NULL, 1, &context->bridge->topics[i].remote_topic, NULL)){ /* direction = inwards only. This means we should not be subscribed * to the topic. It is possible that we used to be subscribed to * this topic so unsubscribe. */ return 1; } } } } for(i=0; ibridge->topic_count; i++){ if(context->bridge->topics[i].direction == bd_out || context->bridge->topics[i].direction == bd_both){ sub__retain_queue(db, context, context->bridge->topics[i].local_topic, context->bridge->topics[i].qos, 0); } } } mosquitto__set_state(context, mosq_cs_active); return MOSQ_ERR_SUCCESS; case CONNACK_REFUSED_PROTOCOL_VERSION: if(context->bridge){ context->bridge->try_private_accepted = false; } log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: unacceptable protocol version"); return 1; case CONNACK_REFUSED_IDENTIFIER_REJECTED: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: identifier rejected"); return 1; case CONNACK_REFUSED_SERVER_UNAVAILABLE: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: broker unavailable"); return 1; case CONNACK_REFUSED_BAD_USERNAME_PASSWORD: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: broker unavailable"); return 1; case CONNACK_REFUSED_NOT_AUTHORIZED: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: not authorised"); return 1; default: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: unknown reason"); return 1; } return 1; } mosquitto-1.6.9/src/plugin_defer.c0000664000175000017500000000365313626052637016232 0ustar rogerroger/* Copyright (c) 2015-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ /* This is a skeleton authentication and access control plugin that simply defers all checks. */ #include #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, const struct mosquitto *client, struct mosquitto_acl_msg *msg) { printf("mosquitto_acl_check(u:%s)\n", mosquitto_client_username(client)); return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_unpwd_check(void *user_data, const struct mosquitto *client, const char *username, const char *password) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_psk_key_get(void *user_data, const struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_PLUGIN_DEFER; } mosquitto-1.6.9/src/handle_disconnect.c0000664000175000017500000000437113626052637017231 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "util_mosq.h" #include "will_mosq.h" int handle__disconnect(struct mosquitto_db *db, struct mosquitto *context) { int rc; uint8_t reason_code = 0; mosquitto_property *properties = NULL; if(!context){ return MOSQ_ERR_INVAL; } if(context->protocol == mosq_p_mqtt5 && context->in_packet.remaining_length > 0){ /* FIXME - must handle reason code */ rc = packet__read_byte(&context->in_packet, &reason_code); if(rc) return rc; if(context->in_packet.remaining_length > 1){ rc = property__read_all(CMD_DISCONNECT, &context->in_packet, &properties); if(rc) return rc; } } rc = property__process_disconnect(context, &properties); if(rc){ if(rc == MOSQ_ERR_PROTOCOL){ send__disconnect(context, MQTT_RC_PROTOCOL_ERROR, NULL); } mosquitto_property_free_all(&properties); return rc; } mosquitto_property_free_all(&properties); /* FIXME - TEMPORARY UNTIL PROPERTIES PROCESSED */ if(context->in_packet.pos != context->in_packet.remaining_length){ return MOSQ_ERR_PROTOCOL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received DISCONNECT from %s", context->id); if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ if((context->in_packet.command&0x0F) != 0x00){ do_disconnect(db, context, MOSQ_ERR_PROTOCOL); return MOSQ_ERR_PROTOCOL; } } if(reason_code == MQTT_RC_DISCONNECT_WITH_WILL_MSG){ mosquitto__set_state(context, mosq_cs_disconnect_with_will); }else{ will__clear(context); mosquitto__set_state(context, mosq_cs_disconnecting); } do_disconnect(db, context, MOSQ_ERR_SUCCESS); return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/src/session_expiry.c0000664000175000017500000000755513626052637016657 0ustar rogerroger/* Copyright (c) 2019-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "sys_tree.h" #include "time_mosq.h" static struct session_expiry_list *expiry_list = NULL; static time_t last_check = 0; static int session_expiry__cmp(struct session_expiry_list *i1, struct session_expiry_list *i2) { if(i1->context->session_expiry_time == i2->context->session_expiry_time){ return 0; }else if(i1->context->session_expiry_time > i2->context->session_expiry_time){ return 1; }else{ return -1; } } int session_expiry__add(struct mosquitto_db *db, struct mosquitto *context) { struct session_expiry_list *item; if(db->config->persistent_client_expiration == 0){ if(context->session_expiry_interval == UINT32_MAX){ /* There isn't a global expiry set, and the client has asked to * never expire, so we don't add it to the list. */ return MOSQ_ERR_SUCCESS; } } item = mosquitto__calloc(1, sizeof(struct session_expiry_list)); if(!item) return MOSQ_ERR_NOMEM; item->context = context; item->context->session_expiry_time = time(NULL); if(db->config->persistent_client_expiration == 0){ /* No global expiry, so use the client expiration interval */ item->context->session_expiry_time += item->context->session_expiry_interval; }else{ /* We have a global expiry interval */ if(db->config->persistent_client_expiration < item->context->session_expiry_interval){ /* The client expiry is longer than the global expiry, so use the global */ item->context->session_expiry_time += db->config->persistent_client_expiration; }else{ /* The global expiry is longer than the client expiry, so use the client */ item->context->session_expiry_time += item->context->session_expiry_interval; } } context->expiry_list_item = item; DL_INSERT_INORDER(expiry_list, item, session_expiry__cmp); return MOSQ_ERR_SUCCESS; } void session_expiry__remove(struct mosquitto *context) { if(context->expiry_list_item){ DL_DELETE(expiry_list, context->expiry_list_item); mosquitto__free(context->expiry_list_item); context->expiry_list_item = NULL; } } /* Call on broker shutdown only */ void session_expiry__remove_all(struct mosquitto_db *db) { struct session_expiry_list *item, *tmp; struct mosquitto *context; DL_FOREACH_SAFE(expiry_list, item, tmp){ context = item->context; session_expiry__remove(context); context->session_expiry_interval = 0; context->will_delay_interval = 0; will_delay__remove(context); context__disconnect(db, context); } } void session_expiry__check(struct mosquitto_db *db, time_t now) { struct session_expiry_list *item, *tmp; struct mosquitto *context; if(now <= last_check) return; last_check = now; DL_FOREACH_SAFE(expiry_list, item, tmp){ if(item->context->session_expiry_time < now){ context = item->context; session_expiry__remove(context); if(context->id){ log__printf(NULL, MOSQ_LOG_NOTICE, "Expiring client %s due to timeout.", context->id); } G_CLIENTS_EXPIRED_INC(); /* Session has now expired, so clear interval */ context->session_expiry_interval = 0; /* Session has expired, so will delay should be cleared. */ context->will_delay_interval = 0; will_delay__remove(context); context__send_will(db, context); context__add_to_disused(db, context); }else{ return; } } } mosquitto-1.6.9/src/context.c0000664000175000017500000001761113626052637015252 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "alias_mosq.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "time_mosq.h" #include "util_mosq.h" #include "will_mosq.h" #include "uthash.h" struct mosquitto *context__init(struct mosquitto_db *db, mosq_sock_t sock) { struct mosquitto *context; char address[1024]; context = mosquitto__calloc(1, sizeof(struct mosquitto)); if(!context) return NULL; context->pollfd_index = -1; mosquitto__set_state(context, mosq_cs_new); context->sock = sock; context->last_msg_in = mosquitto_time(); context->next_msg_out = mosquitto_time() + 60; context->keepalive = 60; /* Default to 60s */ context->clean_start = true; context->id = NULL; context->last_mid = 0; context->will = NULL; context->username = NULL; context->password = NULL; context->listener = NULL; context->acl_list = NULL; /* is_bridge records whether this client is a bridge or not. This could be * done by looking at context->bridge for bridges that we create ourself, * but incoming bridges need some other way of being recorded. */ context->is_bridge = false; context->in_packet.payload = NULL; packet__cleanup(&context->in_packet); context->out_packet = NULL; context->current_out_packet = NULL; context->address = NULL; if((int)sock >= 0){ if(!net__socket_get_address(sock, address, 1024)){ context->address = mosquitto__strdup(address); } if(!context->address){ /* getpeername and inet_ntop failed and not a bridge */ mosquitto__free(context); return NULL; } } context->bridge = NULL; context->msgs_in.inflight_maximum = db->config->max_inflight_messages; context->msgs_out.inflight_maximum = db->config->max_inflight_messages; context->msgs_in.inflight_quota = db->config->max_inflight_messages; context->msgs_out.inflight_quota = db->config->max_inflight_messages; context->maximum_qos = 2; #ifdef WITH_TLS context->ssl = NULL; #endif if((int)context->sock >= 0){ HASH_ADD(hh_sock, db->contexts_by_sock, sock, sizeof(context->sock), context); } return context; } /* * This will result in any outgoing packets going unsent. If we're disconnected * forcefully then it is usually an error condition and shouldn't be a problem, * but it will mean that CONNACK messages will never get sent for bad protocol * versions for example. */ void context__cleanup(struct mosquitto_db *db, struct mosquitto *context, bool do_free) { struct mosquitto__packet *packet; #ifdef WITH_BRIDGE int i; #endif if(!context) return; #ifdef WITH_BRIDGE if(context->bridge){ for(i=0; ibridge_count; i++){ if(db->bridges[i] == context){ db->bridges[i] = NULL; } } mosquitto__free(context->bridge->local_clientid); context->bridge->local_clientid = NULL; mosquitto__free(context->bridge->local_username); context->bridge->local_username = NULL; mosquitto__free(context->bridge->local_password); context->bridge->local_password = NULL; if(context->bridge->remote_clientid != context->id){ mosquitto__free(context->bridge->remote_clientid); } context->bridge->remote_clientid = NULL; if(context->bridge->remote_username != context->username){ mosquitto__free(context->bridge->remote_username); } context->bridge->remote_username = NULL; if(context->bridge->remote_password != context->password){ mosquitto__free(context->bridge->remote_password); } context->bridge->remote_password = NULL; } #endif alias__free_all(context); mosquitto__free(context->auth_method); context->auth_method = NULL; mosquitto__free(context->username); context->username = NULL; mosquitto__free(context->password); context->password = NULL; net__socket_close(db, context); if(do_free || context->clean_start){ sub__clean_session(db, context); db__messages_delete(db, context); } mosquitto__free(context->address); context->address = NULL; context__send_will(db, context); if(context->id){ context__remove_from_by_id(db, context); mosquitto__free(context->id); context->id = NULL; } packet__cleanup(&(context->in_packet)); if(context->current_out_packet){ packet__cleanup(context->current_out_packet); mosquitto__free(context->current_out_packet); context->current_out_packet = NULL; } while(context->out_packet){ packet__cleanup(context->out_packet); packet = context->out_packet; context->out_packet = context->out_packet->next; mosquitto__free(packet); } if(do_free || context->clean_start){ db__messages_delete(db, context); } #if defined(WITH_BROKER) && defined(__GLIBC__) && defined(WITH_ADNS) if(context->adns){ gai_cancel(context->adns); mosquitto__free((struct addrinfo *)context->adns->ar_request); mosquitto__free(context->adns); } #endif if(do_free){ mosquitto__free(context); } } void context__send_will(struct mosquitto_db *db, struct mosquitto *ctxt) { if(ctxt->state != mosq_cs_disconnecting && ctxt->will){ if(ctxt->will_delay_interval > 0){ will_delay__add(ctxt); return; } if(mosquitto_acl_check(db, ctxt, ctxt->will->msg.topic, ctxt->will->msg.payloadlen, ctxt->will->msg.payload, ctxt->will->msg.qos, ctxt->will->msg.retain, MOSQ_ACL_WRITE) == MOSQ_ERR_SUCCESS){ /* Unexpected disconnect, queue the client will. */ db__messages_easy_queue(db, ctxt, ctxt->will->msg.topic, ctxt->will->msg.qos, ctxt->will->msg.payloadlen, ctxt->will->msg.payload, ctxt->will->msg.retain, ctxt->will->expiry_interval, &ctxt->will->properties); } } will__clear(ctxt); } void context__disconnect(struct mosquitto_db *db, struct mosquitto *context) { net__socket_close(db, context); context__send_will(db, context); if(context->session_expiry_interval == 0){ /* Client session is due to be expired now */ #ifdef WITH_BRIDGE if(!context->bridge) #endif { if(context->will_delay_interval == 0){ /* This will be done later, after the will is published for delay>0. */ context__add_to_disused(db, context); } } }else{ session_expiry__add(db, context); } mosquitto__set_state(context, mosq_cs_disconnected); } void context__add_to_disused(struct mosquitto_db *db, struct mosquitto *context) { if(context->state == mosq_cs_disused) return; mosquitto__set_state(context, mosq_cs_disused); if(context->id){ context__remove_from_by_id(db, context); mosquitto__free(context->id); context->id = NULL; } if(db->ll_for_free){ context->for_free_next = db->ll_for_free; db->ll_for_free = context; }else{ db->ll_for_free = context; } } void context__free_disused(struct mosquitto_db *db) { struct mosquitto *context, *next; #ifdef WITH_WEBSOCKETS struct mosquitto *last = NULL; #endif assert(db); context = db->ll_for_free; while(context){ #ifdef WITH_WEBSOCKETS if(context->wsi){ /* Don't delete yet, lws hasn't finished with it */ if(last){ last->for_free_next = context; }else{ db->ll_for_free = context; } next = context->for_free_next; context->for_free_next = NULL; last = context; context = next; }else #endif { next = context->for_free_next; context__cleanup(db, context, true); context = next; } } db->ll_for_free = NULL; } void context__remove_from_by_id(struct mosquitto_db *db, struct mosquitto *context) { if(context->removed_from_by_id == false && context->id){ HASH_DELETE(hh_id, db->contexts_by_id, context); context->removed_from_by_id = true; } } mosquitto-1.6.9/src/CMakeLists.txt0000664000175000017500000001241513626052637016157 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/src ${mosquitto_SOURCE_DIR}/lib ${OPENSSL_INCLUDE_DIR} ${STDBOOL_H_PATH} ${STDINT_H_PATH}) set (MOSQ_SRCS ../lib/alias_mosq.c ../lib/alias_mosq.h conf.c conf_includedir.c context.c database.c handle_auth.c handle_connack.c handle_connect.c handle_disconnect.c ../lib/handle_ping.c ../lib/handle_pubackcomp.c handle_publish.c ../lib/handle_pubrec.c ../lib/handle_pubrel.c ../lib/handle_suback.c handle_subscribe.c ../lib/handle_unsuback.c handle_unsubscribe.c lib_load.h logging.c loop.c ../lib/memory_mosq.c ../lib/memory_mosq.h mosquitto.c mosquitto_broker.h mosquitto_broker_internal.h ../lib/misc_mosq.c ../lib/misc_mosq.h net.c ../lib/net_mosq_ocsp.c ../lib/net_mosq.c ../lib/net_mosq.h ../lib/packet_datatypes.c ../lib/packet_mosq.c ../lib/packet_mosq.h persist_read_v234.c persist_read_v5.c persist_read.c persist_write_v5.c persist_write.c persist.h plugin.c property_broker.c ../lib/property_mosq.c ../lib/property_mosq.h read_handle.c ../lib/read_handle.h security.c security_default.c ../lib/send_mosq.c ../lib/send_mosq.h send_auth.c send_connack.c ../lib/send_connect.c ../lib/send_disconnect.c ../lib/send_publish.c send_suback.c signals.c ../lib/send_subscribe.c send_unsuback.c ../lib/send_unsubscribe.c session_expiry.c subs.c sys_tree.c sys_tree.h ../lib/time_mosq.c ../lib/tls_mosq.c ../lib/util_mosq.c ../lib/util_topic.c ../lib/util_mosq.h ../lib/utf8_mosq.c websockets.c will_delay.c ../lib/will_mosq.c ../lib/will_mosq.h) option(WITH_BUNDLED_DEPS "Build with bundled dependencies?" ON) if (WITH_BUNDLED_DEPS) include_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/src/deps) endif (WITH_BUNDLED_DEPS) option(INC_BRIDGE_SUPPORT "Include bridge support for connecting to other brokers?" ON) if (INC_BRIDGE_SUPPORT) set (MOSQ_SRCS ${MOSQ_SRCS} bridge.c) add_definitions("-DWITH_BRIDGE") endif (INC_BRIDGE_SUPPORT) option(USE_LIBWRAP "Include tcp-wrappers support?" OFF) if (USE_LIBWRAP) set (MOSQ_LIBS ${MOSQ_LIBS} wrap) add_definitions("-DWITH_WRAP") endif (USE_LIBWRAP) option(INC_DB_UPGRADE "Include database upgrade support? (recommended)" ON) option(INC_MEMTRACK "Include memory tracking support?" ON) if (INC_MEMTRACK) add_definitions("-DWITH_MEMORY_TRACKING") endif (INC_MEMTRACK) option(WITH_PERSISTENCE "Include persistence support?" ON) if (WITH_PERSISTENCE) add_definitions("-DWITH_PERSISTENCE") endif (WITH_PERSISTENCE) option(WITH_SYS_TREE "Include $SYS tree support?" ON) if (WITH_SYS_TREE) add_definitions("-DWITH_SYS_TREE") endif (WITH_SYS_TREE) option(WITH_ADNS "Include ADNS support?" OFF) if (CMAKE_SYSTEM_NAME STREQUAL Linux) option(WITH_SYSTEMD "Include systemd support?" OFF) if (WITH_SYSTEMD) add_definitions("-DWITH_SYSTEMD") find_library(SYSTEMD_LIBRARY systemd) set (MOSQ_LIBS ${MOSQ_LIBS} ${SYSTEMD_LIBRARY}) endif (WITH_SYSTEMD) endif (CMAKE_SYSTEM_NAME STREQUAL Linux) option(WITH_WEBSOCKETS "Include websockets support?" OFF) option(STATIC_WEBSOCKETS "Use the static libwebsockets library?" OFF) if (WITH_WEBSOCKETS) add_definitions("-DWITH_WEBSOCKETS") endif (WITH_WEBSOCKETS) if (WIN32 OR CYGWIN) set (MOSQ_SRCS ${MOSQ_SRCS} service.c) endif (WIN32 OR CYGWIN) add_definitions (-DWITH_BROKER) if (WITH_DLT) message(STATUS "DLT_LIBDIR = ${DLT_LIBDIR}") link_directories(${DLT_LIBDIR}) set (MOSQ_LIBS ${MOSQ_LIBS} ${DLT_LIBRARIES}) endif (WITH_DLT) set (MOSQ_LIBS ${MOSQ_LIBS} ${OPENSSL_LIBRARIES}) # Check for getaddrinfo_a include(CheckLibraryExists) check_library_exists(anl getaddrinfo_a "" HAVE_GETADDRINFO_A) if (HAVE_GETADDRINFO_A AND WITH_ADNS) add_definitions("-DWITH_ADNS") add_definitions(-DHAVE_GETADDRINFO_A) set (MOSQ_LIBS ${MOSQ_LIBS} anl) endif (HAVE_GETADDRINFO_A AND WITH_ADNS) if (UNIX) if (APPLE) set (MOSQ_LIBS ${MOSQ_LIBS} dl m) elseif(QNX) set(MOSQ_LIBS ${MOSQ_LIBS} m socket) else(APPLE) set (MOSQ_LIBS ${MOSQ_LIBS} dl m) find_library(LIBRT rt) if (LIBRT) set (MOSQ_LIBS ${MOSQ_LIBS} rt) endif (LIBRT) endif (APPLE) endif (UNIX) if (WIN32) set (MOSQ_LIBS ${MOSQ_LIBS} ws2_32) endif (WIN32) if (WITH_WEBSOCKETS) if (STATIC_WEBSOCKETS) set (MOSQ_LIBS ${MOSQ_LIBS} websockets_static) if (WIN32) set (MOSQ_LIBS ${MOSQ_LIBS} iphlpapi) link_directories(${mosquitto_SOURCE_DIR}) endif (WIN32) else (STATIC_WEBSOCKETS) set (MOSQ_LIBS ${MOSQ_LIBS} websockets) endif (STATIC_WEBSOCKETS) endif (WITH_WEBSOCKETS) add_executable(mosquitto ${MOSQ_SRCS}) target_link_libraries(mosquitto ${MOSQ_LIBS}) if (UNIX) if (APPLE) set_target_properties(mosquitto PROPERTIES LINK_FLAGS "-Wl,-exported_symbols_list -Wl,${mosquitto_SOURCE_DIR}/src/linker-macosx.syms") else (APPLE) set_target_properties(mosquitto PROPERTIES LINK_FLAGS "-Wl,-dynamic-list=${mosquitto_SOURCE_DIR}/src/linker.syms") endif (APPLE) endif (UNIX) install(TARGETS mosquitto RUNTIME DESTINATION "${CMAKE_INSTALL_SBINDIR}") install(FILES mosquitto_broker.h mosquitto_plugin.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") if (WITH_TLS) add_executable(mosquitto_passwd mosquitto_passwd.c ../lib/misc_mosq.c) target_link_libraries(mosquitto_passwd ${OPENSSL_LIBRARIES}) install(TARGETS mosquitto_passwd RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") endif (WITH_TLS) mosquitto-1.6.9/src/handle_connect.c0000664000175000017500000006651513626052637016541 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "sys_tree.h" #include "time_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #include "will_mosq.h" #ifdef WITH_WEBSOCKETS # include #endif static char nibble_to_hex(uint8_t value) { if(value < 0x0A){ return '0'+value; }else{ return 'A'+value-0x0A; } } static char *client_id_gen(int *idlen, const char *auto_id_prefix, int auto_id_prefix_len) { char *client_id; uint8_t rnd[16]; int i; int pos; if(util__random_bytes(rnd, 16)) return NULL; *idlen = 36 + auto_id_prefix_len; client_id = (char *)mosquitto__calloc((*idlen) + 1, sizeof(char)); if(!client_id){ return NULL; } if(auto_id_prefix){ memcpy(client_id, auto_id_prefix, auto_id_prefix_len); } pos = 0; for(i=0; i<16; i++){ client_id[auto_id_prefix_len + pos + 0] = nibble_to_hex(rnd[i] & 0x0F); client_id[auto_id_prefix_len + pos + 1] = nibble_to_hex((rnd[i] >> 4) & 0x0F); pos += 2; if(pos == 8 || pos == 13 || pos == 18 || pos == 23){ client_id[auto_id_prefix_len + pos] = '-'; pos++; } } return client_id; } /* Remove any queued messages that are no longer allowed through ACL, * assuming a possible change of username. */ void connection_check_acl(struct mosquitto_db *db, struct mosquitto *context, struct mosquitto_client_msg **head) { struct mosquitto_client_msg *msg_tail, *tmp; DL_FOREACH_SAFE((*head), msg_tail, tmp){ if(msg_tail->direction == mosq_md_out){ if(mosquitto_acl_check(db, context, msg_tail->store->topic, msg_tail->store->payloadlen, UHPA_ACCESS(msg_tail->store->payload, msg_tail->store->payloadlen), msg_tail->store->qos, msg_tail->store->retain, MOSQ_ACL_READ) != MOSQ_ERR_SUCCESS){ DL_DELETE((*head), msg_tail); db__msg_store_ref_dec(db, &msg_tail->store); mosquitto_property_free_all(&msg_tail->properties); mosquitto__free(msg_tail); } } } } int connect__on_authorised(struct mosquitto_db *db, struct mosquitto *context, void *auth_data_out, uint16_t auth_data_out_len) { struct mosquitto *found_context; struct mosquitto__subleaf *leaf; mosquitto_property *connack_props = NULL; uint8_t connect_ack = 0; int i; int rc; /* Find if this client already has an entry. This must be done *after* any security checks. */ HASH_FIND(hh_id, db->contexts_by_id, context->id, strlen(context->id), found_context); if(found_context){ /* Found a matching client */ if(found_context->sock == INVALID_SOCKET){ /* Client is reconnecting after a disconnect */ /* FIXME - does anything need to be done here? */ }else{ /* Client is already connected, disconnect old version. This is * done in context__cleanup() below. */ if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_ERR, "Client %s already connected, closing old connection.", context->id); } } if(context->clean_start == false && found_context->session_expiry_interval > 0){ if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ connect_ack |= 0x01; } if(found_context->msgs_in.inflight || found_context->msgs_in.queued || found_context->msgs_out.inflight || found_context->msgs_out.queued){ memcpy(&context->msgs_in, &found_context->msgs_in, sizeof(struct mosquitto_msg_data)); memcpy(&context->msgs_out, &found_context->msgs_out, sizeof(struct mosquitto_msg_data)); memset(&found_context->msgs_in, 0, sizeof(struct mosquitto_msg_data)); memset(&found_context->msgs_out, 0, sizeof(struct mosquitto_msg_data)); db__message_reconnect_reset(db, context); } context->subs = found_context->subs; found_context->subs = NULL; context->sub_count = found_context->sub_count; found_context->sub_count = 0; context->last_mid = found_context->last_mid; for(i=0; isub_count; i++){ if(context->subs[i]){ leaf = context->subs[i]->subs; while(leaf){ if(leaf->context == found_context){ leaf->context = context; } leaf = leaf->next; } } } } if(context->clean_start == true){ sub__clean_session(db, found_context); } session_expiry__remove(found_context); will_delay__remove(found_context); will__clear(found_context); found_context->clean_start = true; found_context->session_expiry_interval = 0; mosquitto__set_state(found_context, mosq_cs_duplicate); do_disconnect(db, found_context, MOSQ_ERR_SUCCESS); } rc = acl__find_acls(db, context); if(rc){ free(auth_data_out); return rc; } if(db->config->connection_messages == true){ if(context->is_bridge){ if(context->username){ log__printf(NULL, MOSQ_LOG_NOTICE, "New bridge connected from %s as %s (p%d, c%d, k%d, u'%s').", context->address, context->id, context->protocol, context->clean_start, context->keepalive, context->username); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "New bridge connected from %s as %s (p%d, c%d, k%d).", context->address, context->id, context->protocol, context->clean_start, context->keepalive); } }else{ if(context->username){ log__printf(NULL, MOSQ_LOG_NOTICE, "New client connected from %s as %s (p%d, c%d, k%d, u'%s').", context->address, context->id, context->protocol, context->clean_start, context->keepalive, context->username); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "New client connected from %s as %s (p%d, c%d, k%d).", context->address, context->id, context->protocol, context->clean_start, context->keepalive); } } if(context->will) { log__printf(NULL, MOSQ_LOG_DEBUG, "Will message specified (%ld bytes) (r%d, q%d).", (long)context->will->msg.payloadlen, context->will->msg.retain, context->will->msg.qos); log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s", context->will->msg.topic); } else { log__printf(NULL, MOSQ_LOG_DEBUG, "No will message specified."); } } context->ping_t = 0; context->is_dropping = false; connection_check_acl(db, context, &context->msgs_in.inflight); connection_check_acl(db, context, &context->msgs_in.queued); connection_check_acl(db, context, &context->msgs_out.inflight); connection_check_acl(db, context, &context->msgs_out.queued); HASH_ADD_KEYPTR(hh_id, db->contexts_by_id, context->id, strlen(context->id), context); #ifdef WITH_PERSISTENCE if(!context->clean_start){ db->persistence_changes++; } #endif context->maximum_qos = context->listener->maximum_qos; if(context->protocol == mosq_p_mqtt5){ if(context->maximum_qos != 2){ if(mosquitto_property_add_byte(&connack_props, MQTT_PROP_MAXIMUM_QOS, context->maximum_qos)){ rc = MOSQ_ERR_NOMEM; goto error; } } if(context->listener->max_topic_alias > 0){ if(mosquitto_property_add_int16(&connack_props, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, context->listener->max_topic_alias)){ rc = MOSQ_ERR_NOMEM; goto error; } } if(context->keepalive > db->config->max_keepalive){ context->keepalive = db->config->max_keepalive; if(mosquitto_property_add_int16(&connack_props, MQTT_PROP_SERVER_KEEP_ALIVE, context->keepalive)){ rc = MOSQ_ERR_NOMEM; goto error; } } if(context->assigned_id){ if(mosquitto_property_add_string(&connack_props, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, context->id)){ rc = MOSQ_ERR_NOMEM; goto error; } } if(context->auth_method){ if(mosquitto_property_add_string(&connack_props, MQTT_PROP_AUTHENTICATION_METHOD, context->auth_method)){ rc = MOSQ_ERR_NOMEM; goto error; } if(auth_data_out && auth_data_out_len > 0){ if(mosquitto_property_add_binary(&connack_props, MQTT_PROP_AUTHENTICATION_DATA, auth_data_out, auth_data_out_len)){ rc = MOSQ_ERR_NOMEM; goto error; } } } } free(auth_data_out); mosquitto__set_state(context, mosq_cs_active); rc = send__connack(db, context, connect_ack, CONNACK_ACCEPTED, connack_props); mosquitto_property_free_all(&connack_props); return rc; error: free(auth_data_out); mosquitto_property_free_all(&connack_props); return rc; } static int will__read(struct mosquitto *context, struct mosquitto_message_all **will, uint8_t will_qos, int will_retain) { int rc = MOSQ_ERR_SUCCESS; int slen; struct mosquitto_message_all *will_struct = NULL; char *will_topic_mount = NULL; uint16_t payloadlen; mosquitto_property *properties = NULL; will_struct = mosquitto__calloc(1, sizeof(struct mosquitto_message_all)); if(!will_struct){ rc = MOSQ_ERR_NOMEM; goto error_cleanup; } if(context->protocol == PROTOCOL_VERSION_v5){ rc = property__read_all(CMD_WILL, &context->in_packet, &properties); if(rc) goto error_cleanup; rc = property__process_will(context, will_struct, &properties); mosquitto_property_free_all(&properties); if(rc) goto error_cleanup; } rc = packet__read_string(&context->in_packet, &will_struct->msg.topic, &slen); if(rc) goto error_cleanup; if(!slen){ rc = MOSQ_ERR_PROTOCOL; goto error_cleanup; } if(context->listener->mount_point){ slen = strlen(context->listener->mount_point) + strlen(will_struct->msg.topic) + 1; will_topic_mount = mosquitto__malloc(slen+1); if(!will_topic_mount){ rc = MOSQ_ERR_NOMEM; goto error_cleanup; } snprintf(will_topic_mount, slen, "%s%s", context->listener->mount_point, will_struct->msg.topic); will_topic_mount[slen] = '\0'; mosquitto__free(will_struct->msg.topic); will_struct->msg.topic = will_topic_mount; } rc = mosquitto_pub_topic_check(will_struct->msg.topic); if(rc) goto error_cleanup; rc = packet__read_uint16(&context->in_packet, &payloadlen); if(rc) goto error_cleanup; will_struct->msg.payloadlen = payloadlen; if(will_struct->msg.payloadlen > 0){ will_struct->msg.payload = mosquitto__malloc(will_struct->msg.payloadlen); if(!will_struct->msg.payload){ rc = MOSQ_ERR_NOMEM; goto error_cleanup; } rc = packet__read_bytes(&context->in_packet, will_struct->msg.payload, will_struct->msg.payloadlen); if(rc) goto error_cleanup; } will_struct->msg.qos = will_qos; will_struct->msg.retain = will_retain; *will = will_struct; return MOSQ_ERR_SUCCESS; error_cleanup: if(will_struct){ mosquitto__free(will_struct->msg.topic); mosquitto__free(will_struct->msg.payload); mosquitto_property_free_all(&will_struct->properties); mosquitto__free(will_struct); } return rc; } int handle__connect(struct mosquitto_db *db, struct mosquitto *context) { char protocol_name[7]; uint8_t protocol_version; uint8_t connect_flags; char *client_id = NULL; struct mosquitto_message_all *will_struct = NULL; uint8_t will, will_retain, will_qos, clean_start; uint8_t username_flag, password_flag; char *username = NULL, *password = NULL; int rc; int slen; uint16_t slen16; mosquitto_property *properties = NULL; void *auth_data = NULL; uint16_t auth_data_len = 0; void *auth_data_out = NULL; uint16_t auth_data_out_len = 0; #ifdef WITH_TLS int i; X509 *client_cert = NULL; X509_NAME *name; X509_NAME_ENTRY *name_entry; ASN1_STRING *name_asn1 = NULL; #endif G_CONNECTION_COUNT_INC(); if(!context->listener){ return MOSQ_ERR_INVAL; } /* Don't accept multiple CONNECT commands. */ if(context->state != mosq_cs_new){ log__printf(NULL, MOSQ_LOG_NOTICE, "Bad client %s sending multiple CONNECT messages.", context->id); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } /* Read protocol name as length then bytes rather than with read_string * because the length is fixed and we can check that. Removes the need * for another malloc as well. */ if(packet__read_uint16(&context->in_packet, &slen16)){ rc = 1; goto handle_connect_error; } slen = slen16; if(slen != 4 /* MQTT */ && slen != 6 /* MQIsdp */){ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } if(packet__read_bytes(&context->in_packet, protocol_name, slen)){ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } protocol_name[slen] = '\0'; if(packet__read_byte(&context->in_packet, &protocol_version)){ rc = 1; goto handle_connect_error; } if(!strcmp(protocol_name, PROTOCOL_NAME_v31)){ if((protocol_version&0x7F) != PROTOCOL_VERSION_v31){ if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid protocol version %d in CONNECT from %s.", protocol_version, context->address); } send__connack(db, context, 0, CONNACK_REFUSED_PROTOCOL_VERSION, NULL); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } context->protocol = mosq_p_mqtt31; if((protocol_version&0x80) == 0x80){ context->is_bridge = true; } }else if(!strcmp(protocol_name, PROTOCOL_NAME)){ if((protocol_version&0x7F) == PROTOCOL_VERSION_v311){ context->protocol = mosq_p_mqtt311; if((protocol_version&0x80) == 0x80){ context->is_bridge = true; } }else if((protocol_version&0x7F) == PROTOCOL_VERSION_v5){ context->protocol = mosq_p_mqtt5; }else{ if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid protocol version %d in CONNECT from %s.", protocol_version, context->address); } send__connack(db, context, 0, CONNACK_REFUSED_PROTOCOL_VERSION, NULL); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } if((context->in_packet.command&0x0F) != 0x00){ /* Reserved flags not set to 0, must disconnect. */ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } }else{ if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid protocol \"%s\" in CONNECT from %s.", protocol_name, context->address); } rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } if(packet__read_byte(&context->in_packet, &connect_flags)){ rc = 1; goto handle_connect_error; } if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ if((connect_flags & 0x01) != 0x00){ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } } clean_start = (connect_flags & 0x02) >> 1; /* session_expiry_interval will be overriden if the properties are read later */ if(clean_start == false && protocol_version != PROTOCOL_VERSION_v5){ /* v3* has clean_start == false mean the session never expires */ context->session_expiry_interval = UINT32_MAX; }else{ context->session_expiry_interval = 0; } will = connect_flags & 0x04; will_qos = (connect_flags & 0x18) >> 3; if(will_qos == 3){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid Will QoS in CONNECT from %s.", context->address); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } will_retain = ((connect_flags & 0x20) == 0x20); // Temporary hack because MSVC<1800 doesn't have stdbool.h. password_flag = connect_flags & 0x40; username_flag = connect_flags & 0x80; if(will && will_retain && db->config->retain_available == false){ if(protocol_version == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_RETAIN_NOT_SUPPORTED, NULL); } rc = 1; goto handle_connect_error; } if(packet__read_uint16(&context->in_packet, &(context->keepalive))){ rc = 1; goto handle_connect_error; } if(protocol_version == PROTOCOL_VERSION_v5){ rc = property__read_all(CMD_CONNECT, &context->in_packet, &properties); if(rc) goto handle_connect_error; } property__process_connect(context, &properties); if(mosquitto_property_read_string(properties, MQTT_PROP_AUTHENTICATION_METHOD, &context->auth_method, false)){ mosquitto_property_read_binary(properties, MQTT_PROP_AUTHENTICATION_DATA, &auth_data, &auth_data_len, false); } mosquitto_property_free_all(&properties); /* FIXME - TEMPORARY UNTIL PROPERTIES PROCESSED */ if(packet__read_string(&context->in_packet, &client_id, &slen)){ rc = 1; goto handle_connect_error; } if(slen == 0){ if(context->protocol == mosq_p_mqtt31){ send__connack(db, context, 0, CONNACK_REFUSED_IDENTIFIER_REJECTED, NULL); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; }else{ /* mqtt311/mqtt5 */ mosquitto__free(client_id); client_id = NULL; bool allow_zero_length_clientid; if(db->config->per_listener_settings){ allow_zero_length_clientid = context->listener->security_options.allow_zero_length_clientid; }else{ allow_zero_length_clientid = db->config->security_options.allow_zero_length_clientid; } if((context->protocol == mosq_p_mqtt311 && clean_start == 0) || allow_zero_length_clientid == false){ if(context->protocol == mosq_p_mqtt311){ send__connack(db, context, 0, CONNACK_REFUSED_IDENTIFIER_REJECTED, NULL); }else{ send__connack(db, context, 0, MQTT_RC_UNSPECIFIED, NULL); } rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; }else{ if(db->config->per_listener_settings){ client_id = client_id_gen(&slen, context->listener->security_options.auto_id_prefix, context->listener->security_options.auto_id_prefix_len); }else{ client_id = client_id_gen(&slen, db->config->security_options.auto_id_prefix, db->config->security_options.auto_id_prefix_len); } if(!client_id){ rc = MOSQ_ERR_NOMEM; goto handle_connect_error; } context->assigned_id = true; } } } /* clientid_prefixes check */ if(db->config->clientid_prefixes){ if(strncmp(db->config->clientid_prefixes, client_id, strlen(db->config->clientid_prefixes))){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = 1; goto handle_connect_error; } } if(will){ rc = will__read(context, &will_struct, will_qos, will_retain); if(rc) goto handle_connect_error; }else{ if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ if(will_qos != 0 || will_retain != 0){ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } } } if(username_flag){ rc = packet__read_string(&context->in_packet, &username, &slen); if(rc == MOSQ_ERR_NOMEM){ rc = MOSQ_ERR_NOMEM; goto handle_connect_error; }else if(rc != MOSQ_ERR_SUCCESS){ if(context->protocol == mosq_p_mqtt31){ /* Username flag given, but no username. Ignore. */ username_flag = 0; }else{ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } } }else{ if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt31){ if(password_flag){ /* username_flag == 0 && password_flag == 1 is forbidden */ log__printf(NULL, MOSQ_LOG_ERR, "Protocol error from %s: password without username, closing connection.", client_id); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } } } if(password_flag){ rc = packet__read_binary(&context->in_packet, (uint8_t **)&password, &slen); if(rc == MOSQ_ERR_NOMEM){ rc = MOSQ_ERR_NOMEM; goto handle_connect_error; }else if(rc == MOSQ_ERR_PROTOCOL){ if(context->protocol == mosq_p_mqtt31){ /* Password flag given, but no password. Ignore. */ }else{ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } } } if(context->in_packet.pos != context->in_packet.remaining_length){ /* Surplus data at end of packet, this must be an error. */ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } #ifdef WITH_TLS if(context->listener->ssl_ctx && (context->listener->use_identity_as_username || context->listener->use_subject_as_username)){ /* Don't need the username or password if provided */ mosquitto__free(username); username = NULL; mosquitto__free(password); password = NULL; if(!context->ssl){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } #ifdef FINAL_WITH_TLS_PSK if(context->listener->psk_hint){ /* Client should have provided an identity to get this far. */ if(!context->username){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } }else{ #endif /* FINAL_WITH_TLS_PSK */ client_cert = SSL_get_peer_certificate(context->ssl); if(!client_cert){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } name = X509_get_subject_name(client_cert); if(!name){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } if (context->listener->use_identity_as_username) { //use_identity_as_username i = X509_NAME_get_index_by_NID(name, NID_commonName, -1); if(i == -1){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } name_entry = X509_NAME_get_entry(name, i); if(name_entry){ name_asn1 = X509_NAME_ENTRY_get_data(name_entry); if (name_asn1 == NULL) { if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } #if OPENSSL_VERSION_NUMBER < 0x10100000L context->username = mosquitto__strdup((char *) ASN1_STRING_data(name_asn1)); #else context->username = mosquitto__strdup((char *) ASN1_STRING_get0_data(name_asn1)); #endif if(!context->username){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_SERVER_UNAVAILABLE, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_SERVER_UNAVAILABLE, NULL); } rc = MOSQ_ERR_NOMEM; goto handle_connect_error; } /* Make sure there isn't an embedded NUL character in the CN */ if ((size_t)ASN1_STRING_length(name_asn1) != strlen(context->username)) { if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = 1; goto handle_connect_error; } } } else { // use_subject_as_username BIO *subject_bio = BIO_new(BIO_s_mem()); X509_NAME_print_ex(subject_bio, X509_get_subject_name(client_cert), 0, XN_FLAG_RFC2253); char *data_start = NULL; long name_length = BIO_get_mem_data(subject_bio, &data_start); char *subject = mosquitto__malloc(sizeof(char)*name_length+1); if(!subject){ BIO_free(subject_bio); rc = MOSQ_ERR_NOMEM; goto handle_connect_error; } memcpy(subject, data_start, name_length); subject[name_length] = '\0'; BIO_free(subject_bio); context->username = subject; } if(!context->username){ rc = 1; goto handle_connect_error; } X509_free(client_cert); client_cert = NULL; #ifdef FINAL_WITH_TLS_PSK } #endif /* FINAL_WITH_TLS_PSK */ }else{ #endif /* WITH_TLS */ if(username_flag || password_flag){ /* FIXME - these ensure the mosquitto_client_id() and * mosquitto_client_username() functions work, but is hacky */ context->id = client_id; context->username = username; rc = mosquitto_unpwd_check(db, context, username, password); context->username = NULL; context->id = NULL; switch(rc){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_AUTH: if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } context__disconnect(db, context); rc = 1; goto handle_connect_error; break; default: context__disconnect(db, context); rc = 1; goto handle_connect_error; break; } context->username = username; context->password = password; username = NULL; /* Avoid free() in error: below. */ password = NULL; }else{ if((db->config->per_listener_settings && context->listener->security_options.allow_anonymous == false) || (!db->config->per_listener_settings && db->config->security_options.allow_anonymous == false)){ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = 1; goto handle_connect_error; } } #ifdef WITH_TLS } #endif if(context->listener->use_username_as_clientid){ if(context->username){ mosquitto__free(client_id); client_id = mosquitto__strdup(context->username); if(!client_id){ rc = MOSQ_ERR_NOMEM; goto handle_connect_error; } }else{ if(context->protocol == mosq_p_mqtt5){ send__connack(db, context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(db, context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = 1; goto handle_connect_error; } } context->clean_start = clean_start; context->id = client_id; context->will = will_struct; if(context->auth_method){ rc = mosquitto_security_auth_start(db, context, false, auth_data, auth_data_len, &auth_data_out, &auth_data_out_len); mosquitto__free(auth_data); if(rc == MOSQ_ERR_SUCCESS){ return connect__on_authorised(db, context, auth_data_out, auth_data_out_len); }else if(rc == MOSQ_ERR_AUTH_CONTINUE){ mosquitto__set_state(context, mosq_cs_authenticating); rc = send__auth(db, context, MQTT_RC_CONTINUE_AUTHENTICATION, auth_data_out, auth_data_out_len); free(auth_data_out); return rc; }else{ free(auth_data_out); will__clear(context); if(rc == MOSQ_ERR_AUTH){ send__connack(db, context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); mosquitto__free(context->id); context->id = NULL; return MOSQ_ERR_PROTOCOL; }else if(rc == MOSQ_ERR_NOT_SUPPORTED){ /* Client has requested extended authentication, but we don't support it. */ send__connack(db, context, 0, MQTT_RC_BAD_AUTHENTICATION_METHOD, NULL); mosquitto__free(context->id); context->id = NULL; return MOSQ_ERR_PROTOCOL; }else{ mosquitto__free(context->id); context->id = NULL; return rc; } } }else{ return connect__on_authorised(db, context, NULL, 0); } handle_connect_error: mosquitto__free(auth_data); mosquitto__free(client_id); mosquitto__free(username); mosquitto__free(password); if(will_struct){ mosquitto_property_free_all(&will_struct->properties); mosquitto__free(will_struct->msg.payload); mosquitto__free(will_struct->msg.topic); mosquitto__free(will_struct); } #ifdef WITH_TLS if(client_cert) X509_free(client_cert); #endif /* We return an error here which means the client is freed later on. */ return rc; } mosquitto-1.6.9/src/security.c0000664000175000017500000006307313626052637015440 0ustar rogerroger/* Copyright (c) 2011-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "mosquitto_plugin.h" #include "memory_mosq.h" #include "lib_load.h" typedef int (*FUNC_auth_plugin_version)(void); static int security__cleanup_single(struct mosquitto__security_options *opts, bool reload); void LIB_ERROR(void) { #ifdef WIN32 char *buf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING, NULL, GetLastError(), LANG_NEUTRAL, &buf, 0, NULL); log__printf(NULL, MOSQ_LOG_ERR, "Load error: %s", buf); LocalFree(buf); #else log__printf(NULL, MOSQ_LOG_ERR, "Load error: %s", dlerror()); #endif } int security__load_v2(struct mosquitto__auth_plugin *plugin, struct mosquitto_auth_opt *auth_options, int auth_option_count, void *lib) { int rc; if(!(plugin->plugin_init_v2 = (FUNC_auth_plugin_init_v2)LIB_SYM(lib, "mosquitto_auth_plugin_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_init()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->plugin_cleanup_v2 = (FUNC_auth_plugin_cleanup_v2)LIB_SYM(lib, "mosquitto_auth_plugin_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->security_init_v2 = (FUNC_auth_plugin_security_init_v2)LIB_SYM(lib, "mosquitto_auth_security_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_security_init()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->security_cleanup_v2 = (FUNC_auth_plugin_security_cleanup_v2)LIB_SYM(lib, "mosquitto_auth_security_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_security_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->acl_check_v2 = (FUNC_auth_plugin_acl_check_v2)LIB_SYM(lib, "mosquitto_auth_acl_check"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_acl_check()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->unpwd_check_v2 = (FUNC_auth_plugin_unpwd_check_v2)LIB_SYM(lib, "mosquitto_auth_unpwd_check"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_unpwd_check()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->psk_key_get_v2 = (FUNC_auth_plugin_psk_key_get_v2)LIB_SYM(lib, "mosquitto_auth_psk_key_get"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_psk_key_get()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } plugin->lib = lib; plugin->user_data = NULL; if(plugin->plugin_init_v2){ rc = plugin->plugin_init_v2(&plugin->user_data, auth_options, auth_option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Authentication plugin returned %d when initialising.", rc); return rc; } } return 0; } int security__load_v3(struct mosquitto__auth_plugin *plugin, struct mosquitto_opt *auth_options, int auth_option_count, void *lib) { int rc; if(!(plugin->plugin_init_v3 = (FUNC_auth_plugin_init_v3)LIB_SYM(lib, "mosquitto_auth_plugin_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_init()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->plugin_cleanup_v3 = (FUNC_auth_plugin_cleanup_v3)LIB_SYM(lib, "mosquitto_auth_plugin_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->security_init_v3 = (FUNC_auth_plugin_security_init_v3)LIB_SYM(lib, "mosquitto_auth_security_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_security_init()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->security_cleanup_v3 = (FUNC_auth_plugin_security_cleanup_v3)LIB_SYM(lib, "mosquitto_auth_security_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_security_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->acl_check_v3 = (FUNC_auth_plugin_acl_check_v3)LIB_SYM(lib, "mosquitto_auth_acl_check"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_acl_check()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->unpwd_check_v3 = (FUNC_auth_plugin_unpwd_check_v3)LIB_SYM(lib, "mosquitto_auth_unpwd_check"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_unpwd_check()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->psk_key_get_v3 = (FUNC_auth_plugin_psk_key_get_v3)LIB_SYM(lib, "mosquitto_auth_psk_key_get"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_psk_key_get()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } plugin->lib = lib; plugin->user_data = NULL; if(plugin->plugin_init_v3){ rc = plugin->plugin_init_v3(&plugin->user_data, auth_options, auth_option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Authentication plugin returned %d when initialising.", rc); return rc; } } return 0; } int security__load_v4(struct mosquitto__auth_plugin *plugin, struct mosquitto_opt *auth_options, int auth_option_count, void *lib) { int rc; if(!(plugin->plugin_init_v4 = (FUNC_auth_plugin_init_v4)LIB_SYM(lib, "mosquitto_auth_plugin_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_init()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->plugin_cleanup_v4 = (FUNC_auth_plugin_cleanup_v4)LIB_SYM(lib, "mosquitto_auth_plugin_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->security_init_v4 = (FUNC_auth_plugin_security_init_v4)LIB_SYM(lib, "mosquitto_auth_security_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_security_init()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->security_cleanup_v4 = (FUNC_auth_plugin_security_cleanup_v4)LIB_SYM(lib, "mosquitto_auth_security_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_security_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } if(!(plugin->acl_check_v4 = (FUNC_auth_plugin_acl_check_v4)LIB_SYM(lib, "mosquitto_auth_acl_check"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_acl_check()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } plugin->unpwd_check_v4 = (FUNC_auth_plugin_unpwd_check_v4)LIB_SYM(lib, "mosquitto_auth_unpwd_check"); if(plugin->unpwd_check_v4){ log__printf(NULL, MOSQ_LOG_INFO, " ├── Username/password checking enabled."); }else{ log__printf(NULL, MOSQ_LOG_INFO, " ├── Username/password checking not enabled."); } plugin->psk_key_get_v4 = (FUNC_auth_plugin_psk_key_get_v4)LIB_SYM(lib, "mosquitto_auth_psk_key_get"); if(plugin->psk_key_get_v4){ log__printf(NULL, MOSQ_LOG_INFO, " ├── TLS-PSK checking enabled."); }else{ log__printf(NULL, MOSQ_LOG_INFO, " ├── TLS-PSK checking not enabled."); } plugin->auth_start_v4 = (FUNC_auth_plugin_auth_start_v4)LIB_SYM(lib, "mosquitto_auth_start"); plugin->auth_continue_v4 = (FUNC_auth_plugin_auth_continue_v4)LIB_SYM(lib, "mosquitto_auth_continue"); if(plugin->auth_start_v4){ if(plugin->auth_continue_v4){ log__printf(NULL, MOSQ_LOG_INFO, " └── Extended authentication enabled."); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Plugin has missing mosquitto_auth_continue() function."); LIB_CLOSE(lib); return 1; } }else{ log__printf(NULL, MOSQ_LOG_INFO, " └── Extended authentication not enabled."); } plugin->lib = lib; plugin->user_data = NULL; if(plugin->plugin_init_v4){ rc = plugin->plugin_init_v4(&plugin->user_data, auth_options, auth_option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Authentication plugin returned %d when initialising.", rc); return rc; } } return 0; } static int security__module_init_single(struct mosquitto__security_options *opts) { void *lib; int (*plugin_version)(void) = NULL; int version; int i; int rc; if(opts->auth_plugin_config_count == 0){ return MOSQ_ERR_SUCCESS; } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].path){ memset(&opts->auth_plugin_configs[i].plugin, 0, sizeof(struct mosquitto__auth_plugin)); log__printf(NULL, MOSQ_LOG_INFO, "Loading plugin: %s", opts->auth_plugin_configs[i].path); lib = LIB_LOAD(opts->auth_plugin_configs[i].path); if(!lib){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin \"%s\".", opts->auth_plugin_configs[i].path); LIB_ERROR(); return 1; } opts->auth_plugin_configs[i].plugin.lib = NULL; if(!(plugin_version = (FUNC_auth_plugin_version)LIB_SYM(lib, "mosquitto_auth_plugin_version"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_version()."); LIB_ERROR(); LIB_CLOSE(lib); return 1; } version = plugin_version(); opts->auth_plugin_configs[i].plugin.version = version; if(version == 4){ rc = security__load_v4( &opts->auth_plugin_configs[i].plugin, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, lib); if(rc){ return rc; } }else if(version == 3){ rc = security__load_v3( &opts->auth_plugin_configs[i].plugin, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, lib); if(rc){ return rc; } }else if(version == 2){ rc = security__load_v2( &opts->auth_plugin_configs[i].plugin, (struct mosquitto_auth_opt *)opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, lib); if(rc){ return rc; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Incorrect auth plugin version (got %d, expected %d).", version, MOSQ_AUTH_PLUGIN_VERSION); LIB_ERROR(); LIB_CLOSE(lib); return 1; } } } return MOSQ_ERR_SUCCESS; } int mosquitto_security_module_init(struct mosquitto_db *db) { int rc = MOSQ_ERR_SUCCESS; int i; if(db->config->per_listener_settings){ for(i=0; iconfig->listener_count; i++){ rc = security__module_init_single(&db->config->listeners[i].security_options); if(rc) return rc; } }else{ rc = security__module_init_single(&db->config->security_options); } return rc; } static void security__module_cleanup_single(struct mosquitto__security_options *opts) { int i; for(i=0; iauth_plugin_config_count; i++){ /* Run plugin cleanup function */ if(opts->auth_plugin_configs[i].plugin.version == 4){ opts->auth_plugin_configs[i].plugin.plugin_cleanup_v4( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count); }else if(opts->auth_plugin_configs[i].plugin.version == 3){ opts->auth_plugin_configs[i].plugin.plugin_cleanup_v3( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count); }else if(opts->auth_plugin_configs[i].plugin.version == 2){ opts->auth_plugin_configs[i].plugin.plugin_cleanup_v2( opts->auth_plugin_configs[i].plugin.user_data, (struct mosquitto_auth_opt *)opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count); } if(opts->auth_plugin_configs[i].plugin.lib){ LIB_CLOSE(opts->auth_plugin_configs[i].plugin.lib); } memset(&opts->auth_plugin_configs[i].plugin, 0, sizeof(struct mosquitto__auth_plugin)); } } int mosquitto_security_module_cleanup(struct mosquitto_db *db) { int i; mosquitto_security_cleanup(db, false); security__module_cleanup_single(&db->config->security_options); for(i=0; iconfig->listener_count; i++){ security__module_cleanup_single(&db->config->listeners[i].security_options); } return MOSQ_ERR_SUCCESS; } static int security__init_single(struct mosquitto__security_options *opts, bool reload) { int i; int rc; for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.version == 4){ rc = opts->auth_plugin_configs[i].plugin.security_init_v4( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, reload); }else if(opts->auth_plugin_configs[i].plugin.version == 3){ rc = opts->auth_plugin_configs[i].plugin.security_init_v3( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, reload); }else if(opts->auth_plugin_configs[i].plugin.version == 2){ rc = opts->auth_plugin_configs[i].plugin.security_init_v2( opts->auth_plugin_configs[i].plugin.user_data, (struct mosquitto_auth_opt *)opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, reload); }else{ rc = MOSQ_ERR_INVAL; } if(rc != MOSQ_ERR_SUCCESS){ return rc; } } return MOSQ_ERR_SUCCESS; } int mosquitto_security_init(struct mosquitto_db *db, bool reload) { int i; int rc; if(db->config->per_listener_settings){ for(i=0; iconfig->listener_count; i++){ rc = security__init_single(&db->config->listeners[i].security_options, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } }else{ rc = security__init_single(&db->config->security_options, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } return mosquitto_security_init_default(db, reload); } /* Apply security settings after a reload. * Includes: * - Disconnecting anonymous users if appropriate * - Disconnecting users with invalid passwords * - Reapplying ACLs */ int mosquitto_security_apply(struct mosquitto_db *db) { return mosquitto_security_apply_default(db); } static int security__cleanup_single(struct mosquitto__security_options *opts, bool reload) { int i; int rc; for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.version == 4){ rc = opts->auth_plugin_configs[i].plugin.security_cleanup_v4( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, reload); }else if(opts->auth_plugin_configs[i].plugin.version == 3){ rc = opts->auth_plugin_configs[i].plugin.security_cleanup_v3( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, reload); }else if(opts->auth_plugin_configs[i].plugin.version == 2){ rc = opts->auth_plugin_configs[i].plugin.security_cleanup_v2( opts->auth_plugin_configs[i].plugin.user_data, (struct mosquitto_auth_opt *)opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count, reload); }else{ rc = MOSQ_ERR_INVAL; } if(rc != MOSQ_ERR_SUCCESS){ return rc; } } return MOSQ_ERR_SUCCESS; } int mosquitto_security_cleanup(struct mosquitto_db *db, bool reload) { int i; int rc; rc = security__cleanup_single(&db->config->security_options, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; for(i=0; iconfig->listener_count; i++){ rc = security__cleanup_single(&db->config->listeners[i].security_options, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } return mosquitto_security_cleanup_default(db, reload); } //int mosquitto_acl_check(struct mosquitto_db *db, struct mosquitto *context, const char *topic, int access) static int acl__check_single(struct mosquitto__auth_plugin_config *auth_plugin, struct mosquitto *context, struct mosquitto_acl_msg *msg, int access) { const char *username; const char *topic = msg->topic; username = mosquitto_client_username(context); if(auth_plugin->deny_special_chars == true){ /* Check whether the client id or username contains a +, # or / and if * so deny access. * * Do this check for every message regardless, we have to protect the * plugins against possible pattern based attacks. */ if(username && strpbrk(username, "+#")){ log__printf(NULL, MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous username \"%s\"", username); return MOSQ_ERR_ACL_DENIED; } if(context->id && strpbrk(context->id, "+#")){ log__printf(NULL, MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous client id \"%s\"", context->id); return MOSQ_ERR_ACL_DENIED; } } if(auth_plugin->plugin.version == 4){ return auth_plugin->plugin.acl_check_v4(auth_plugin->plugin.user_data, access, context, msg); }else if(auth_plugin->plugin.version == 3){ return auth_plugin->plugin.acl_check_v3(auth_plugin->plugin.user_data, access, context, msg); }else if(auth_plugin->plugin.version == 2){ if(access == MOSQ_ACL_SUBSCRIBE){ return MOSQ_ERR_SUCCESS; } return auth_plugin->plugin.acl_check_v2(auth_plugin->plugin.user_data, context->id, username, topic, access); }else{ return MOSQ_ERR_INVAL; } } static int acl__check_dollar(const char *topic, int access) { int rc; bool match = false; if(topic[0] != '$') return MOSQ_ERR_SUCCESS; if(!strncmp(topic, "$SYS", 4)){ if(access == MOSQ_ACL_WRITE){ /* Potentially allow write access for bridge status, otherwise explicitly deny. */ rc = mosquitto_topic_matches_sub("$SYS/broker/connection/+/state", topic, &match); if(rc == MOSQ_ERR_SUCCESS && match == true){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } }else{ return MOSQ_ERR_SUCCESS; } }else if(!strncmp(topic, "$share", 6)){ /* Only allow sub/unsub to shared subscriptions */ if(access == MOSQ_ACL_SUBSCRIBE){ //FIXME if(access == MOSQ_ACL_SUBSCRIBE || access == MOSQ_ACL_UNSUBSCRIBE){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } }else{ /* This is an unknown $ topic, for the moment just defer to actual tests. */ return MOSQ_ERR_SUCCESS; } } int mosquitto_acl_check(struct mosquitto_db *db, struct mosquitto *context, const char *topic, long payloadlen, void* payload, int qos, bool retain, int access) { int rc; int i; struct mosquitto__security_options *opts; struct mosquitto_acl_msg msg; if(!context->id){ return MOSQ_ERR_ACL_DENIED; } rc = acl__check_dollar(topic, access); if(rc) return rc; rc = mosquitto_acl_check_default(db, context, topic, access); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } /* Default check has accepted or deferred at this point. * If no plugins exist we should accept at this point so set rc to success. */ rc = MOSQ_ERR_SUCCESS; if(db->config->per_listener_settings){ opts = &context->listener->security_options; }else{ opts = &db->config->security_options; } memset(&msg, 0, sizeof(msg)); msg.topic = topic; msg.payloadlen = payloadlen; msg.payload = payload; msg.qos = qos; msg.retain = retain; for(i=0; iauth_plugin_config_count; i++){ rc = acl__check_single(&opts->auth_plugin_configs[i], context, &msg, access); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } } /* If all plugins deferred, this is a denial. If rc == MOSQ_ERR_SUCCESS * here, then no plugins were configured. */ if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc = MOSQ_ERR_ACL_DENIED; } return rc; } int mosquitto_unpwd_check(struct mosquitto_db *db, struct mosquitto *context, const char *username, const char *password) { int rc; int i; struct mosquitto__security_options *opts; rc = mosquitto_unpwd_check_default(db, context, username, password); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } /* Default check has accepted or deferred at this point. * If no plugins exist we should accept at this point so set rc to success. */ if(db->config->per_listener_settings){ opts = &context->listener->security_options; }else{ opts = &db->config->security_options; } rc = MOSQ_ERR_SUCCESS; for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.version == 4 && opts->auth_plugin_configs[i].plugin.unpwd_check_v4){ rc = opts->auth_plugin_configs[i].plugin.unpwd_check_v4( opts->auth_plugin_configs[i].plugin.user_data, context, username, password); }else if(opts->auth_plugin_configs[i].plugin.version == 3){ rc = opts->auth_plugin_configs[i].plugin.unpwd_check_v3( opts->auth_plugin_configs[i].plugin.user_data, context, username, password); }else if(opts->auth_plugin_configs[i].plugin.version == 2){ rc = opts->auth_plugin_configs[i].plugin.unpwd_check_v2( opts->auth_plugin_configs[i].plugin.user_data, username, password); }else{ rc = MOSQ_ERR_INVAL; } if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } } /* If all plugins deferred, this is a denial. If rc == MOSQ_ERR_SUCCESS * here, then no plugins were configured. */ if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc = MOSQ_ERR_AUTH; } return rc; } int mosquitto_psk_key_get(struct mosquitto_db *db, struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len) { int rc; int i; struct mosquitto__security_options *opts; rc = mosquitto_psk_key_get_default(db, context, hint, identity, key, max_key_len); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } /* Default check has accepted or deferred at this point. * If no plugins exist we should accept at this point so set rc to success. */ if(db->config->per_listener_settings){ opts = &context->listener->security_options; }else{ opts = &db->config->security_options; } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.version == 4 && opts->auth_plugin_configs[i].plugin.psk_key_get_v4){ rc = opts->auth_plugin_configs[i].plugin.psk_key_get_v4( opts->auth_plugin_configs[i].plugin.user_data, context, hint, identity, key, max_key_len); }else if(opts->auth_plugin_configs[i].plugin.version == 3){ rc = opts->auth_plugin_configs[i].plugin.psk_key_get_v3( opts->auth_plugin_configs[i].plugin.user_data, context, hint, identity, key, max_key_len); }else if(opts->auth_plugin_configs[i].plugin.version == 2){ rc = opts->auth_plugin_configs[i].plugin.psk_key_get_v2( opts->auth_plugin_configs[i].plugin.user_data, hint, identity, key, max_key_len); }else{ rc = MOSQ_ERR_INVAL; } if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } } /* If all plugins deferred, this is a denial. If rc == MOSQ_ERR_SUCCESS * here, then no plugins were configured. */ if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc = MOSQ_ERR_AUTH; } return rc; } int mosquitto_security_auth_start(struct mosquitto_db *db, struct mosquitto *context, bool reauth, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len) { int rc = MOSQ_ERR_PLUGIN_DEFER; int i; struct mosquitto__security_options *opts; if(!context || !context->listener || !context->auth_method) return MOSQ_ERR_INVAL; if(!data_out || !data_out_len) return MOSQ_ERR_INVAL; if(db->config->per_listener_settings){ opts = &context->listener->security_options; }else{ opts = &db->config->security_options; } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.auth_start_v4){ *data_out = NULL; *data_out_len = 0; rc = opts->auth_plugin_configs[i].plugin.auth_start_v4( opts->auth_plugin_configs[i].plugin.user_data, context, context->auth_method, reauth, data_in, data_in_len, data_out, data_out_len); if(rc == MOSQ_ERR_SUCCESS){ return MOSQ_ERR_SUCCESS; }else if(rc == MOSQ_ERR_AUTH_CONTINUE){ return MOSQ_ERR_AUTH_CONTINUE; }else if(rc != MOSQ_ERR_NOT_SUPPORTED){ return rc; } } } return MOSQ_ERR_NOT_SUPPORTED; } int mosquitto_security_auth_continue(struct mosquitto_db *db, struct mosquitto *context, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len) { int rc = MOSQ_ERR_PLUGIN_DEFER; int i; struct mosquitto__security_options *opts; if(!context || !context->listener || !context->auth_method) return MOSQ_ERR_INVAL; if(!data_out || !data_out_len) return MOSQ_ERR_INVAL; if(db->config->per_listener_settings){ opts = &context->listener->security_options; }else{ opts = &db->config->security_options; } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.auth_start_v4){ *data_out = NULL; *data_out_len = 0; rc = opts->auth_plugin_configs[i].plugin.auth_continue_v4( opts->auth_plugin_configs[i].plugin.user_data, context, context->auth_method, data_in, data_in_len, data_out, data_out_len); if(rc == MOSQ_ERR_SUCCESS){ return MOSQ_ERR_SUCCESS; }else if(rc == MOSQ_ERR_AUTH_CONTINUE){ return MOSQ_ERR_AUTH_CONTINUE; }else if(rc != MOSQ_ERR_NOT_SUPPORTED){ return rc; } } } return MOSQ_ERR_NOT_SUPPORTED; } mosquitto-1.6.9/src/database.c0000664000175000017500000007207313626052637015335 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "send_mosq.h" #include "sys_tree.h" #include "time_mosq.h" #include "util_mosq.h" static unsigned long max_inflight_bytes = 0; static int max_queued = 100; static unsigned long max_queued_bytes = 0; /** * Is this context ready to take more in flight messages right now? * @param context the client context of interest * @param qos qos for the packet of interest * @return true if more in flight are allowed. */ static bool db__ready_for_flight(struct mosquitto_msg_data *msgs, int qos) { bool valid_bytes; bool valid_count; if(qos == 0 || (msgs->inflight_maximum == 0 && max_inflight_bytes == 0)){ return true; } valid_bytes = msgs->msg_bytes12 < max_inflight_bytes; valid_count = msgs->inflight_quota > 0; if(msgs->inflight_maximum == 0){ return valid_bytes; } if(max_inflight_bytes == 0){ return valid_count; } return valid_bytes && valid_count; } /** * For a given client context, are more messages allowed to be queued? * It is assumed that inflight checks and queue_qos0 checks have already * been made. * @param context client of interest * @param qos destination qos for the packet of interest * @return true if queuing is allowed, false if should be dropped */ static bool db__ready_for_queue(struct mosquitto *context, int qos, struct mosquitto_msg_data *msg_data) { int source_count; int adjust_count; unsigned long source_bytes; unsigned long adjust_bytes = max_inflight_bytes; if(max_queued == 0 && max_queued_bytes == 0){ return true; } if(qos == 0){ source_bytes = msg_data->msg_bytes; source_count = msg_data->msg_count; }else{ source_bytes = msg_data->msg_bytes12; source_count = msg_data->msg_count12; } adjust_count = msg_data->inflight_maximum; /* nothing in flight for offline clients */ if(context->sock == INVALID_SOCKET){ adjust_bytes = 0; adjust_count = 0; } bool valid_bytes = source_bytes - adjust_bytes < max_queued_bytes; bool valid_count = source_count - adjust_count < max_queued; if(max_queued_bytes == 0){ return valid_count; } if(max_queued == 0){ return valid_bytes; } return valid_bytes && valid_count; } int db__open(struct mosquitto__config *config, struct mosquitto_db *db) { struct mosquitto__subhier *subhier; if(!config || !db) return MOSQ_ERR_INVAL; db->last_db_id = 0; db->contexts_by_id = NULL; db->contexts_by_sock = NULL; db->contexts_for_free = NULL; #ifdef WITH_BRIDGE db->bridges = NULL; db->bridge_count = 0; #endif // Initialize the hashtable db->clientid_index_hash = NULL; db->subs = NULL; subhier = sub__add_hier_entry(NULL, &db->subs, "", strlen("")); if(!subhier) return MOSQ_ERR_NOMEM; subhier = sub__add_hier_entry(NULL, &db->subs, "$SYS", strlen("$SYS")); if(!subhier) return MOSQ_ERR_NOMEM; db->unpwd = NULL; #ifdef WITH_PERSISTENCE if(persist__restore(db)) return 1; #endif return MOSQ_ERR_SUCCESS; } static void subhier_clean(struct mosquitto_db *db, struct mosquitto__subhier **subhier) { struct mosquitto__subhier *peer, *subhier_tmp; struct mosquitto__subleaf *leaf, *nextleaf; HASH_ITER(hh, *subhier, peer, subhier_tmp){ leaf = peer->subs; while(leaf){ nextleaf = leaf->next; mosquitto__free(leaf); leaf = nextleaf; } if(peer->retained){ db__msg_store_ref_dec(db, &peer->retained); } subhier_clean(db, &peer->children); mosquitto__free(peer->topic); HASH_DELETE(hh, *subhier, peer); mosquitto__free(peer); } } int db__close(struct mosquitto_db *db) { subhier_clean(db, &db->subs); db__msg_store_clean(db); return MOSQ_ERR_SUCCESS; } void db__msg_store_add(struct mosquitto_db *db, struct mosquitto_msg_store *store) { store->next = db->msg_store; store->prev = NULL; if(db->msg_store){ db->msg_store->prev = store; } db->msg_store = store; } void db__msg_store_remove(struct mosquitto_db *db, struct mosquitto_msg_store *store) { int i; if(store->prev){ store->prev->next = store->next; if(store->next){ store->next->prev = store->prev; } }else{ db->msg_store = store->next; if(store->next){ store->next->prev = NULL; } } db->msg_store_count--; db->msg_store_bytes -= store->payloadlen; mosquitto__free(store->source_id); mosquitto__free(store->source_username); if(store->dest_ids){ for(i=0; idest_id_count; i++){ mosquitto__free(store->dest_ids[i]); } mosquitto__free(store->dest_ids); } mosquitto__free(store->topic); mosquitto_property_free_all(&store->properties); UHPA_FREE_PAYLOAD(store); mosquitto__free(store); } void db__msg_store_clean(struct mosquitto_db *db) { struct mosquitto_msg_store *store, *next;; store = db->msg_store; while(store){ next = store->next; db__msg_store_remove(db, store); store = next; } } void db__msg_store_ref_inc(struct mosquitto_msg_store *store) { store->ref_count++; } void db__msg_store_ref_dec(struct mosquitto_db *db, struct mosquitto_msg_store **store) { (*store)->ref_count--; if((*store)->ref_count == 0){ db__msg_store_remove(db, *store); *store = NULL; } } void db__msg_store_compact(struct mosquitto_db *db) { struct mosquitto_msg_store *store, *next; store = db->msg_store; while(store){ next = store->next; if(store->ref_count < 1){ db__msg_store_remove(db, store); } store = next; } } static void db__message_remove(struct mosquitto_db *db, struct mosquitto_msg_data *msg_data, struct mosquitto_client_msg *item) { if(!msg_data || !item){ return; } DL_DELETE(msg_data->inflight, item); if(item->store){ msg_data->msg_count--; msg_data->msg_bytes -= item->store->payloadlen; if(item->qos > 0){ msg_data->msg_count12--; msg_data->msg_bytes12 -= item->store->payloadlen; } db__msg_store_ref_dec(db, &item->store); } mosquitto_property_free_all(&item->properties); mosquitto__free(item); } void db__message_dequeue_first(struct mosquitto *context, struct mosquitto_msg_data *msg_data) { struct mosquitto_client_msg *msg; msg = msg_data->queued; DL_DELETE(msg_data->queued, msg); DL_APPEND(msg_data->inflight, msg); if(msg_data->inflight_quota > 0){ msg_data->inflight_quota--; } } int db__message_delete_outgoing(struct mosquitto_db *db, struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state expect_state, int qos) { struct mosquitto_client_msg *tail, *tmp; int msg_index = 0; if(!context) return MOSQ_ERR_INVAL; DL_FOREACH_SAFE(context->msgs_out.inflight, tail, tmp){ msg_index++; if(tail->mid == mid){ if(tail->qos != qos){ return MOSQ_ERR_PROTOCOL; }else if(qos == 2 && tail->state != expect_state){ return MOSQ_ERR_PROTOCOL; } msg_index--; db__message_remove(db, &context->msgs_out, tail); } } DL_FOREACH_SAFE(context->msgs_out.queued, tail, tmp){ if(context->msgs_out.inflight_maximum != 0 && msg_index >= context->msgs_out.inflight_maximum){ break; } msg_index++; tail->timestamp = mosquitto_time(); switch(tail->qos){ case 0: tail->state = mosq_ms_publish_qos0; break; case 1: tail->state = mosq_ms_publish_qos1; break; case 2: tail->state = mosq_ms_publish_qos2; break; } db__message_dequeue_first(context, &context->msgs_out); } return MOSQ_ERR_SUCCESS; } int db__message_insert(struct mosquitto_db *db, struct mosquitto *context, uint16_t mid, enum mosquitto_msg_direction dir, int qos, bool retain, struct mosquitto_msg_store *stored, mosquitto_property *properties) { struct mosquitto_client_msg *msg; struct mosquitto_msg_data *msg_data; enum mosquitto_msg_state state = mosq_ms_invalid; int rc = 0; int i; char **dest_ids; assert(stored); if(!context) return MOSQ_ERR_INVAL; if(!context->id) return MOSQ_ERR_SUCCESS; /* Protect against unlikely "client is disconnected but not entirely freed" scenario */ if(dir == mosq_md_out){ msg_data = &context->msgs_out; }else{ msg_data = &context->msgs_in; } /* Check whether we've already sent this message to this client * for outgoing messages only. * If retain==true then this is a stale retained message and so should be * sent regardless. FIXME - this does mean retained messages will received * multiple times for overlapping subscriptions, although this is only the * case for SUBSCRIPTION with multiple subs in so is a minor concern. */ if(context->protocol != mosq_p_mqtt5 && db->config->allow_duplicate_messages == false && dir == mosq_md_out && retain == false && stored->dest_ids){ for(i=0; idest_id_count; i++){ if(!strcmp(stored->dest_ids[i], context->id)){ /* We have already sent this message to this client. */ mosquitto_property_free_all(&properties); return MOSQ_ERR_SUCCESS; } } } if(context->sock == INVALID_SOCKET){ /* Client is not connected only queue messages with QoS>0. */ if(qos == 0 && !db->config->queue_qos0_messages){ if(!context->bridge){ mosquitto_property_free_all(&properties); return 2; }else{ if(context->bridge->start_type != bst_lazy){ mosquitto_property_free_all(&properties); return 2; } } } } if(context->sock != INVALID_SOCKET){ if(db__ready_for_flight(msg_data, qos)){ if(dir == mosq_md_out){ switch(qos){ case 0: state = mosq_ms_publish_qos0; break; case 1: state = mosq_ms_publish_qos1; break; case 2: state = mosq_ms_publish_qos2; break; } }else{ if(qos == 2){ state = mosq_ms_wait_for_pubrel; }else{ mosquitto_property_free_all(&properties); return 1; } } }else if(db__ready_for_queue(context, qos, msg_data)){ state = mosq_ms_queued; rc = 2; }else{ /* Dropping message due to full queue. */ if(context->is_dropping == false){ context->is_dropping = true; log__printf(NULL, MOSQ_LOG_NOTICE, "Outgoing messages are being dropped for client %s.", context->id); } G_MSGS_DROPPED_INC(); mosquitto_property_free_all(&properties); return 2; } }else{ if (db__ready_for_queue(context, qos, msg_data)){ state = mosq_ms_queued; }else{ G_MSGS_DROPPED_INC(); if(context->is_dropping == false){ context->is_dropping = true; log__printf(NULL, MOSQ_LOG_NOTICE, "Outgoing messages are being dropped for client %s.", context->id); } mosquitto_property_free_all(&properties); return 2; } } assert(state != mosq_ms_invalid); #ifdef WITH_PERSISTENCE if(state == mosq_ms_queued){ db->persistence_changes++; } #endif msg = mosquitto__malloc(sizeof(struct mosquitto_client_msg)); if(!msg) return MOSQ_ERR_NOMEM; msg->prev = NULL; msg->next = NULL; msg->store = stored; db__msg_store_ref_inc(msg->store); msg->mid = mid; msg->timestamp = mosquitto_time(); msg->direction = dir; msg->state = state; msg->dup = false; if(qos > context->maximum_qos){ msg->qos = context->maximum_qos; }else{ msg->qos = qos; } msg->retain = retain; msg->properties = properties; if(state == mosq_ms_queued){ DL_APPEND(msg_data->queued, msg); }else{ DL_APPEND(msg_data->inflight, msg); } msg_data->msg_count++; msg_data->msg_bytes+= msg->store->payloadlen; if(qos > 0){ msg_data->msg_count12++; msg_data->msg_bytes12 += msg->store->payloadlen; } if(db->config->allow_duplicate_messages == false && dir == mosq_md_out && retain == false){ /* Record which client ids this message has been sent to so we can avoid duplicates. * Outgoing messages only. * If retain==true then this is a stale retained message and so should be * sent regardless. FIXME - this does mean retained messages will received * multiple times for overlapping subscriptions, although this is only the * case for SUBSCRIPTION with multiple subs in so is a minor concern. */ dest_ids = mosquitto__realloc(stored->dest_ids, sizeof(char *)*(stored->dest_id_count+1)); if(dest_ids){ stored->dest_ids = dest_ids; stored->dest_id_count++; stored->dest_ids[stored->dest_id_count-1] = mosquitto__strdup(context->id); if(!stored->dest_ids[stored->dest_id_count-1]){ return MOSQ_ERR_NOMEM; } }else{ return MOSQ_ERR_NOMEM; } } #ifdef WITH_BRIDGE if(context->bridge && context->bridge->start_type == bst_lazy && context->sock == INVALID_SOCKET && context->msgs_out.msg_count >= context->bridge->threshold){ context->bridge->lazy_reconnect = true; } #endif if(dir == mosq_md_out && msg->qos > 0){ util__decrement_send_quota(context); } #ifdef WITH_WEBSOCKETS if(context->wsi && rc == 0){ return db__message_write(db, context); }else{ return rc; } #else return rc; #endif } int db__message_update_outgoing(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state state, int qos) { struct mosquitto_client_msg *tail; DL_FOREACH(context->msgs_out.inflight, tail){ if(tail->mid == mid){ if(tail->qos != qos){ return MOSQ_ERR_PROTOCOL; } tail->state = state; tail->timestamp = mosquitto_time(); return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_NOT_FOUND; } void db__messages_delete_list(struct mosquitto_db *db, struct mosquitto_client_msg **head) { struct mosquitto_client_msg *tail, *tmp; DL_FOREACH_SAFE(*head, tail, tmp){ DL_DELETE(*head, tail); db__msg_store_ref_dec(db, &tail->store); mosquitto_property_free_all(&tail->properties); mosquitto__free(tail); } *head = NULL; } int db__messages_delete(struct mosquitto_db *db, struct mosquitto *context) { if(!context) return MOSQ_ERR_INVAL; db__messages_delete_list(db, &context->msgs_in.inflight); db__messages_delete_list(db, &context->msgs_in.queued); db__messages_delete_list(db, &context->msgs_out.inflight); db__messages_delete_list(db, &context->msgs_out.queued); context->msgs_in.msg_bytes = 0; context->msgs_in.msg_bytes12 = 0; context->msgs_in.msg_count = 0; context->msgs_in.msg_count12 = 0; context->msgs_out.msg_bytes = 0; context->msgs_out.msg_bytes12 = 0; context->msgs_out.msg_count = 0; context->msgs_out.msg_count12 = 0; return MOSQ_ERR_SUCCESS; } int db__messages_easy_queue(struct mosquitto_db *db, struct mosquitto *context, const char *topic, int qos, uint32_t payloadlen, const void *payload, int retain, uint32_t message_expiry_interval, mosquitto_property **properties) { struct mosquitto_msg_store *stored; char *source_id; char *topic_heap; mosquitto__payload_uhpa payload_uhpa; mosquitto_property *local_properties = NULL; enum mosquitto_msg_origin origin; assert(db); payload_uhpa.ptr = NULL; if(!topic) return MOSQ_ERR_INVAL; topic_heap = mosquitto__strdup(topic); if(!topic_heap) return MOSQ_ERR_INVAL; if(db->config->retain_available == false){ retain = 0; } if(UHPA_ALLOC(payload_uhpa, payloadlen) == 0){ mosquitto__free(topic_heap); return MOSQ_ERR_NOMEM; } memcpy(UHPA_ACCESS(payload_uhpa, payloadlen), payload, payloadlen); if(context && context->id){ source_id = context->id; }else{ source_id = ""; } if(properties){ local_properties = *properties; *properties = NULL; } if(context){ origin = mosq_mo_client; }else{ origin = mosq_mo_broker; } if(db__message_store(db, context, 0, topic_heap, qos, payloadlen, &payload_uhpa, retain, &stored, message_expiry_interval, local_properties, 0, origin)) return 1; return sub__messages_queue(db, source_id, topic_heap, qos, retain, &stored); } /* This function requires topic to be allocated on the heap. Once called, it owns topic and will free it on error. Likewise payload and properties. */ int db__message_store(struct mosquitto_db *db, const struct mosquitto *source, uint16_t source_mid, char *topic, int qos, uint32_t payloadlen, mosquitto__payload_uhpa *payload, int retain, struct mosquitto_msg_store **stored, uint32_t message_expiry_interval, mosquitto_property *properties, dbid_t store_id, enum mosquitto_msg_origin origin) { struct mosquitto_msg_store *temp = NULL; int rc = MOSQ_ERR_SUCCESS; assert(db); assert(stored); temp = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(!temp){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); rc = MOSQ_ERR_NOMEM; goto error; } temp->topic = NULL; temp->payload.ptr = NULL; temp->ref_count = 0; if(source && source->id){ temp->source_id = mosquitto__strdup(source->id); }else{ temp->source_id = mosquitto__strdup(""); } if(!temp->source_id){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); rc = MOSQ_ERR_NOMEM; goto error; } if(source && source->username){ temp->source_username = mosquitto__strdup(source->username); if(!temp->source_username){ rc = MOSQ_ERR_NOMEM; goto error; } } if(source){ temp->source_listener = source->listener; } temp->source_mid = source_mid; temp->mid = 0; temp->qos = qos; temp->retain = retain; temp->topic = topic; topic = NULL; temp->payloadlen = payloadlen; temp->properties = properties; temp->origin = origin; if(payloadlen){ UHPA_MOVE(temp->payload, *payload, payloadlen); }else{ temp->payload.ptr = NULL; } if(message_expiry_interval > 0){ temp->message_expiry_time = time(NULL) + message_expiry_interval; }else{ temp->message_expiry_time = 0; } temp->dest_ids = NULL; temp->dest_id_count = 0; db->msg_store_count++; db->msg_store_bytes += payloadlen; (*stored) = temp; if(!store_id){ temp->db_id = ++db->last_db_id; }else{ temp->db_id = store_id; } db__msg_store_add(db, temp); return MOSQ_ERR_SUCCESS; error: mosquitto__free(topic); if(temp){ mosquitto__free(temp->source_id); mosquitto__free(temp->source_username); mosquitto__free(temp->topic); mosquitto__free(temp); } mosquitto_property_free_all(&properties); UHPA_FREE(*payload, payloadlen); return rc; } int db__message_store_find(struct mosquitto *context, uint16_t mid, struct mosquitto_msg_store **stored) { struct mosquitto_client_msg *tail; if(!context) return MOSQ_ERR_INVAL; *stored = NULL; DL_FOREACH(context->msgs_in.inflight, tail){ if(tail->store->source_mid == mid){ *stored = tail->store; return MOSQ_ERR_SUCCESS; } } DL_FOREACH(context->msgs_in.queued, tail){ if(tail->store->source_mid == mid){ *stored = tail->store; return MOSQ_ERR_SUCCESS; } } return 1; } /* Called on reconnect to set outgoing messages to a sensible state and force a * retry, and to set incoming messages to expect an appropriate retry. */ int db__message_reconnect_reset_outgoing(struct mosquitto_db *db, struct mosquitto *context) { struct mosquitto_client_msg *msg, *tmp; context->msgs_out.msg_bytes = 0; context->msgs_out.msg_bytes12 = 0; context->msgs_out.msg_count = 0; context->msgs_out.msg_count12 = 0; context->msgs_out.inflight_quota = context->msgs_out.inflight_maximum; DL_FOREACH_SAFE(context->msgs_out.inflight, msg, tmp){ context->msgs_out.msg_count++; context->msgs_out.msg_bytes += msg->store->payloadlen; if(msg->qos > 0){ context->msgs_out.msg_count12++; context->msgs_out.msg_bytes12 += msg->store->payloadlen; util__decrement_receive_quota(context); } switch(msg->qos){ case 0: msg->state = mosq_ms_publish_qos0; break; case 1: msg->state = mosq_ms_publish_qos1; break; case 2: if(msg->state == mosq_ms_wait_for_pubcomp){ msg->state = mosq_ms_resend_pubrel; }else{ msg->state = mosq_ms_publish_qos2; } break; } } /* Messages received when the client was disconnected are put * in the mosq_ms_queued state. If we don't change them to the * appropriate "publish" state, then the queued messages won't * get sent until the client next receives a message - and they * will be sent out of order. */ DL_FOREACH_SAFE(context->msgs_out.queued, msg, tmp){ context->msgs_out.msg_count++; context->msgs_out.msg_bytes += msg->store->payloadlen; if(msg->qos > 0){ context->msgs_out.msg_count12++; context->msgs_out.msg_bytes12 += msg->store->payloadlen; } if(db__ready_for_flight(&context->msgs_out, msg->qos)){ switch(msg->qos){ case 0: msg->state = mosq_ms_publish_qos0; break; case 1: msg->state = mosq_ms_publish_qos1; break; case 2: msg->state = mosq_ms_publish_qos2; break; } db__message_dequeue_first(context, &context->msgs_out); } } return MOSQ_ERR_SUCCESS; } /* Called on reconnect to set incoming messages to expect an appropriate retry. */ int db__message_reconnect_reset_incoming(struct mosquitto_db *db, struct mosquitto *context) { struct mosquitto_client_msg *msg, *tmp; context->msgs_in.msg_bytes = 0; context->msgs_in.msg_bytes12 = 0; context->msgs_in.msg_count = 0; context->msgs_in.msg_count12 = 0; context->msgs_in.inflight_quota = context->msgs_in.inflight_maximum; DL_FOREACH_SAFE(context->msgs_in.inflight, msg, tmp){ context->msgs_in.msg_count++; context->msgs_in.msg_bytes += msg->store->payloadlen; if(msg->qos > 0){ context->msgs_in.msg_count12++; context->msgs_in.msg_bytes12 += msg->store->payloadlen; util__decrement_receive_quota(context); } if(msg->qos != 2){ /* Anything msgs_in, msg); }else{ /* Message state can be preserved here because it should match * whatever the client has got. */ } } /* Messages received when the client was disconnected are put * in the mosq_ms_queued state. If we don't change them to the * appropriate "publish" state, then the queued messages won't * get sent until the client next receives a message - and they * will be sent out of order. */ DL_FOREACH_SAFE(context->msgs_in.queued, msg, tmp){ context->msgs_in.msg_count++; context->msgs_in.msg_bytes += msg->store->payloadlen; if(msg->qos > 0){ context->msgs_in.msg_count12++; context->msgs_in.msg_bytes12 += msg->store->payloadlen; } if(db__ready_for_flight(&context->msgs_in, msg->qos)){ switch(msg->qos){ case 0: msg->state = mosq_ms_publish_qos0; break; case 1: msg->state = mosq_ms_publish_qos1; break; case 2: msg->state = mosq_ms_publish_qos2; break; } db__message_dequeue_first(context, &context->msgs_in); } } return MOSQ_ERR_SUCCESS; } int db__message_reconnect_reset(struct mosquitto_db *db, struct mosquitto *context) { int rc; rc = db__message_reconnect_reset_outgoing(db, context); if(rc) return rc; return db__message_reconnect_reset_incoming(db, context); } int db__message_release_incoming(struct mosquitto_db *db, struct mosquitto *context, uint16_t mid) { struct mosquitto_client_msg *tail, *tmp; int retain; char *topic; char *source_id; int msg_index = 0; bool deleted = false; int rc; if(!context) return MOSQ_ERR_INVAL; DL_FOREACH_SAFE(context->msgs_in.inflight, tail, tmp){ msg_index++; if(tail->mid == mid){ if(tail->store->qos != 2){ return MOSQ_ERR_PROTOCOL; } topic = tail->store->topic; retain = tail->retain; source_id = tail->store->source_id; /* topic==NULL should be a QoS 2 message that was * denied/dropped and is being processed so the client doesn't * keep resending it. That means we don't send it to other * clients. */ if(!topic){ db__message_remove(db, &context->msgs_in, tail); deleted = true; }else{ rc = sub__messages_queue(db, source_id, topic, 2, retain, &tail->store); if(rc == MOSQ_ERR_SUCCESS || rc == MOSQ_ERR_NO_SUBSCRIBERS){ db__message_remove(db, &context->msgs_in, tail); deleted = true; }else{ return 1; } } } } DL_FOREACH_SAFE(context->msgs_in.queued, tail, tmp){ if(context->msgs_in.inflight_maximum != 0 && msg_index >= context->msgs_in.inflight_maximum){ break; } msg_index++; tail->timestamp = mosquitto_time(); if(tail->qos == 2){ send__pubrec(context, tail->mid, 0); tail->state = mosq_ms_wait_for_pubrel; db__message_dequeue_first(context, &context->msgs_in); } } if(deleted){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } } int db__message_write(struct mosquitto_db *db, struct mosquitto *context) { int rc; struct mosquitto_client_msg *tail, *tmp; uint16_t mid; int retries; int retain; const char *topic; int qos; uint32_t payloadlen; const void *payload; int msg_count = 0; mosquitto_property *cmsg_props = NULL, *store_props = NULL; time_t now = 0; uint32_t expiry_interval; if(!context || context->sock == INVALID_SOCKET || (context->state == mosq_cs_active && !context->id)){ return MOSQ_ERR_INVAL; } if(context->state != mosq_cs_active){ return MOSQ_ERR_SUCCESS; } DL_FOREACH_SAFE(context->msgs_in.inflight, tail, tmp){ msg_count++; if(tail->store->message_expiry_time){ if(now == 0){ now = time(NULL); } if(now > tail->store->message_expiry_time){ /* Message is expired, must not send. */ db__message_remove(db, &context->msgs_in, tail); continue; } } mid = tail->mid; switch(tail->state){ case mosq_ms_send_pubrec: rc = send__pubrec(context, mid, 0); if(!rc){ tail->state = mosq_ms_wait_for_pubrel; }else{ return rc; } break; case mosq_ms_resend_pubcomp: rc = send__pubcomp(context, mid); if(!rc){ tail->state = mosq_ms_wait_for_pubrel; }else{ return rc; } break; case mosq_ms_invalid: case mosq_ms_publish_qos0: case mosq_ms_publish_qos1: case mosq_ms_publish_qos2: case mosq_ms_resend_pubrel: case mosq_ms_wait_for_puback: case mosq_ms_wait_for_pubrec: case mosq_ms_wait_for_pubrel: case mosq_ms_wait_for_pubcomp: case mosq_ms_queued: break; } } DL_FOREACH_SAFE(context->msgs_out.inflight, tail, tmp){ msg_count++; if(tail->store->message_expiry_time){ if(now == 0){ now = time(NULL); } if(now > tail->store->message_expiry_time){ /* Message is expired, must not send. */ db__message_remove(db, &context->msgs_out, tail); continue; }else{ expiry_interval = tail->store->message_expiry_time - now; } }else{ expiry_interval = 0; } mid = tail->mid; retries = tail->dup; retain = tail->retain; topic = tail->store->topic; qos = tail->qos; payloadlen = tail->store->payloadlen; payload = UHPA_ACCESS_PAYLOAD(tail->store); cmsg_props = tail->properties; store_props = tail->store->properties; switch(tail->state){ case mosq_ms_publish_qos0: rc = send__publish(context, mid, topic, payloadlen, payload, qos, retain, retries, cmsg_props, store_props, expiry_interval); if(rc == MOSQ_ERR_SUCCESS || rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove(db, &context->msgs_out, tail); }else{ return rc; } break; case mosq_ms_publish_qos1: rc = send__publish(context, mid, topic, payloadlen, payload, qos, retain, retries, cmsg_props, store_props, expiry_interval); if(rc == MOSQ_ERR_SUCCESS){ tail->timestamp = mosquitto_time(); tail->dup = 1; /* Any retry attempts are a duplicate. */ tail->state = mosq_ms_wait_for_puback; }else if(rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove(db, &context->msgs_out, tail); }else{ return rc; } break; case mosq_ms_publish_qos2: rc = send__publish(context, mid, topic, payloadlen, payload, qos, retain, retries, cmsg_props, store_props, expiry_interval); if(rc == MOSQ_ERR_SUCCESS){ tail->timestamp = mosquitto_time(); tail->dup = 1; /* Any retry attempts are a duplicate. */ tail->state = mosq_ms_wait_for_pubrec; }else if(rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove(db, &context->msgs_out, tail); }else{ return rc; } break; case mosq_ms_resend_pubrel: rc = send__pubrel(context, mid); if(!rc){ tail->state = mosq_ms_wait_for_pubcomp; }else{ return rc; } break; case mosq_ms_invalid: case mosq_ms_send_pubrec: case mosq_ms_resend_pubcomp: case mosq_ms_wait_for_puback: case mosq_ms_wait_for_pubrec: case mosq_ms_wait_for_pubrel: case mosq_ms_wait_for_pubcomp: case mosq_ms_queued: break; } } DL_FOREACH_SAFE(context->msgs_in.queued, tail, tmp){ if(context->msgs_out.inflight_maximum != 0 && context->msgs_in.inflight_quota == 0){ break; } msg_count++; if(tail->qos == 2){ tail->state = mosq_ms_send_pubrec; db__message_dequeue_first(context, &context->msgs_in); rc = send__pubrec(context, tail->mid, 0); if(!rc){ tail->state = mosq_ms_wait_for_pubrel; }else{ return rc; } } } DL_FOREACH_SAFE(context->msgs_out.queued, tail, tmp){ if(context->msgs_out.inflight_maximum != 0 && context->msgs_out.inflight_quota == 0){ break; } msg_count++; switch(tail->qos){ case 0: tail->state = mosq_ms_publish_qos0; break; case 1: tail->state = mosq_ms_publish_qos1; break; case 2: tail->state = mosq_ms_publish_qos2; break; } db__message_dequeue_first(context, &context->msgs_out); } return MOSQ_ERR_SUCCESS; } void db__limits_set(unsigned long inflight_bytes, int queued, unsigned long queued_bytes) { max_inflight_bytes = inflight_bytes; max_queued = queued; max_queued_bytes = queued_bytes; } mosquitto-1.6.9/src/send_auth.c0000664000175000017500000000462713626052637015543 0ustar rogerroger/* Copyright (c) 2019-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "util_mosq.h" int send__auth(struct mosquitto_db *db, struct mosquitto *context, int reason_code, const void *auth_data, uint16_t auth_data_len) { struct mosquitto__packet *packet = NULL; int rc; mosquitto_property *properties = NULL; int proplen, varbytes; uint32_t remaining_length; if(context->auth_method == NULL) return MOSQ_ERR_INVAL; if(context->protocol != mosq_p_mqtt5) return MOSQ_ERR_PROTOCOL; log__printf(NULL, MOSQ_LOG_DEBUG, "Sending AUTH to %s (rc%d, %s)", context->id, reason_code, context->auth_method); remaining_length = 1; rc = mosquitto_property_add_string(&properties, MQTT_PROP_AUTHENTICATION_METHOD, context->auth_method); if(rc){ mosquitto_property_free_all(&properties); return rc; } if(auth_data != NULL && auth_data_len > 0){ rc = mosquitto_property_add_binary(&properties, MQTT_PROP_AUTHENTICATION_DATA, auth_data, auth_data_len); if(rc){ mosquitto_property_free_all(&properties); return rc; } } proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); remaining_length += proplen + varbytes; if(packet__check_oversize(context, remaining_length)){ mosquitto_property_free_all(&properties); mosquitto__free(packet); return MOSQ_ERR_OVERSIZE_PACKET; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = CMD_AUTH; packet->remaining_length = remaining_length; rc = packet__alloc(packet); if(rc){ mosquitto_property_free_all(&properties); mosquitto__free(packet); return rc; } packet__write_byte(packet, reason_code); property__write_all(packet, properties, true); mosquitto_property_free_all(&properties); return packet__queue(context, packet); } mosquitto-1.6.9/src/persist_write.c0000664000175000017500000002521413626052637016467 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_PERSISTENCE #ifndef WIN32 #include #endif #include #include #include #include #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "persist.h" #include "time_mosq.h" #include "misc_mosq.h" #include "util_mosq.h" static int persist__client_messages_save(struct mosquitto_db *db, FILE *db_fptr, struct mosquitto *context, struct mosquitto_client_msg *queue) { struct P_client_msg chunk; struct mosquitto_client_msg *cmsg; int rc; assert(db); assert(db_fptr); assert(context); memset(&chunk, 0, sizeof(struct P_client_msg)); cmsg = queue; while(cmsg){ if(!strncmp(cmsg->store->topic, "$SYS", 4) && cmsg->store->ref_count <= 1 && cmsg->store->dest_id_count == 0){ /* This $SYS message won't have been persisted, so we can't persist * this client message. */ cmsg = cmsg->next; continue; } chunk.F.store_id = cmsg->store->db_id; chunk.F.mid = cmsg->mid; chunk.F.id_len = strlen(context->id); chunk.F.qos = cmsg->qos; chunk.F.retain_dup = (cmsg->retain&0x0F)<<4 | (cmsg->dup&0x0F); chunk.F.direction = cmsg->direction; chunk.F.state = cmsg->state; chunk.client_id = context->id; chunk.properties = cmsg->properties; rc = persist__chunk_client_msg_write_v5(db_fptr, &chunk); if(rc){ return rc; } cmsg = cmsg->next; } return MOSQ_ERR_SUCCESS; } static int persist__message_store_save(struct mosquitto_db *db, FILE *db_fptr) { struct P_msg_store chunk; struct mosquitto_msg_store *stored; int rc; assert(db); assert(db_fptr); memset(&chunk, 0, sizeof(struct P_msg_store)); stored = db->msg_store; while(stored){ if(stored->ref_count < 1 || stored->topic == NULL){ stored = stored->next; continue; } if(!strncmp(stored->topic, "$SYS", 4)){ if(stored->ref_count <= 1 && stored->dest_id_count == 0){ /* $SYS messages that are only retained shouldn't be persisted. */ stored = stored->next; continue; } /* Don't save $SYS messages as retained otherwise they can give * misleading information when reloaded. They should still be saved * because a disconnected durable client may have them in their * queue. */ chunk.F.retain = 0; }else{ chunk.F.retain = (uint8_t)stored->retain; } chunk.F.store_id = stored->db_id; chunk.F.expiry_time = stored->message_expiry_time; chunk.F.payloadlen = stored->payloadlen; chunk.F.source_mid = stored->source_mid; if(stored->source_id){ chunk.F.source_id_len = strlen(stored->source_id); chunk.source.id = stored->source_id; }else{ chunk.F.source_id_len = 0; chunk.source.id = NULL; } if(stored->source_username){ chunk.F.source_username_len = strlen(stored->source_username); chunk.source.username = stored->source_username; }else{ chunk.F.source_username_len = 0; chunk.source.username = NULL; } chunk.F.topic_len = strlen(stored->topic); chunk.topic = stored->topic; if(stored->source_listener){ chunk.F.source_port = stored->source_listener->port; }else{ chunk.F.source_port = 0; } chunk.F.qos = stored->qos; chunk.payload = stored->payload; chunk.properties = stored->properties; rc = persist__chunk_message_store_write_v5(db_fptr, &chunk); if(rc){ return rc; } stored = stored->next; } return MOSQ_ERR_SUCCESS; } static int persist__client_save(struct mosquitto_db *db, FILE *db_fptr) { struct mosquitto *context, *ctxt_tmp; struct P_client chunk; int rc; assert(db); assert(db_fptr); memset(&chunk, 0, sizeof(struct P_client)); HASH_ITER(hh_id, db->contexts_by_id, context, ctxt_tmp){ if(context && context->clean_start == false){ chunk.F.session_expiry_time = context->session_expiry_time; chunk.F.session_expiry_interval = context->session_expiry_interval; chunk.F.last_mid = context->last_mid; chunk.F.id_len = strlen(context->id); chunk.client_id = context->id; rc = persist__chunk_client_write_v5(db_fptr, &chunk); if(rc){ return rc; } if(persist__client_messages_save(db, db_fptr, context, context->msgs_in.inflight)) return 1; if(persist__client_messages_save(db, db_fptr, context, context->msgs_in.queued)) return 1; if(persist__client_messages_save(db, db_fptr, context, context->msgs_out.inflight)) return 1; if(persist__client_messages_save(db, db_fptr, context, context->msgs_out.queued)) return 1; } } return MOSQ_ERR_SUCCESS; } static int persist__subs_retain_save(struct mosquitto_db *db, FILE *db_fptr, struct mosquitto__subhier *node, const char *topic, int level) { struct mosquitto__subhier *subhier, *subhier_tmp; struct mosquitto__subleaf *sub; struct P_retain retain_chunk; struct P_sub sub_chunk; char *thistopic; size_t slen; int rc; memset(&retain_chunk, 0, sizeof(struct P_retain)); memset(&sub_chunk, 0, sizeof(struct P_sub)); slen = strlen(topic) + node->topic_len + 2; thistopic = mosquitto__malloc(sizeof(char)*slen); if(!thistopic) return MOSQ_ERR_NOMEM; if(level > 1 || strlen(topic)){ snprintf(thistopic, slen, "%s/%s", topic, node->topic); }else{ snprintf(thistopic, slen, "%s", node->topic); } sub = node->subs; while(sub){ if(sub->context->clean_start == false && sub->context->id){ sub_chunk.F.identifier = sub->identifier; sub_chunk.F.id_len = strlen(sub->context->id); sub_chunk.F.topic_len = strlen(thistopic); sub_chunk.F.qos = (uint8_t)sub->qos; sub_chunk.F.options = sub->no_local<<2 | sub->retain_as_published<<3; sub_chunk.client_id = sub->context->id; sub_chunk.topic = thistopic; rc = persist__chunk_sub_write_v5(db_fptr, &sub_chunk); if(rc){ mosquitto__free(thistopic); return rc; } } sub = sub->next; } if(node->retained){ if(strncmp(node->retained->topic, "$SYS", 4)){ /* Don't save $SYS messages. */ retain_chunk.F.store_id = node->retained->db_id; rc = persist__chunk_retain_write_v5(db_fptr, &retain_chunk); if(rc){ mosquitto__free(thistopic); return rc; } } } HASH_ITER(hh, node->children, subhier, subhier_tmp){ persist__subs_retain_save(db, db_fptr, subhier, thistopic, level+1); } mosquitto__free(thistopic); return MOSQ_ERR_SUCCESS; } static int persist__subs_retain_save_all(struct mosquitto_db *db, FILE *db_fptr) { struct mosquitto__subhier *subhier, *subhier_tmp; HASH_ITER(hh, db->subs, subhier, subhier_tmp){ if(subhier->children){ persist__subs_retain_save(db, db_fptr, subhier->children, "", 0); } } return MOSQ_ERR_SUCCESS; } int persist__backup(struct mosquitto_db *db, bool shutdown) { int rc = 0; FILE *db_fptr = NULL; uint32_t db_version_w = htonl(MOSQ_DB_VERSION); uint32_t crc = 0; char *err; char *outfile = NULL; int len; struct PF_cfg cfg_chunk; if(!db || !db->config || !db->config->persistence_filepath) return MOSQ_ERR_INVAL; if(db->config->persistence == false) return MOSQ_ERR_SUCCESS; log__printf(NULL, MOSQ_LOG_INFO, "Saving in-memory database to %s.", db->config->persistence_filepath); len = strlen(db->config->persistence_filepath)+5; outfile = mosquitto__malloc(len+1); if(!outfile){ log__printf(NULL, MOSQ_LOG_INFO, "Error saving in-memory database, out of memory."); return MOSQ_ERR_NOMEM; } snprintf(outfile, len, "%s.new", db->config->persistence_filepath); outfile[len] = '\0'; #ifndef WIN32 /** * * If a system lost power during the rename operation at the * end of this file the filesystem could potentially be left * with a directory that looks like this after powerup: * * 24094 -rw-r--r-- 2 root root 4099 May 30 16:27 mosquitto.db * 24094 -rw-r--r-- 2 root root 4099 May 30 16:27 mosquitto.db.new * * The 24094 shows that mosquitto.db.new is hard-linked to the * same file as mosquitto.db. If fopen(outfile, "wb") is naively * called then mosquitto.db will be truncated and the database * potentially corrupted. * * Any existing mosquitto.db.new file must be removed prior to * opening to guarantee that it is not hard-linked to * mosquitto.db. * */ rc = unlink(outfile); if (rc != 0) { rc = 0; if (errno != ENOENT) { log__printf(NULL, MOSQ_LOG_INFO, "Error saving in-memory database, unable to remove %s.", outfile); goto error; } } #endif db_fptr = mosquitto__fopen(outfile, "wb", true); if(db_fptr == NULL){ log__printf(NULL, MOSQ_LOG_INFO, "Error saving in-memory database, unable to open %s for writing.", outfile); goto error; } /* Header */ write_e(db_fptr, magic, 15); write_e(db_fptr, &crc, sizeof(uint32_t)); write_e(db_fptr, &db_version_w, sizeof(uint32_t)); memset(&cfg_chunk, 0, sizeof(struct PF_cfg)); cfg_chunk.last_db_id = db->last_db_id; cfg_chunk.shutdown = shutdown; cfg_chunk.dbid_size = sizeof(dbid_t); if(persist__chunk_cfg_write_v5(db_fptr, &cfg_chunk)){ goto error; } if(persist__message_store_save(db, db_fptr)){ goto error; } persist__client_save(db, db_fptr); persist__subs_retain_save_all(db, db_fptr); #ifndef WIN32 /** * * Closing a file does not guarantee that the contents are * written to disk. Need to flush to send data from app to OS * buffers, then fsync to deliver data from OS buffers to disk * (as well as disk hardware permits). * * man close (http://linux.die.net/man/2/close, 2016-06-20): * * "successful close does not guarantee that the data has * been successfully saved to disk, as the kernel defers * writes. It is not common for a filesystem to flush * the buffers when the stream is closed. If you need * to be sure that the data is physically stored, use * fsync(2). (It will depend on the disk hardware at this * point." * * This guarantees that the new state file will not overwrite * the old state file before its contents are valid. * */ fflush(db_fptr); fsync(fileno(db_fptr)); #endif fclose(db_fptr); #ifdef WIN32 if(remove(db->config->persistence_filepath) != 0){ if(errno != ENOENT){ goto error; } } #endif if(rename(outfile, db->config->persistence_filepath) != 0){ goto error; } mosquitto__free(outfile); outfile = NULL; return rc; error: mosquitto__free(outfile); err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); if(db_fptr) fclose(db_fptr); return 1; } #endif mosquitto-1.6.9/src/lib_load.h0000664000175000017500000000201413626052637015327 0ustar rogerroger/* Copyright (c) 2012-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef LIB_LOAD_H #define LIB_LOAD_H #ifdef WIN32 # include #else # include #endif #ifdef WIN32 # define LIB_LOAD(A) LoadLibrary(A) # define LIB_CLOSE(A) FreeLibrary(A) # define LIB_SYM(HANDLE, SYM) GetProcAddress(HANDLE, SYM) #else # define LIB_LOAD(A) dlopen(A, RTLD_NOW|RTLD_GLOBAL) # define LIB_CLOSE(A) dlclose(A) # define LIB_SYM(HANDLE, SYM) dlsym(HANDLE, SYM) #endif #define LIB_SYM_EASY(MEMBER, HANDLE, SYM) if(!(MEMBER = LIB_SYM(HANDLE, SYM)) return 1 #endif mosquitto-1.6.9/src/persist_read_v234.c0000664000175000017500000001260613626052637017027 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_PERSISTENCE #ifndef WIN32 #include #endif #include #include #include #include #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "persist.h" #include "time_mosq.h" #include "util_mosq.h" int persist__chunk_header_read_v234(FILE *db_fptr, int *chunk, int *length) { size_t rlen; uint16_t i16temp; uint32_t i32temp; rlen = fread(&i16temp, sizeof(uint16_t), 1, db_fptr); if(rlen != 1) return 1; rlen = fread(&i32temp, sizeof(uint32_t), 1, db_fptr); if(rlen != 1) return 1; *chunk = ntohs(i16temp); *length = ntohl(i32temp); return MOSQ_ERR_SUCCESS; } int persist__chunk_cfg_read_v234(FILE *db_fptr, struct PF_cfg *chunk) { read_e(db_fptr, &chunk->shutdown, sizeof(uint8_t)); // shutdown read_e(db_fptr, &chunk->dbid_size, sizeof(uint8_t)); // sizeof(dbid_t) read_e(db_fptr, &chunk->last_db_id, sizeof(dbid_t)); return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_client_read_v234(FILE *db_fptr, struct P_client *chunk, int db_version) { uint16_t i16temp; int rc; time_t temp; rc = persist__read_string(db_fptr, &chunk->client_id); if(rc){ return rc; } read_e(db_fptr, &i16temp, sizeof(uint16_t)); chunk->F.last_mid = ntohs(i16temp); if(db_version != 2){ read_e(db_fptr, &temp, sizeof(time_t)); } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); mosquitto__free(chunk->client_id); return 1; } int persist__chunk_client_msg_read_v234(FILE *db_fptr, struct P_client_msg *chunk) { uint16_t i16temp; int rc; char *err; uint8_t retain, dup; rc = persist__read_string(db_fptr, &chunk->client_id); if(rc){ return rc; } read_e(db_fptr, &chunk->F.store_id, sizeof(dbid_t)); read_e(db_fptr, &i16temp, sizeof(uint16_t)); chunk->F.mid = ntohs(i16temp); read_e(db_fptr, &chunk->F.qos, sizeof(uint8_t)); read_e(db_fptr, &retain, sizeof(uint8_t)); read_e(db_fptr, &chunk->F.direction, sizeof(uint8_t)); read_e(db_fptr, &chunk->F.state, sizeof(uint8_t)); read_e(db_fptr, &dup, sizeof(uint8_t)); chunk->F.retain_dup = (retain&0x0F)<<4 | (dup&0x0F); return MOSQ_ERR_SUCCESS; error: err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); mosquitto__free(chunk->client_id); return 1; } int persist__chunk_msg_store_read_v234(FILE *db_fptr, struct P_msg_store *chunk, int db_version) { uint32_t i32temp; uint16_t i16temp; int rc = 0; char *err; read_e(db_fptr, &chunk->F.store_id, sizeof(dbid_t)); rc = persist__read_string(db_fptr, &chunk->source.id); if(rc){ return rc; } if(db_version == 4){ rc = persist__read_string(db_fptr, &chunk->source.username); if(rc){ mosquitto__free(chunk->source.id); return rc; } read_e(db_fptr, &i16temp, sizeof(uint16_t)); chunk->F.source_port = ntohs(i16temp); } read_e(db_fptr, &i16temp, sizeof(uint16_t)); chunk->F.source_mid = ntohs(i16temp); /* This is the mid - don't need it */ read_e(db_fptr, &i16temp, sizeof(uint16_t)); rc = persist__read_string(db_fptr, &chunk->topic); if(rc){ mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); return rc; } read_e(db_fptr, &chunk->F.qos, sizeof(uint8_t)); read_e(db_fptr, &chunk->F.retain, sizeof(uint8_t)); read_e(db_fptr, &i32temp, sizeof(uint32_t)); chunk->F.payloadlen = ntohl(i32temp); if(chunk->F.payloadlen){ if(UHPA_ALLOC(chunk->payload, chunk->F.payloadlen) == 0){ mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); mosquitto__free(chunk->topic); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } read_e(db_fptr, UHPA_ACCESS(chunk->payload, chunk->F.payloadlen), chunk->F.payloadlen); } return MOSQ_ERR_SUCCESS; error: err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); return 1; } int persist__chunk_retain_read_v234(FILE *db_fptr, struct P_retain *chunk) { dbid_t i64temp; char *err; if(fread(&i64temp, sizeof(dbid_t), 1, db_fptr) != 1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); return 1; } chunk->F.store_id = i64temp; return MOSQ_ERR_SUCCESS; } int persist__chunk_sub_read_v234(FILE *db_fptr, struct P_sub *chunk) { int rc; char *err; rc = persist__read_string(db_fptr, &chunk->client_id); if(rc){ return rc; } rc = persist__read_string(db_fptr, &chunk->topic); if(rc){ mosquitto__free(chunk->client_id); return rc; } read_e(db_fptr, &chunk->F.qos, sizeof(uint8_t)); return MOSQ_ERR_SUCCESS; error: err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); mosquitto__free(chunk->client_id); mosquitto__free(chunk->topic); return 1; } #endif mosquitto-1.6.9/src/plugin_debug.c0000664000175000017500000000771313626052637016234 0ustar rogerroger/* Copyright (c) 2015-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ /* This is a skeleton authentication and access control plugin that print a * message when each check occurs. It allows everything. */ #include #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" #define ANSI_GREEN "\e[0;32m" #define ANSI_BLUE "\e[0;34m" #define ANSI_MAGENTA "\e[0;35m" #define ANSI_RESET "\e[0m" void print_col(struct mosquitto *client) { switch(mosquitto_client_protocol(client)){ case mp_mqtt: printf("%s", ANSI_GREEN); break; case mp_websockets: printf("%s", ANSI_MAGENTA); break; default: break; } } int mosquitto_auth_plugin_version(void) { printf(ANSI_BLUE "PLUGIN ::: mosquitto_auth_plugin_version()" ANSI_RESET "\n"); return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { printf(ANSI_BLUE "PLUGIN ::: mosquitto_auth_plugin_init(,,%d)" ANSI_RESET "\n", auth_opt_count); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { printf(ANSI_BLUE "PLUGIN ::: mosquitto_auth_plugin_cleanup(,,%d)" ANSI_RESET "\n", auth_opt_count); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { printf(ANSI_BLUE "PLUGIN ::: mosquitto_auth_security_init(,,%d, %d)" ANSI_RESET "\n", auth_opt_count, reload); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { printf(ANSI_BLUE "PLUGIN ::: mosquitto_auth_security_cleanup(,,%d, %d)" ANSI_RESET "\n", auth_opt_count, reload); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { print_col(client); printf("PLUGIN ::: mosquitto_auth_acl_check(%p, %d, %s, %s)" ANSI_RESET "\n", user_data, access, mosquitto_client_username(client), msg->topic); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { print_col(client); printf("PLUGIN ::: mosquitto_auth_unpwd_check(%p, %s, %s)" ANSI_RESET "\n", user_data, mosquitto_client_username(client), username); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { print_col(client); printf("PLUGIN ::: mosquitto_auth_psk_key_get(%p, %s, %s)" ANSI_RESET "\n", user_data, mosquitto_client_username(client), hint); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_start(void *user_data, struct mosquitto *client, const char *method, bool reauth, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len) { print_col(client); printf("PLUGIN ::: mosquitto_auth_start(%p, %s, %s, %d, %d, %hn)" ANSI_RESET "\n", user_data, mosquitto_client_username(client), method, reauth, data_in_len, data_out_len); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_continue(void *user_data, struct mosquitto *client, const char *method, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len) { print_col(client); printf("PLUGIN ::: mosquitto_auth_continue(%p, %s, %s, %d, %hn)" ANSI_RESET "\n", user_data, mosquitto_client_username(client), method, data_in_len, data_out_len); return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/src/send_connack.c0000664000175000017500000000530513626052637016210 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "util_mosq.h" int send__connack(struct mosquitto_db *db, struct mosquitto *context, int ack, int reason_code, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; int rc; mosquitto_property *connack_props = NULL; int proplen, varbytes; uint32_t remaining_length; rc = mosquitto_property_copy_all(&connack_props, properties); if(rc){ return rc; } if(context->id){ log__printf(NULL, MOSQ_LOG_DEBUG, "Sending CONNACK to %s (%d, %d)", context->id, ack, reason_code); }else{ log__printf(NULL, MOSQ_LOG_DEBUG, "Sending CONNACK to %s (%d, %d)", context->address, ack, reason_code); } remaining_length = 2; if(context->protocol == mosq_p_mqtt5){ if(reason_code < 128 && db->config->retain_available == false){ rc = mosquitto_property_add_byte(&connack_props, MQTT_PROP_RETAIN_AVAILABLE, 0); if(rc){ mosquitto_property_free_all(&connack_props); return rc; } } if(db->config->max_packet_size > 0){ rc = mosquitto_property_add_int32(&connack_props, MQTT_PROP_MAXIMUM_PACKET_SIZE, db->config->max_packet_size); if(rc){ mosquitto_property_free_all(&connack_props); return rc; } } proplen = property__get_length_all(connack_props); varbytes = packet__varint_bytes(proplen); remaining_length += proplen + varbytes; } if(packet__check_oversize(context, remaining_length)){ mosquitto_property_free_all(&connack_props); mosquitto__free(packet); return MOSQ_ERR_OVERSIZE_PACKET; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = CMD_CONNACK; packet->remaining_length = remaining_length; rc = packet__alloc(packet); if(rc){ mosquitto_property_free_all(&connack_props); mosquitto__free(packet); return rc; } packet__write_byte(packet, ack); packet__write_byte(packet, reason_code); if(context->protocol == mosq_p_mqtt5){ property__write_all(packet, connack_props, true); } mosquitto_property_free_all(&connack_props); return packet__queue(context, packet); } mosquitto-1.6.9/src/conf.c0000664000175000017500000027146313626052637014522 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #ifdef WIN32 #else # include # include #endif #ifndef WIN32 # include # include #else # include # include #endif #if !defined(WIN32) && !defined(__CYGWIN__) # include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "misc_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #include "mqtt_protocol.h" struct config_recurse { int log_dest; int log_dest_set; int log_type; int log_type_set; unsigned long max_inflight_bytes; unsigned long max_queued_bytes; int max_queued_messages; }; #if defined(WIN32) || defined(__CYGWIN__) #include extern SERVICE_STATUS_HANDLE service_handle; #endif static struct mosquitto__security_options *cur_security_options = NULL; static int conf__parse_bool(char **token, const char *name, bool *value, char *saveptr); static int conf__parse_int(char **token, const char *name, int *value, char *saveptr); static int conf__parse_ssize_t(char **token, const char *name, ssize_t *value, char *saveptr); static int conf__parse_string(char **token, const char *name, char **value, char *saveptr); static int config__read_file(struct mosquitto__config *config, bool reload, const char *file, struct config_recurse *config_tmp, int level, int *lineno); static int config__check(struct mosquitto__config *config); static void config__cleanup_plugins(struct mosquitto__config *config); static void conf__set_cur_security_options(struct mosquitto__config *config, struct mosquitto__listener *cur_listener, struct mosquitto__security_options **security_options) { if(config->per_listener_settings){ (*security_options) = &cur_listener->security_options; }else{ (*security_options) = &config->security_options; } } static int conf__attempt_resolve(const char *host, const char *text, int log, const char *msg) { struct addrinfo gai_hints; struct addrinfo *gai_res; int rc; memset(&gai_hints, 0, sizeof(struct addrinfo)); gai_hints.ai_family = AF_UNSPEC; gai_hints.ai_socktype = SOCK_STREAM; gai_res = NULL; rc = getaddrinfo(host, NULL, &gai_hints, &gai_res); if(gai_res){ freeaddrinfo(gai_res); } if(rc != 0){ #ifndef WIN32 if(rc == EAI_SYSTEM){ if(errno == ENOENT){ log__printf(NULL, log, "%s: Unable to resolve %s %s.", msg, text, host); }else{ log__printf(NULL, log, "%s: Error resolving %s: %s.", msg, text, strerror(errno)); } }else{ log__printf(NULL, log, "%s: Error resolving %s: %s.", msg, text, gai_strerror(rc)); } #else if(rc == WSAHOST_NOT_FOUND){ log__printf(NULL, log, "%s: Error resolving %s.", msg, text); } #endif return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static void config__init_reload(struct mosquitto_db *db, struct mosquitto__config *config) { int i; /* Set defaults */ for(i=0; ilistener_count; i++){ mosquitto__free(config->listeners[i].security_options.acl_file); config->listeners[i].security_options.acl_file = NULL; mosquitto__free(config->listeners[i].security_options.password_file); config->listeners[i].security_options.password_file = NULL; mosquitto__free(config->listeners[i].security_options.psk_file); config->listeners[i].security_options.psk_file = NULL; config->listeners[i].security_options.allow_anonymous = -1; config->listeners[i].security_options.allow_zero_length_clientid = true; config->listeners[i].security_options.auto_id_prefix = NULL; config->listeners[i].security_options.auto_id_prefix_len = 0; } config->allow_duplicate_messages = false; mosquitto__free(config->security_options.acl_file); config->security_options.acl_file = NULL; config->security_options.allow_anonymous = -1; config->security_options.allow_zero_length_clientid = true; config->security_options.auto_id_prefix = NULL; config->security_options.auto_id_prefix_len = 0; mosquitto__free(config->security_options.password_file); config->security_options.password_file = NULL; mosquitto__free(config->security_options.psk_file); config->security_options.psk_file = NULL; config->autosave_interval = 1800; config->autosave_on_changes = false; mosquitto__free(config->clientid_prefixes); config->connection_messages = true; config->clientid_prefixes = NULL; config->per_listener_settings = false; if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } mosquitto__free(config->log_file); config->log_file = NULL; #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ /* This is running as a Windows service. Default to no logging. Using * stdout/stderr is forbidden because the first clients to connect will * get log information sent to them for some reason. */ config->log_dest = MQTT3_LOG_NONE; }else{ config->log_dest = MQTT3_LOG_STDERR; } #else config->log_facility = LOG_DAEMON; config->log_dest = MQTT3_LOG_STDERR; if(db->verbose){ config->log_type = UINT_MAX; }else{ config->log_type = MOSQ_LOG_ERR | MOSQ_LOG_WARNING | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO; } #endif config->log_timestamp = true; mosquitto__free(config->log_timestamp_format); config->log_timestamp_format = NULL; config->max_keepalive = 65535; config->max_packet_size = 0; config->max_inflight_messages = 20; config->persistence = false; mosquitto__free(config->persistence_location); config->persistence_location = NULL; mosquitto__free(config->persistence_file); config->persistence_file = NULL; config->persistent_client_expiration = 0; config->queue_qos0_messages = false; config->retain_available = true; config->set_tcp_nodelay = false; config->sys_interval = 10; config->upgrade_outgoing_qos = false; config__cleanup_plugins(config); } static void config__cleanup_plugins(struct mosquitto__config *config) { int i, j; struct mosquitto__auth_plugin_config *plug; if(config->security_options.auth_plugin_configs){ for(i=0; isecurity_options.auth_plugin_config_count; i++){ plug = &config->security_options.auth_plugin_configs[i]; mosquitto__free(plug->path); plug->path = NULL; if(plug->options){ for(j=0; joption_count; j++){ mosquitto__free(plug->options[j].key); mosquitto__free(plug->options[j].value); } mosquitto__free(plug->options); plug->options = NULL; plug->option_count = 0; } } mosquitto__free(config->security_options.auth_plugin_configs); config->security_options.auth_plugin_configs = NULL; } } void config__init(struct mosquitto_db *db, struct mosquitto__config *config) { memset(config, 0, sizeof(struct mosquitto__config)); config__init_reload(db, config); config->daemon = false; memset(&config->default_listener, 0, sizeof(struct mosquitto__listener)); config->default_listener.max_connections = -1; config->default_listener.protocol = mp_mqtt; config->default_listener.security_options.allow_anonymous = -1; config->default_listener.security_options.allow_zero_length_clientid = true; config->default_listener.maximum_qos = 2; config->default_listener.max_topic_alias = 10; } void config__cleanup(struct mosquitto__config *config) { int i; #ifdef WITH_BRIDGE int j; #endif mosquitto__free(config->clientid_prefixes); mosquitto__free(config->persistence_location); mosquitto__free(config->persistence_file); mosquitto__free(config->persistence_filepath); mosquitto__free(config->security_options.auto_id_prefix); mosquitto__free(config->security_options.acl_file); mosquitto__free(config->security_options.password_file); mosquitto__free(config->security_options.psk_file); mosquitto__free(config->pid_file); mosquitto__free(config->user); mosquitto__free(config->log_timestamp_format); if(config->listeners){ for(i=0; ilistener_count; i++){ mosquitto__free(config->listeners[i].host); mosquitto__free(config->listeners[i].bind_interface); mosquitto__free(config->listeners[i].mount_point); mosquitto__free(config->listeners[i].socks); mosquitto__free(config->listeners[i].security_options.auto_id_prefix); mosquitto__free(config->listeners[i].security_options.acl_file); mosquitto__free(config->listeners[i].security_options.password_file); mosquitto__free(config->listeners[i].security_options.psk_file); #ifdef WITH_TLS mosquitto__free(config->listeners[i].cafile); mosquitto__free(config->listeners[i].capath); mosquitto__free(config->listeners[i].certfile); mosquitto__free(config->listeners[i].keyfile); mosquitto__free(config->listeners[i].ciphers); mosquitto__free(config->listeners[i].psk_hint); mosquitto__free(config->listeners[i].crlfile); mosquitto__free(config->listeners[i].dhparamfile); mosquitto__free(config->listeners[i].tls_version); mosquitto__free(config->listeners[i].tls_engine); mosquitto__free(config->listeners[i].tls_engine_kpass_sha1); #ifdef WITH_WEBSOCKETS if(!config->listeners[i].ws_context) /* libwebsockets frees its own SSL_CTX */ #endif { SSL_CTX_free(config->listeners[i].ssl_ctx); } #endif #ifdef WITH_WEBSOCKETS mosquitto__free(config->listeners[i].http_dir); #endif } mosquitto__free(config->listeners); } #ifdef WITH_BRIDGE if(config->bridges){ for(i=0; ibridge_count; i++){ mosquitto__free(config->bridges[i].name); if(config->bridges[i].addresses){ for(j=0; jbridges[i].address_count; j++){ mosquitto__free(config->bridges[i].addresses[j].address); } mosquitto__free(config->bridges[i].addresses); } mosquitto__free(config->bridges[i].remote_clientid); mosquitto__free(config->bridges[i].remote_username); mosquitto__free(config->bridges[i].remote_password); mosquitto__free(config->bridges[i].local_clientid); mosquitto__free(config->bridges[i].local_username); mosquitto__free(config->bridges[i].local_password); if(config->bridges[i].topics){ for(j=0; jbridges[i].topic_count; j++){ mosquitto__free(config->bridges[i].topics[j].topic); mosquitto__free(config->bridges[i].topics[j].local_prefix); mosquitto__free(config->bridges[i].topics[j].remote_prefix); mosquitto__free(config->bridges[i].topics[j].local_topic); mosquitto__free(config->bridges[i].topics[j].remote_topic); } mosquitto__free(config->bridges[i].topics); } mosquitto__free(config->bridges[i].notification_topic); #ifdef WITH_TLS mosquitto__free(config->bridges[i].tls_version); mosquitto__free(config->bridges[i].tls_cafile); mosquitto__free(config->bridges[i].tls_alpn); #ifdef FINAL_WITH_TLS_PSK mosquitto__free(config->bridges[i].tls_psk_identity); mosquitto__free(config->bridges[i].tls_psk); #endif #endif } mosquitto__free(config->bridges); } #endif config__cleanup_plugins(config); if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } if(config->log_file){ mosquitto__free(config->log_file); config->log_file = NULL; } } static void print_usage(void) { printf("mosquitto version %s\n\n", VERSION); printf("mosquitto is an MQTT v3.1.1 broker.\n\n"); printf("Usage: mosquitto [-c config_file] [-d] [-h] [-p port]\n\n"); printf(" -c : specify the broker config file.\n"); printf(" -d : put the broker into the background after starting.\n"); printf(" -h : display this help.\n"); printf(" -p : start the broker listening on the specified port.\n"); printf(" Not recommended in conjunction with the -c option.\n"); printf(" -v : verbose mode - enable all logging types. This overrides\n"); printf(" any logging options given in the config file.\n"); printf("\nSee http://mosquitto.org/ for more information.\n\n"); } int config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; iconfig_file = argv[i+1]; if(config__read(db, config, false)){ return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){ config->daemon = true; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){ print_usage(); return MOSQ_ERR_INVAL; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } config->default_listener.port = port_tmp; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ db->verbose = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } if(config->listener_count == 0 || config->default_listener.bind_interface #ifdef WITH_TLS || config->default_listener.cafile || config->default_listener.capath || config->default_listener.certfile || config->default_listener.keyfile || config->default_listener.tls_engine || config->default_listener.tls_keyform != mosq_k_pem || config->default_listener.tls_engine_kpass_sha1 || config->default_listener.ciphers || config->default_listener.dhparamfile || config->default_listener.psk_hint || config->default_listener.require_certificate || config->default_listener.crlfile || config->default_listener.use_identity_as_username || config->default_listener.use_subject_as_username #endif || config->default_listener.use_username_as_clientid || config->default_listener.host || config->default_listener.port || config->default_listener.max_connections != -1 || config->default_listener.maximum_qos != 2 || config->default_listener.mount_point || config->default_listener.protocol != mp_mqtt || config->default_listener.socket_domain || config->default_listener.security_options.password_file || config->default_listener.security_options.psk_file || config->default_listener.security_options.auth_plugin_config_count || config->default_listener.security_options.allow_anonymous != -1 || config->default_listener.security_options.allow_zero_length_clientid != true ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener)); if(config->default_listener.port){ config->listeners[config->listener_count-1].port = config->default_listener.port; }else{ config->listeners[config->listener_count-1].port = 1883; } if(config->default_listener.host){ config->listeners[config->listener_count-1].host = config->default_listener.host; }else{ config->listeners[config->listener_count-1].host = NULL; } if(config->default_listener.mount_point){ config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point; }else{ config->listeners[config->listener_count-1].mount_point = NULL; } config->listeners[config->listener_count-1].bind_interface = config->default_listener.bind_interface; config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections; config->listeners[config->listener_count-1].protocol = config->default_listener.protocol; config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].socks = NULL; config->listeners[config->listener_count-1].sock_count = 0; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid; config->listeners[config->listener_count-1].maximum_qos = config->default_listener.maximum_qos; config->listeners[config->listener_count-1].max_topic_alias = config->default_listener.max_topic_alias; #ifdef WITH_TLS config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version; config->listeners[config->listener_count-1].tls_engine = config->default_listener.tls_engine; config->listeners[config->listener_count-1].tls_keyform = config->default_listener.tls_keyform; config->listeners[config->listener_count-1].tls_engine_kpass_sha1 = config->default_listener.tls_engine_kpass_sha1; config->listeners[config->listener_count-1].cafile = config->default_listener.cafile; config->listeners[config->listener_count-1].capath = config->default_listener.capath; config->listeners[config->listener_count-1].certfile = config->default_listener.certfile; config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile; config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers; config->listeners[config->listener_count-1].dhparamfile = config->default_listener.dhparamfile; config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint; config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate; config->listeners[config->listener_count-1].ssl_ctx = NULL; config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile; config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username; config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username; #endif config->listeners[config->listener_count-1].security_options.acl_file = config->default_listener.security_options.acl_file; config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file; config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file; config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs; config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count; config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous; config->listeners[config->listener_count-1].security_options.allow_zero_length_clientid = config->default_listener.security_options.allow_zero_length_clientid; } /* Default to drop to mosquitto user if we are privileged and no user specified. */ if(!config->user){ config->user = mosquitto__strdup("mosquitto"); if(config->user == NULL){ return MOSQ_ERR_NOMEM; } } if(db->verbose){ config->log_type = UINT_MAX; } return config__check(config); } void config__copy(struct mosquitto__config *src, struct mosquitto__config *dest) { mosquitto__free(dest->security_options.acl_file); dest->security_options.acl_file = src->security_options.acl_file; dest->security_options.allow_anonymous = src->security_options.allow_anonymous; dest->security_options.allow_zero_length_clientid = src->security_options.allow_zero_length_clientid; mosquitto__free(dest->security_options.auto_id_prefix); dest->security_options.auto_id_prefix = src->security_options.auto_id_prefix; dest->security_options.auto_id_prefix_len = src->security_options.auto_id_prefix_len; mosquitto__free(dest->security_options.password_file); dest->security_options.password_file = src->security_options.password_file; mosquitto__free(dest->security_options.psk_file); dest->security_options.psk_file = src->security_options.psk_file; dest->allow_duplicate_messages = src->allow_duplicate_messages; dest->autosave_interval = src->autosave_interval; dest->autosave_on_changes = src->autosave_on_changes; mosquitto__free(dest->clientid_prefixes); dest->clientid_prefixes = src->clientid_prefixes; dest->connection_messages = src->connection_messages; dest->log_dest = src->log_dest; dest->log_facility = src->log_facility; dest->log_type = src->log_type; dest->log_timestamp = src->log_timestamp; mosquitto__free(dest->log_timestamp_format); dest->log_timestamp_format = src->log_timestamp_format; mosquitto__free(dest->log_file); dest->log_file = src->log_file; dest->message_size_limit = src->message_size_limit; dest->persistence = src->persistence; mosquitto__free(dest->persistence_location); dest->persistence_location = src->persistence_location; mosquitto__free(dest->persistence_file); dest->persistence_file = src->persistence_file; mosquitto__free(dest->persistence_filepath); dest->persistence_filepath = src->persistence_filepath; dest->persistent_client_expiration = src->persistent_client_expiration; dest->queue_qos0_messages = src->queue_qos0_messages; dest->sys_interval = src->sys_interval; dest->upgrade_outgoing_qos = src->upgrade_outgoing_qos; #ifdef WITH_WEBSOCKETS dest->websockets_log_level = src->websockets_log_level; #endif } int config__read(struct mosquitto_db *db, struct mosquitto__config *config, bool reload) { int rc = MOSQ_ERR_SUCCESS; struct config_recurse cr; int lineno = 0; #ifdef WITH_PERSISTENCE int len; #endif struct mosquitto__config config_reload; struct mosquitto__auth_plugin *plugin; int i, j; if(reload){ memset(&config_reload, 0, sizeof(struct mosquitto__config)); } cr.log_dest = MQTT3_LOG_NONE; cr.log_dest_set = 0; cr.log_type = MOSQ_LOG_NONE; cr.log_type_set = 0; cr.max_inflight_bytes = 0; cr.max_queued_bytes = 0; cr.max_queued_messages = 100; if(!db->config_file) return 0; if(reload){ /* Re-initialise appropriate config vars to default for reload. */ config__init_reload(db, &config_reload); config_reload.listeners = config->listeners; config_reload.listener_count = config->listener_count; cur_security_options = NULL; rc = config__read_file(&config_reload, reload, db->config_file, &cr, 0, &lineno); }else{ rc = config__read_file(config, reload, db->config_file, &cr, 0, &lineno); } if(rc){ if(lineno > 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", db->config_file, lineno); } return rc; } if(reload){ config__copy(&config_reload, config); } /* If auth/access options are set and allow_anonymous not explicitly set, disallow anon. */ if(config->per_listener_settings){ for(i=0; ilistener_count; i++){ if(config->listeners[i].security_options.allow_anonymous == -1){ /* Default option if no security options set */ config->listeners[i].security_options.allow_anonymous = true; if(config->listeners[i].security_options.password_file || config->listeners[i].security_options.psk_file){ /* allow_anonymous not set explicitly, some other security options * have been set - so disable allow_anonymous */ config->listeners[i].security_options.allow_anonymous = false; } /* Check plugins loaded to see if they have username/password checks enabled */ for(j=0; jlisteners[i].security_options.auth_plugin_config_count; j++){ plugin = &config->listeners[i].security_options.auth_plugin_configs[j].plugin; if(plugin->version == 3 || plugin->version == 2){ /* Version 2 and 3 always have username/password checks */ config->listeners[i].security_options.allow_anonymous = false; break; }else{ /* Version 4 has optional unpwd checks. */ if(plugin->unpwd_check_v4 != NULL){ config->listeners[i].security_options.allow_anonymous = false; break; } } } } } }else{ if(config->security_options.allow_anonymous == -1){ /* Default option if no security options set */ config->security_options.allow_anonymous = true; if(config->security_options.password_file || config->security_options.psk_file){ /* allow_anonymous not set explicitly, some other security options * have been set - so disable allow_anonymous */ config->security_options.allow_anonymous = false; } /* Check plugins loaded to see if they have username/password checks enabled */ for(j=0; jsecurity_options.auth_plugin_config_count; j++){ plugin = &config->security_options.auth_plugin_configs[j].plugin; if(plugin->version == 3 || plugin->version == 2){ /* Version 2 and 3 always have username/password checks */ config->security_options.allow_anonymous = false; break; }else{ /* Version 4 has optional unpwd checks. */ if(plugin->unpwd_check_v4 != NULL){ config->security_options.allow_anonymous = false; break; } } } } } #ifdef WITH_PERSISTENCE if(config->persistence){ if(!config->persistence_file){ config->persistence_file = mosquitto__strdup("mosquitto.db"); if(!config->persistence_file) return MOSQ_ERR_NOMEM; } mosquitto__free(config->persistence_filepath); if(config->persistence_location && strlen(config->persistence_location)){ len = strlen(config->persistence_location) + strlen(config->persistence_file) + 1; config->persistence_filepath = mosquitto__malloc(len); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; snprintf(config->persistence_filepath, len, "%s%s", config->persistence_location, config->persistence_file); }else{ config->persistence_filepath = mosquitto__strdup(config->persistence_file); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; } } #endif /* Default to drop to mosquitto user if no other user specified. This must * remain here even though it is covered in config__parse_args() because this * function may be called on its own. */ if(!config->user){ config->user = mosquitto__strdup("mosquitto"); } db__limits_set(cr.max_inflight_bytes, cr.max_queued_messages, cr.max_queued_bytes); #ifdef WITH_BRIDGE for(i=0; ibridge_count; i++){ if(!config->bridges[i].name || !config->bridges[i].addresses || !config->bridges[i].topic_count){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef FINAL_WITH_TLS_PSK if(config->bridges[i].tls_psk && !config->bridges[i].tls_psk_identity){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: missing bridge_identity."); return MOSQ_ERR_INVAL; } if(config->bridges[i].tls_psk_identity && !config->bridges[i].tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: missing bridge_psk."); return MOSQ_ERR_INVAL; } #endif } #endif if(cr.log_dest_set){ config->log_dest = cr.log_dest; } if(db->verbose){ config->log_type = UINT_MAX; }else if(cr.log_type_set){ config->log_type = cr.log_type; } return MOSQ_ERR_SUCCESS; } int config__read_file_core(struct mosquitto__config *config, bool reload, struct config_recurse *cr, int level, int *lineno, FILE *fptr, char **buf, int *buflen) { int rc; char *token; int tmp_int; char *saveptr = NULL; #ifdef WITH_BRIDGE char *tmp_char; struct mosquitto__bridge *cur_bridge = NULL; struct mosquitto__bridge_topic *cur_topic; int len; #endif struct mosquitto__auth_plugin_config *cur_auth_plugin_config = NULL; time_t expiration_mult; char *key; struct mosquitto__listener *cur_listener = &config->default_listener; int i; int lineno_ext = 0; *lineno = 0; while(fgets_extending(buf, buflen, fptr)){ (*lineno)++; if((*buf)[0] != '#' && (*buf)[0] != 10 && (*buf)[0] != 13){ while((*buf)[strlen((*buf))-1] == 10 || (*buf)[strlen((*buf))-1] == 13){ (*buf)[strlen((*buf))-1] = 0; } token = strtok_r((*buf), " ", &saveptr); if(token){ if(!strcmp(token, "acl_file")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->acl_file); cur_security_options->acl_file = NULL; } if(conf__parse_string(&token, "acl_file", &cur_security_options->acl_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "address") || !strcmp(token, "addresses")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge || cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } while((token = strtok_r(NULL, " ", &saveptr))){ if (token[0] == '#'){ break; } cur_bridge->address_count++; cur_bridge->addresses = mosquitto__realloc(cur_bridge->addresses, sizeof(struct bridge_address)*cur_bridge->address_count); if(!cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->addresses[cur_bridge->address_count-1].address = token; } for(i=0; iaddress_count; i++){ /* cur_bridge->addresses[i].address is now * "address[:port]". If address is an IPv6 address, * then port is required. We must check for the : * backwards. */ tmp_char = strrchr(cur_bridge->addresses[i].address, ':'); if(tmp_char){ /* Remove ':', so cur_bridge->addresses[i].address * now just looks like the address. */ tmp_char[0] = '\0'; /* The remainder of the string */ tmp_int = atoi(&tmp_char[1]); if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } cur_bridge->addresses[i].port = tmp_int; }else{ cur_bridge->addresses[i].port = 1883; } /* This looks a bit weird, but isn't. Before this * call, cur_bridge->addresses[i].address points * to the tokenised part of the line, it will be * reused in a future parse of a config line so we * must duplicate it. */ cur_bridge->addresses[i].address = mosquitto__strdup(cur_bridge->addresses[i].address); conf__attempt_resolve(cur_bridge->addresses[i].address, "bridge address", MOSQ_LOG_WARNING, "Warning"); } if(cur_bridge->address_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty address value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "allow_anonymous")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "allow_anonymous", (bool *)&cur_security_options->allow_anonymous, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "allow_duplicate_messages")){ if(conf__parse_bool(&token, "allow_duplicate_messages", &config->allow_duplicate_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "allow_zero_length_clientid")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "allow_zero_length_clientid", &cur_security_options->allow_zero_length_clientid, saveptr)) return MOSQ_ERR_INVAL; }else if(!strncmp(token, "auth_opt_", 9)){ if(reload) continue; // Auth plugin not currently valid for reloading. if(!cur_auth_plugin_config){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_opt_ option exists in the config file without an auth_plugin."); return MOSQ_ERR_INVAL; } if(strlen(token) < 12){ /* auth_opt_ == 9, + one digit key == 10, + one space == 11, + one value == 12 */ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid auth_opt_ config option."); return MOSQ_ERR_INVAL; } key = mosquitto__strdup(&token[9]); if(!key){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; }else if(STREMPTY(key)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid auth_opt_ config option."); mosquitto__free(key); return MOSQ_ERR_INVAL; } token += 9+strlen(key)+1; while(token[0] == ' ' || token[0] == '\t'){ token++; } if(token[0]){ cur_auth_plugin_config->option_count++; cur_auth_plugin_config->options = mosquitto__realloc(cur_auth_plugin_config->options, cur_auth_plugin_config->option_count*sizeof(struct mosquitto_auth_opt)); if(!cur_auth_plugin_config->options){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); mosquitto__free(key); return MOSQ_ERR_NOMEM; } cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].key = key; cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].value = mosquitto__strdup(token); if(!cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", key); mosquitto__free(key); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "auth_plugin")){ if(reload) continue; // Auth plugin not currently valid for reloading. conf__set_cur_security_options(config, cur_listener, &cur_security_options); cur_security_options->auth_plugin_configs = mosquitto__realloc(cur_security_options->auth_plugin_configs, (cur_security_options->auth_plugin_config_count+1)*sizeof(struct mosquitto__auth_plugin_config)); if(!cur_security_options->auth_plugin_configs){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_auth_plugin_config = &cur_security_options->auth_plugin_configs[cur_security_options->auth_plugin_config_count]; memset(cur_auth_plugin_config, 0, sizeof(struct mosquitto__auth_plugin_config)); cur_auth_plugin_config->path = NULL; cur_auth_plugin_config->options = NULL; cur_auth_plugin_config->option_count = 0; cur_auth_plugin_config->deny_special_chars = true; cur_security_options->auth_plugin_config_count++; if(conf__parse_string(&token, "auth_plugin", &cur_auth_plugin_config->path, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "auth_plugin_deny_special_chars")){ if(reload) continue; // Auth plugin not currently valid for reloading. if(!cur_auth_plugin_config){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_plugin_deny_special_chars option exists in the config file without an auth_plugin."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "auth_plugin_deny_special_chars", &cur_auth_plugin_config->deny_special_chars, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "auto_id_prefix")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_string(&token, "auto_id_prefix", &cur_security_options->auto_id_prefix, saveptr)) return MOSQ_ERR_INVAL; if(cur_security_options->auto_id_prefix){ cur_security_options->auto_id_prefix_len = strlen(cur_security_options->auto_id_prefix); }else{ cur_security_options->auto_id_prefix_len = 0; } }else if(!strcmp(token, "autosave_interval")){ if(conf__parse_int(&token, "autosave_interval", &config->autosave_interval, saveptr)) return MOSQ_ERR_INVAL; if(config->autosave_interval < 0) config->autosave_interval = 0; }else if(!strcmp(token, "autosave_on_changes")){ if(conf__parse_bool(&token, "autosave_on_changes", &config->autosave_on_changes, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "bind_address")){ if(reload) continue; // Listener not valid for reloading. if(conf__parse_string(&token, "default listener bind_address", &config->default_listener.host, saveptr)) return MOSQ_ERR_INVAL; if(conf__attempt_resolve(config->default_listener.host, "bind_address", MOSQ_LOG_ERR, "Error")){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "bind_interface")){ #ifdef SO_BINDTODEVICE if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "bind_interface", &cur_listener->bind_interface, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_ERR, "Error: bind_interface specified but socket option not available."); return MOSQ_ERR_INVAL; #endif }else if(!strcmp(token, "bridge_attempt_unsubscribe")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_attempt_unsubscribe", &cur_bridge->attempt_unsubscribe, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_cafile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef FINAL_WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_cafile", &cur_bridge->tls_cafile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_alpn")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_alpn", &cur_bridge->tls_alpn, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_capath")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef FINAL_WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_capath", &cur_bridge->tls_capath, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_certfile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef FINAL_WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_certfile", &cur_bridge->tls_certfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_identity")){ #if defined(WITH_BRIDGE) && defined(FINAL_WITH_TLS_PSK) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and identity encryption in a single bridge."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_identity", &cur_bridge->tls_psk_identity, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_insecure")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_insecure", &cur_bridge->tls_insecure, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->tls_insecure){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge %s using insecure mode.", cur_bridge->name); } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_require_ocsp")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_require_ocsp", &cur_bridge->tls_ocsp_required, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "bridge_keyfile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef FINAL_WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_keyfile", &cur_bridge->tls_keyfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_protocol_version")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, "", &saveptr); if(token){ if(!strcmp(token, "mqttv31")){ cur_bridge->protocol_version = mosq_p_mqtt31; }else if(!strcmp(token, "mqttv311")){ cur_bridge->protocol_version = mosq_p_mqtt311; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge_protocol_version value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty bridge_protocol_version value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_psk")){ #if defined(WITH_BRIDGE) && defined(FINAL_WITH_TLS_PSK) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_psk", &cur_bridge->tls_psk, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_tls_version")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_tls_version", &cur_bridge->tls_version, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "cafile")){ #if defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(cur_listener->psk_hint){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "cafile", &cur_listener->cafile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "capath")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "capath", &cur_listener->capath, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "certfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(cur_listener->psk_hint){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "certfile", &cur_listener->certfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "check_retain_source")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "check_retain_source", &config->check_retain_source, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "ciphers")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "ciphers", &cur_listener->ciphers, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "clientid") || !strcmp(token, "remote_clientid")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote clientid", &cur_bridge->remote_clientid, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "cleansession")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "cleansession", &cur_bridge->clean_start, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "clientid_prefixes")){ if(reload){ mosquitto__free(config->clientid_prefixes); config->clientid_prefixes = NULL; } if(conf__parse_string(&token, "clientid_prefixes", &config->clientid_prefixes, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "connection")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME token = strtok_r(NULL, " ", &saveptr); if(token){ /* Check for existing bridge name. */ for(i=0; ibridge_count; i++){ if(!strcmp(config->bridges[i].name, token)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate bridge name \"%s\".", token); return MOSQ_ERR_INVAL; } } config->bridge_count++; config->bridges = mosquitto__realloc(config->bridges, config->bridge_count*sizeof(struct mosquitto__bridge)); if(!config->bridges){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge = &(config->bridges[config->bridge_count-1]); memset(cur_bridge, 0, sizeof(struct mosquitto__bridge)); cur_bridge->name = mosquitto__strdup(token); if(!cur_bridge->name){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->keepalive = 60; cur_bridge->notifications = true; cur_bridge->notifications_local_only = false; cur_bridge->start_type = bst_automatic; cur_bridge->idle_timeout = 60; cur_bridge->restart_timeout = 0; cur_bridge->backoff_base = 5; cur_bridge->backoff_cap = 30; cur_bridge->threshold = 10; cur_bridge->try_private = true; cur_bridge->attempt_unsubscribe = true; cur_bridge->protocol_version = mosq_p_mqtt311; cur_bridge->primary_retry_sock = INVALID_SOCKET; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty connection value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "connection_messages")){ if(conf__parse_bool(&token, token, &config->connection_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "crlfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "crlfile", &cur_listener->crlfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "dhparamfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "dhparamfile", &cur_listener->dhparamfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "http_dir")){ #ifdef WITH_WEBSOCKETS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "http_dir", &cur_listener->http_dir, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "idle_timeout")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "idle_timeout", &cur_bridge->idle_timeout, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->idle_timeout < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "idle_timeout interval too low, using 1 second."); cur_bridge->idle_timeout = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "include_dir")){ if(level == 0){ /* Only process include_dir from the main config file. */ token = strtok_r(NULL, "", &saveptr); if(!token){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty include_dir value in configuration."); return 1; } char **files; int file_count; rc = config__get_dir_files(token, &files, &file_count); if(rc) return rc; for(i=0; i 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", files[i], lineno_ext); } /* Free happens below */ break; } } for(i=0; ikeepalive, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->keepalive < 5){ log__printf(NULL, MOSQ_LOG_NOTICE, "keepalive interval too low, using 5 seconds."); cur_bridge->keepalive = 5; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "keyfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "keyfile", &cur_listener->keyfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "listener")){ token = strtok_r(NULL, " ", &saveptr); if(token){ tmp_int = atoi(token); if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } if(reload){ /* We reload listeners settings based on port number. * If the port number doesn't already exist, exit with a complaint. */ cur_listener = NULL; for(i=0; ilistener_count; i++){ if(config->listeners[i].port == tmp_int){ cur_listener = &config->listeners[i]; } } if(!cur_listener){ log__printf(NULL, MOSQ_LOG_ERR, "Error: It is not currently possible to add/remove listeners when reloading the config file."); return MOSQ_ERR_INVAL; } }else{ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_listener = &config->listeners[config->listener_count-1]; memset(cur_listener, 0, sizeof(struct mosquitto__listener)); } cur_listener->security_options.allow_anonymous = -1; cur_listener->security_options.allow_zero_length_clientid = true; cur_listener->protocol = mp_mqtt; cur_listener->port = tmp_int; cur_listener->maximum_qos = 2; cur_listener->max_topic_alias = 10; token = strtok_r(NULL, " ", &saveptr); if (token != NULL && token[0] == '#'){ token = NULL; } mosquitto__free(cur_listener->host); if(token){ cur_listener->host = mosquitto__strdup(token); }else{ cur_listener->host = NULL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty listener value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "local_clientid")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local clientd", &cur_bridge->local_clientid, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "local_password")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local_password", &cur_bridge->local_password, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "local_username")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local_username", &cur_bridge->local_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "log_dest")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->log_dest_set = 1; if(!strcmp(token, "none")){ cr->log_dest = MQTT3_LOG_NONE; }else if(!strcmp(token, "syslog")){ cr->log_dest |= MQTT3_LOG_SYSLOG; }else if(!strcmp(token, "stdout")){ cr->log_dest |= MQTT3_LOG_STDOUT; }else if(!strcmp(token, "stderr")){ cr->log_dest |= MQTT3_LOG_STDERR; }else if(!strcmp(token, "topic")){ cr->log_dest |= MQTT3_LOG_TOPIC; }else if(!strcmp(token, "file")){ cr->log_dest |= MQTT3_LOG_FILE; if(config->log_fptr || config->log_file){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate \"log_dest file\" value."); return MOSQ_ERR_INVAL; } /* Get remaining string. */ token = &token[strlen(token)+1]; while(token[0] == ' ' || token[0] == '\t'){ token++; } if(token[0]){ config->log_file = mosquitto__strdup(token); if(!config->log_file){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty \"log_dest file\" value in configuration."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_dest value (%s).", token); return MOSQ_ERR_INVAL; } #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ if(cr->log_dest == MQTT3_LOG_STDOUT || cr->log_dest == MQTT3_LOG_STDERR){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot log to stdout/stderr when running as a Windows service."); return MOSQ_ERR_INVAL; } } #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty log_dest value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "log_facility")){ #if defined(WIN32) || defined(__CYGWIN__) log__printf(NULL, MOSQ_LOG_WARNING, "Warning: log_facility not supported on Windows."); #else if(conf__parse_int(&token, "log_facility", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; switch(tmp_int){ case 0: config->log_facility = LOG_LOCAL0; break; case 1: config->log_facility = LOG_LOCAL1; break; case 2: config->log_facility = LOG_LOCAL2; break; case 3: config->log_facility = LOG_LOCAL3; break; case 4: config->log_facility = LOG_LOCAL4; break; case 5: config->log_facility = LOG_LOCAL5; break; case 6: config->log_facility = LOG_LOCAL6; break; case 7: config->log_facility = LOG_LOCAL7; break; default: log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_facility value (%d).", tmp_int); return MOSQ_ERR_INVAL; } #endif }else if(!strcmp(token, "log_timestamp")){ if(conf__parse_bool(&token, token, &config->log_timestamp, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "log_timestamp_format")){ if(conf__parse_string(&token, token, &config->log_timestamp_format, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "log_type")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->log_type_set = 1; if(!strcmp(token, "none")){ cr->log_type = MOSQ_LOG_NONE; }else if(!strcmp(token, "information")){ cr->log_type |= MOSQ_LOG_INFO; }else if(!strcmp(token, "notice")){ cr->log_type |= MOSQ_LOG_NOTICE; }else if(!strcmp(token, "warning")){ cr->log_type |= MOSQ_LOG_WARNING; }else if(!strcmp(token, "error")){ cr->log_type |= MOSQ_LOG_ERR; }else if(!strcmp(token, "debug")){ cr->log_type |= MOSQ_LOG_DEBUG; }else if(!strcmp(token, "subscribe")){ cr->log_type |= MOSQ_LOG_SUBSCRIBE; }else if(!strcmp(token, "unsubscribe")){ cr->log_type |= MOSQ_LOG_UNSUBSCRIBE; }else if(!strcmp(token, "internal")){ cr->log_type |= MOSQ_LOG_INTERNAL; #ifdef WITH_WEBSOCKETS }else if(!strcmp(token, "websockets")){ cr->log_type |= MOSQ_LOG_WEBSOCKETS; #endif }else if(!strcmp(token, "all")){ cr->log_type = MOSQ_LOG_ALL; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_type value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty log_type value in configuration."); } }else if(!strcmp(token, "max_connections")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ cur_listener->max_connections = atoi(token); if(cur_listener->max_connections < 0) cur_listener->max_connections = -1; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_connections value in configuration."); } }else if(!strcmp(token, "maximum_qos")){ if(reload) continue; // Listeners not valid for reloading. if(conf__parse_int(&token, "maximum_qos", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0 || tmp_int > 2){ log__printf(NULL, MOSQ_LOG_ERR, "Error: maximum_qos must be between 0 and 2 inclusive."); return MOSQ_ERR_INVAL; } cur_listener->maximum_qos = tmp_int; }else if(!strcmp(token, "max_inflight_bytes")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_inflight_bytes = atol(token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_inflight_bytes value in configuration."); } }else if(!strcmp(token, "max_inflight_messages")){ if(conf__parse_int(&token, "max_inflight_messages", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0 || tmp_int == 65535){ tmp_int = 0; }else if(tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: max_inflight_messages must be <= 65535."); return MOSQ_ERR_INVAL; } config->max_inflight_messages = tmp_int; }else if(!strcmp(token, "max_keepalive")){ if(conf__parse_int(&token, "max_keepalive", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 10 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid max_keepalive value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->max_keepalive = tmp_int; }else if(!strcmp(token, "max_packet_size")){ if(conf__parse_int(&token, "max_packet_size", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 20){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid max_packet_size value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->max_packet_size = tmp_int; }else if(!strcmp(token, "max_queued_bytes")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_queued_bytes = atol(token); /* 63 bits is ok right? */ }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_queued_bytes value in configuration."); } }else if(!strcmp(token, "max_queued_messages")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_queued_messages = atoi(token); if(cr->max_queued_messages < 0) cr->max_queued_messages = 0; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_queued_messages value in configuration."); } }else if(!strcmp(token, "memory_limit")){ ssize_t lim; if(conf__parse_ssize_t(&token, "memory_limit", &lim, saveptr)) return MOSQ_ERR_INVAL; if(lim < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid memory_limit value (%ld).", lim); return MOSQ_ERR_INVAL; } memory__set_limit(lim); }else if(!strcmp(token, "message_size_limit")){ if(conf__parse_int(&token, "message_size_limit", (int *)&config->message_size_limit, saveptr)) return MOSQ_ERR_INVAL; if(config->message_size_limit > MQTT_MAX_PAYLOAD){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid message_size_limit value (%u).", config->message_size_limit); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "mount_point")){ if(reload) continue; // Listeners not valid for reloading. if(config->listener_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: You must use create a listener before using the mount_point option in the configuration file."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "mount_point", &cur_listener->mount_point, saveptr)) return MOSQ_ERR_INVAL; if(mosquitto_pub_topic_check(cur_listener->mount_point) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid mount_point '%s'. Does it contain a wildcard character?", cur_listener->mount_point); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "notifications")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "notifications", &cur_bridge->notifications, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "notifications_local_only")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration"); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "notifications_local_only", &cur_bridge->notifications_local_only, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "notification_topic")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "notification_topic", &cur_bridge->notification_topic, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "password") || !strcmp(token, "remote_password")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote_password", &cur_bridge->remote_password, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "password_file")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->password_file); cur_security_options->password_file = NULL; } if(conf__parse_string(&token, "password_file", &cur_security_options->password_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "per_listener_settings")){ if(conf__parse_bool(&token, "per_listener_settings", &config->per_listener_settings, saveptr)) return MOSQ_ERR_INVAL; if(cur_security_options && config->per_listener_settings){ log__printf(NULL, MOSQ_LOG_ERR, "Error: per_listener_settings must be set before any other security settings."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "persistence") || !strcmp(token, "retained_persistence")){ if(conf__parse_bool(&token, token, &config->persistence, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistence_file")){ if(conf__parse_string(&token, "persistence_file", &config->persistence_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistence_location")){ if(conf__parse_string(&token, "persistence_location", &config->persistence_location, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistent_client_expiration")){ token = strtok_r(NULL, " ", &saveptr); if(token){ switch(token[strlen(token)-1]){ case 'h': expiration_mult = 3600; break; case 'd': expiration_mult = 86400; break; case 'w': expiration_mult = 86400*7; break; case 'm': expiration_mult = 86400*30; break; case 'y': expiration_mult = 86400*365; break; default: log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid persistent_client_expiration duration in configuration."); return MOSQ_ERR_INVAL; } token[strlen(token)-1] = '\0'; config->persistent_client_expiration = atoi(token)*expiration_mult; if(config->persistent_client_expiration <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid persistent_client_expiration duration in configuration."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty persistent_client_expiration value in configuration."); } }else if(!strcmp(token, "pid_file")){ if(reload) continue; // pid file not valid for reloading. if(conf__parse_string(&token, "pid_file", &config->pid_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "port")){ if(reload) continue; // Listener not valid for reloading. if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } if(conf__parse_int(&token, "port", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->default_listener.port = tmp_int; }else if(!strcmp(token, "protocol")){ token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "mqtt")){ cur_listener->protocol = mp_mqtt; /* }else if(!strcmp(token, "mqttsn")){ cur_listener->protocol = mp_mqttsn; */ }else if(!strcmp(token, "websockets")){ #ifdef WITH_WEBSOCKETS cur_listener->protocol = mp_websockets; config->have_websockets_listener = true; #else log__printf(NULL, MOSQ_LOG_ERR, "Error: Websockets support not available."); return MOSQ_ERR_INVAL; #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid protocol value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty protocol value in configuration."); } }else if(!strcmp(token, "psk_file")){ #ifdef FINAL_WITH_TLS_PSK conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->psk_file); cur_security_options->psk_file = NULL; } if(conf__parse_string(&token, "psk_file", &cur_security_options->psk_file, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS/TLS-PSK support not available."); #endif }else if(!strcmp(token, "psk_hint")){ #ifdef FINAL_WITH_TLS_PSK if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "psk_hint", &cur_listener->psk_hint, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS/TLS-PSK support not available."); #endif }else if(!strcmp(token, "queue_qos0_messages")){ if(conf__parse_bool(&token, token, &config->queue_qos0_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "require_certificate")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "require_certificate", &cur_listener->require_certificate, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "restart_timeout")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(!token){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty restart_timeout value in configuration."); return MOSQ_ERR_INVAL; } cur_bridge->restart_timeout = atoi(token); if(cur_bridge->restart_timeout < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "restart_timeout interval too low, using 1 second."); cur_bridge->restart_timeout = 1; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->backoff_base = cur_bridge->restart_timeout; cur_bridge->backoff_cap = atoi(token); if(cur_bridge->backoff_cap < cur_bridge->backoff_base){ log__printf(NULL, MOSQ_LOG_ERR, "Error: backoff cap is lower than the base in restart_timeout."); return MOSQ_ERR_INVAL; } } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "retain_available")){ if(conf__parse_bool(&token, token, &config->retain_available, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "retry_interval")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: The retry_interval option is no longer available."); }else if(!strcmp(token, "round_robin")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "round_robin", &cur_bridge->round_robin, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "set_tcp_nodelay")){ if(conf__parse_bool(&token, "set_tcp_nodelay", &config->set_tcp_nodelay, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "start_type")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "automatic")){ cur_bridge->start_type = bst_automatic; }else if(!strcmp(token, "lazy")){ cur_bridge->start_type = bst_lazy; }else if(!strcmp(token, "manual")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Manual start_type not supported."); return MOSQ_ERR_INVAL; }else if(!strcmp(token, "once")){ cur_bridge->start_type = bst_once; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid start_type value in configuration (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty start_type value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "socket_domain")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "ipv4")){ cur_listener->socket_domain = AF_INET; }else if(!strcmp(token, "ipv6")){ cur_listener->socket_domain = AF_INET6; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid socket_domain value \"%s\" in configuration.", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty socket_domain value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "store_clean_interval")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: store_clean_interval is no longer needed."); }else if(!strcmp(token, "sys_interval")){ if(conf__parse_int(&token, "sys_interval", &config->sys_interval, saveptr)) return MOSQ_ERR_INVAL; if(config->sys_interval < 0 || config->sys_interval > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid sys_interval value (%d).", config->sys_interval); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "threshold")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "threshold", &cur_bridge->threshold, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->threshold < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "threshold too low, using 1 message."); cur_bridge->threshold = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "tls_engine")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "tls_engine", &cur_listener->tls_engine, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "tls_engine_kpass_sha1")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. char *kpass_sha = NULL, *kpass_sha_bin = NULL; if(conf__parse_string(&token, "tls_engine_kpass_sha1", &kpass_sha, saveptr)) return MOSQ_ERR_INVAL; if(mosquitto__hex2bin_sha1(kpass_sha, (unsigned char**)&kpass_sha_bin) != MOSQ_ERR_SUCCESS){ mosquitto__free(kpass_sha); return MOSQ_ERR_INVAL; } cur_listener->tls_engine_kpass_sha1 = kpass_sha_bin; mosquitto__free(kpass_sha); #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "tls_keyform")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. char *keyform = NULL; if(conf__parse_string(&token, "tls_keyform", &keyform, saveptr)) return MOSQ_ERR_INVAL; cur_listener->tls_keyform = mosq_k_pem; if(!strcmp(keyform, "engine")) cur_listener->tls_keyform = mosq_k_engine; mosquitto__free(keyform); #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "tls_version")){ #if defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "tls_version", &cur_listener->tls_version, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "topic")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->topic_count++; cur_bridge->topics = mosquitto__realloc(cur_bridge->topics, sizeof(struct mosquitto__bridge_topic)*cur_bridge->topic_count); if(!cur_bridge->topics){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_topic = &cur_bridge->topics[cur_bridge->topic_count-1]; if(!strcmp(token, "\"\"")){ cur_topic->topic = NULL; }else{ cur_topic->topic = mosquitto__strdup(token); if(!cur_topic->topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } cur_topic->direction = bd_out; cur_topic->qos = 0; cur_topic->local_prefix = NULL; cur_topic->remote_prefix = NULL; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty topic value in configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcasecmp(token, "out")){ cur_topic->direction = bd_out; }else if(!strcasecmp(token, "in")){ cur_topic->direction = bd_in; }else if(!strcasecmp(token, "both")){ cur_topic->direction = bd_both; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic direction '%s'.", token); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if (token[0] == '#'){ strtok_r(NULL, "", &saveptr); } cur_topic->qos = atoi(token); if(cur_topic->qos < 0 || cur_topic->qos > 2){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge QoS level '%s'.", token); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->topic_remapping = true; if(!strcmp(token, "\"\"") || token[0] == '#'){ cur_topic->local_prefix = NULL; if (token[0] == '#'){ strtok_r(NULL, "", &saveptr); } }else{ if(mosquitto_pub_topic_check(token) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic local prefix '%s'.", token); return MOSQ_ERR_INVAL; } cur_topic->local_prefix = mosquitto__strdup(token); if(!cur_topic->local_prefix){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "\"\"") || token[0] == '#'){ cur_topic->remote_prefix = NULL; }else{ if(mosquitto_pub_topic_check(token) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic remote prefix '%s'.", token); return MOSQ_ERR_INVAL; } cur_topic->remote_prefix = mosquitto__strdup(token); if(!cur_topic->remote_prefix){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } } } } } if(cur_topic->topic == NULL && (cur_topic->local_prefix == NULL || cur_topic->remote_prefix == NULL)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge remapping."); return MOSQ_ERR_INVAL; } if(cur_topic->local_prefix){ if(cur_topic->topic){ len = strlen(cur_topic->topic) + strlen(cur_topic->local_prefix)+1; cur_topic->local_topic = mosquitto__malloc(len+1); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(cur_topic->local_topic, len+1, "%s%s", cur_topic->local_prefix, cur_topic->topic); cur_topic->local_topic[len] = '\0'; }else{ cur_topic->local_topic = mosquitto__strdup(cur_topic->local_prefix); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ cur_topic->local_topic = mosquitto__strdup(cur_topic->topic); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } if(cur_topic->remote_prefix){ if(cur_topic->topic){ len = strlen(cur_topic->topic) + strlen(cur_topic->remote_prefix)+1; cur_topic->remote_topic = mosquitto__malloc(len+1); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(cur_topic->remote_topic, len, "%s%s", cur_topic->remote_prefix, cur_topic->topic); cur_topic->remote_topic[len] = '\0'; }else{ cur_topic->remote_topic = mosquitto__strdup(cur_topic->remote_prefix); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ cur_topic->remote_topic = mosquitto__strdup(cur_topic->topic); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "max_topic_alias")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ cur_listener->max_topic_alias = atoi(token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_topic_alias value in configuration."); } }else if(!strcmp(token, "try_private")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "try_private", &cur_bridge->try_private, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "upgrade_outgoing_qos")){ if(conf__parse_bool(&token, token, &config->upgrade_outgoing_qos, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "use_identity_as_username")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_identity_as_username", &cur_listener->use_identity_as_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "use_subject_as_username")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_subject_as_username", &cur_listener->use_subject_as_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "user")){ if(reload) continue; // Drop privileges user not valid for reloading. mosquitto__free(config->user); if(conf__parse_string(&token, "user", &config->user, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "use_username_as_clientid")){ if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_username_as_clientid", &cur_listener->use_username_as_clientid, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "username") || !strcmp(token, "remote_username")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote_username", &cur_bridge->remote_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "websockets_log_level")){ #ifdef WITH_WEBSOCKETS if(conf__parse_int(&token, "websockets_log_level", &config->websockets_log_level, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "websockets_headers_size")){ #ifdef WITH_WEBSOCKETS # if defined(LWS_LIBRARY_VERSION_NUMBER) && LWS_LIBRARY_VERSION_NUMBER>=1007000 if(conf__parse_int(&token, "websockets_headers_size", &config->websockets_headers_size, saveptr)) return MOSQ_ERR_INVAL; # else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets headers size require libwebsocket 1.7+"); # endif #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "trace_level") || !strcmp(token, "ffdc_output") || !strcmp(token, "max_log_entries") || !strcmp(token, "trace_output")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unsupported rsmb configuration option \"%s\".", token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unknown configuration variable \"%s\".", token); return MOSQ_ERR_INVAL; } } } } return MOSQ_ERR_SUCCESS; } int config__read_file(struct mosquitto__config *config, bool reload, const char *file, struct config_recurse *cr, int level, int *lineno) { int rc; FILE *fptr = NULL; char *buf; int buflen; fptr = mosquitto__fopen(file, "rt", false); if(!fptr){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open config file %s.", file); return 1; } buflen = 1000; buf = mosquitto__malloc(buflen); if(!buf){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); fclose(fptr); return MOSQ_ERR_NOMEM; } rc = config__read_file_core(config, reload, cr, level, lineno, fptr, &buf, &buflen); mosquitto__free(buf); fclose(fptr); return rc; } static int config__check(struct mosquitto__config *config) { /* Checks that are easy to make after the config has been loaded. */ int i; #ifdef WITH_BRIDGE int j; struct mosquitto__bridge *bridge1, *bridge2; char hostname[256]; int len; /* Check for bridge duplicate local_clientid, need to generate missing IDs * first. */ for(i=0; ibridge_count; i++){ bridge1 = &config->bridges[i]; if(!bridge1->remote_clientid){ if(!gethostname(hostname, 256)){ len = strlen(hostname) + strlen(bridge1->name) + 2; bridge1->remote_clientid = mosquitto__malloc(len); if(!bridge1->remote_clientid){ return MOSQ_ERR_NOMEM; } snprintf(bridge1->remote_clientid, len, "%s.%s", hostname, bridge1->name); }else{ return 1; } } if(!bridge1->local_clientid){ len = strlen(bridge1->remote_clientid) + strlen("local.") + 2; bridge1->local_clientid = mosquitto__malloc(len); if(!bridge1->local_clientid){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(bridge1->local_clientid, len, "local.%s", bridge1->remote_clientid); } } for(i=0; ibridge_count; i++){ bridge1 = &config->bridges[i]; for(j=i+1; jbridge_count; j++){ bridge2 = &config->bridges[j]; if(!strcmp(bridge1->local_clientid, bridge2->local_clientid)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Bridge local_clientid " "'%s' is not unique. Try changing or setting the " "local_clientid value for one of the bridges.", bridge1->local_clientid); return MOSQ_ERR_INVAL; } } } #endif /* Default to auto_id_prefix = 'auto-' if none set. */ if(config->per_listener_settings){ for(i=0; ilistener_count; i++){ if(!config->listeners[i].security_options.auto_id_prefix){ config->listeners[i].security_options.auto_id_prefix = mosquitto__strdup("auto-"); if(!config->listeners[i].security_options.auto_id_prefix){ return MOSQ_ERR_NOMEM; } config->listeners[i].security_options.auto_id_prefix_len = strlen("auto-"); } } }else{ if(!config->security_options.auto_id_prefix){ config->security_options.auto_id_prefix = mosquitto__strdup("auto-"); if(!config->security_options.auto_id_prefix){ return MOSQ_ERR_NOMEM; } config->security_options.auto_id_prefix_len = strlen("auto-"); } } return MOSQ_ERR_SUCCESS; } static int conf__parse_bool(char **token, const char *name, bool *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ if(!strcmp(*token, "false") || !strcmp(*token, "0")){ *value = false; }else if(!strcmp(*token, "true") || !strcmp(*token, "1")){ *value = true; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid %s value (%s).", name, *token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_int(char **token, const char *name, int *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ *value = atoi(*token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_ssize_t(char **token, const char *name, ssize_t *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ *value = atol(*token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_string(char **token, const char *name, char **value, char *saveptr) { *token = strtok_r(NULL, "", &saveptr); if(*token){ if(*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate %s value in configuration.", name); return MOSQ_ERR_INVAL; } /* Deal with multiple spaces at the beginning of the string. */ *token = misc__trimblanks(*token); if(strlen(*token) == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(*token, strlen(*token))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Malformed UTF-8 in configuration."); return MOSQ_ERR_INVAL; } *value = mosquitto__strdup(*token); if(!*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/src/send_unsuback.c0000664000175000017500000000316313626052637016407 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" int send__unsuback(struct mosquitto *mosq, uint16_t mid, int reason_code_count, uint8_t *reason_codes, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; int rc; int proplen, varbytes; assert(mosq); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = CMD_UNSUBACK; packet->remaining_length = 2; if(mosq->protocol == mosq_p_mqtt5){ proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); packet->remaining_length += varbytes + proplen + reason_code_count; } rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } packet__write_uint16(packet, mid); if(mosq->protocol == mosq_p_mqtt5){ property__write_all(packet, properties, true); packet__write_bytes(packet, reason_codes, reason_code_count); } return packet__queue(mosq, packet); } mosquitto-1.6.9/src/websockets.c0000664000175000017500000005204313626052637015735 0ustar rogerroger/* Copyright (c) 2014-2020 Roger Light All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of mosquitto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef WITH_WEBSOCKETS #include "config.h" #include #include "mosquitto_internal.h" #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "sys_tree.h" #include "util_mosq.h" #include #include #include #ifndef WIN32 # include #endif /* Be careful if changing these, if TX is not bigger than SERV then there can * be very large write performance penalties. */ #define WS_SERV_BUF_SIZE 4096 #define WS_TX_BUF_SIZE (WS_SERV_BUF_SIZE*2) extern struct mosquitto_db int_db; #if defined(LWS_LIBRARY_VERSION_NUMBER) static int callback_mqtt( #else static int callback_mqtt(struct libwebsocket_context *context, #endif struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len); #if defined(LWS_LIBRARY_VERSION_NUMBER) static int callback_http( #else static int callback_http(struct libwebsocket_context *context, #endif struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len); enum mosq_ws_protocols { PROTOCOL_HTTP = 0, PROTOCOL_MQTT, DEMO_PROTOCOL_COUNT }; struct libws_http_data { FILE *fptr; }; static struct libwebsocket_protocols protocols[] = { /* first protocol must always be HTTP handler */ { "http-only", /* name */ callback_http, /* lws_callback_function */ sizeof (struct libws_http_data), /* per_session_data_size */ 0, /* rx_buffer_size */ #ifndef LWS_LIBRARY_VERSION_NUMBER 0, /* no_buffer_all_partial_tx v1.3 only */ #endif #ifdef LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD 0, /* id */ #endif #ifdef LWS_LIBRARY_VERSION_NUMBER NULL, /* user v1.4 on */ # if LWS_LIBRARY_VERSION_NUMBER >= 2003000 WS_TX_BUF_SIZE /* tx_packet_size v2.3.0 */ # endif #endif }, { "mqtt", callback_mqtt, sizeof(struct libws_mqtt_data), 0, /* rx_buffer_size */ #ifndef LWS_LIBRARY_VERSION_NUMBER 0, /* no_buffer_all_partial_tx v1.3 only */ #endif #ifdef LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD 1, /* id */ #endif #ifdef LWS_LIBRARY_VERSION_NUMBER NULL, /* user v1.4 on */ # if LWS_LIBRARY_VERSION_NUMBER >= 2003000 WS_TX_BUF_SIZE /* tx_packet_size v2.3.0 */ # endif #endif }, { "mqttv3.1", callback_mqtt, sizeof(struct libws_mqtt_data), 0, /* rx_buffer_size */ #ifndef LWS_LIBRARY_VERSION_NUMBER 0, /* no_buffer_all_partial_tx v1.3 only */ #endif #ifdef LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD 2, /* id */ #endif #ifdef LWS_LIBRARY_VERSION_NUMBER NULL, /* user v1.4 on */ # if LWS_LIBRARY_VERSION_NUMBER >= 2003000 WS_TX_BUF_SIZE /* tx_packet_size v2.3.0 */ # endif #endif }, { NULL, NULL, 0, 0, /* rx_buffer_size */ #ifndef LWS_LIBRARY_VERSION_NUMBER 0, /* no_buffer_all_partial_tx v1.3 only */ #endif #ifdef LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD 0, /* id */ #endif #ifdef LWS_LIBRARY_VERSION_NUMBER NULL, /* user v1.4 on */ # if LWS_LIBRARY_VERSION_NUMBER >= 2003000 0 /* tx_packet_size v2.3.0 */ # endif #endif } }; static void easy_address(int sock, struct mosquitto *mosq) { char address[1024]; if(!net__socket_get_address(sock, address, 1024)){ mosq->address = mosquitto__strdup(address); } } #if defined(LWS_LIBRARY_VERSION_NUMBER) static int callback_mqtt( #else static int callback_mqtt(struct libwebsocket_context *context, #endif struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { struct mosquitto_db *db; struct mosquitto *mosq = NULL; struct mosquitto__packet *packet; size_t txlen; int count; const struct libwebsocket_protocols *p; struct libws_mqtt_data *u = (struct libws_mqtt_data *)user; size_t pos; uint8_t *buf; int rc; uint8_t byte; db = &int_db; switch (reason) { case LWS_CALLBACK_ESTABLISHED: mosq = context__init(db, WEBSOCKET_CLIENT); if(mosq){ p = libwebsockets_get_protocol(wsi); mosq->listener = p->user; if(!mosq->listener){ mosquitto__free(mosq); return -1; } #if !defined(LWS_LIBRARY_VERSION_NUMBER) mosq->ws_context = context; #endif mosq->wsi = wsi; #ifdef WITH_TLS if(in){ mosq->ssl = (SSL *)in; if(!mosq->listener->ssl_ctx){ mosq->listener->ssl_ctx = SSL_get_SSL_CTX(mosq->ssl); } } #endif u->mosq = mosq; }else{ return -1; } easy_address(libwebsocket_get_socket_fd(wsi), mosq); if(!mosq->address){ /* getpeername and inet_ntop failed and not a bridge */ mosquitto__free(mosq); u->mosq = NULL; return -1; } if(mosq->listener->max_connections > 0 && mosq->listener->client_count > mosq->listener->max_connections){ if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client connection from %s denied: max_connections exceeded.", mosq->address); } mosquitto__free(mosq->address); mosquitto__free(mosq); u->mosq = NULL; return -1; } mosq->sock = libwebsocket_get_socket_fd(wsi); HASH_ADD(hh_sock, db->contexts_by_sock, sock, sizeof(mosq->sock), mosq); break; case LWS_CALLBACK_CLOSED: if(!u){ return -1; } mosq = u->mosq; if(mosq){ if(mosq->sock != INVALID_SOCKET){ HASH_DELETE(hh_sock, db->contexts_by_sock, mosq); mosq->sock = INVALID_SOCKET; mosq->pollfd_index = -1; } mosq->wsi = NULL; #ifdef WITH_TLS mosq->ssl = NULL; #endif do_disconnect(db, mosq, MOSQ_ERR_CONN_LOST); } break; case LWS_CALLBACK_SERVER_WRITEABLE: if(!u){ return -1; } mosq = u->mosq; if(!mosq){ return -1; } db__message_write(db, mosq); if(mosq->out_packet && !mosq->current_out_packet){ mosq->current_out_packet = mosq->out_packet; mosq->out_packet = mosq->out_packet->next; if(!mosq->out_packet){ mosq->out_packet_last = NULL; } } if(mosq->current_out_packet && !lws_send_pipe_choked(mosq->wsi)){ packet = mosq->current_out_packet; if(packet->pos == 0 && packet->to_process == packet->packet_length){ /* First time this packet has been dealt with. * libwebsockets requires that the payload has * LWS_SEND_BUFFER_PRE_PADDING space available before the * actual data and LWS_SEND_BUFFER_POST_PADDING afterwards. * We've already made the payload big enough to allow this, * but need to move it into position here. */ memmove(&packet->payload[LWS_SEND_BUFFER_PRE_PADDING], packet->payload, packet->packet_length); packet->pos += LWS_SEND_BUFFER_PRE_PADDING; } if(packet->to_process > WS_TX_BUF_SIZE){ txlen = WS_TX_BUF_SIZE; }else{ txlen = packet->to_process; } count = libwebsocket_write(wsi, &packet->payload[packet->pos], txlen, LWS_WRITE_BINARY); if(count < 0){ if (mosq->state == mosq_cs_disconnect_ws || mosq->state == mosq_cs_disconnecting){ return -1; } return 0; } #ifdef WITH_SYS_TREE g_bytes_sent += count; #endif packet->to_process -= count; packet->pos += count; if(packet->to_process > 0){ if (mosq->state == mosq_cs_disconnect_ws || mosq->state == mosq_cs_disconnecting){ return -1; } break; } #ifdef WITH_SYS_TREE g_msgs_sent++; if(((packet->command)&0xF6) == CMD_PUBLISH){ g_pub_msgs_sent++; } #endif /* Free data and reset values */ mosq->current_out_packet = mosq->out_packet; if(mosq->out_packet){ mosq->out_packet = mosq->out_packet->next; if(!mosq->out_packet){ mosq->out_packet_last = NULL; } } packet__cleanup(packet); mosquitto__free(packet); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; } if (mosq->state == mosq_cs_disconnect_ws || mosq->state == mosq_cs_disconnecting){ return -1; } if(mosq->current_out_packet){ libwebsocket_callback_on_writable(mosq->ws_context, mosq->wsi); } break; case LWS_CALLBACK_RECEIVE: if(!u || !u->mosq){ return -1; } mosq = u->mosq; pos = 0; buf = (uint8_t *)in; G_BYTES_RECEIVED_INC(len); while(pos < len){ if(!mosq->in_packet.command){ mosq->in_packet.command = buf[pos]; pos++; /* Clients must send CONNECT as their first command. */ if(mosq->state == mosq_cs_new && (mosq->in_packet.command&0xF0) != CMD_CONNECT){ return -1; } } if(mosq->in_packet.remaining_count <= 0){ do{ if(pos == len){ return 0; } byte = buf[pos]; pos++; mosq->in_packet.remaining_count--; /* Max 4 bytes length for remaining length as defined by protocol. * Anything more likely means a broken/malicious client. */ if(mosq->in_packet.remaining_count < -4){ return -1; } mosq->in_packet.remaining_length += (byte & 127) * mosq->in_packet.remaining_mult; mosq->in_packet.remaining_mult *= 128; }while((byte & 128) != 0); mosq->in_packet.remaining_count *= -1; if(mosq->in_packet.remaining_length > 0){ mosq->in_packet.payload = mosquitto__malloc(mosq->in_packet.remaining_length*sizeof(uint8_t)); if(!mosq->in_packet.payload){ return -1; } mosq->in_packet.to_process = mosq->in_packet.remaining_length; } } if(mosq->in_packet.to_process>0){ if(len - pos >= mosq->in_packet.to_process){ memcpy(&mosq->in_packet.payload[mosq->in_packet.pos], &buf[pos], mosq->in_packet.to_process); mosq->in_packet.pos += mosq->in_packet.to_process; pos += mosq->in_packet.to_process; mosq->in_packet.to_process = 0; }else{ memcpy(&mosq->in_packet.payload[mosq->in_packet.pos], &buf[pos], len-pos); mosq->in_packet.pos += len-pos; mosq->in_packet.to_process -= len-pos; return 0; } } /* All data for this packet is read. */ mosq->in_packet.pos = 0; #ifdef WITH_SYS_TREE G_MSGS_RECEIVED_INC(1); if(((mosq->in_packet.command)&0xF5) == CMD_PUBLISH){ G_PUB_MSGS_RECEIVED_INC(1); } #endif rc = handle__packet(db, mosq); /* Free data and reset values */ packet__cleanup(&mosq->in_packet); mosq->last_msg_in = mosquitto_time(); if(rc && (mosq->out_packet || mosq->current_out_packet)) { if(mosq->state != mosq_cs_disconnecting){ mosquitto__set_state(mosq, mosq_cs_disconnect_ws); } libwebsocket_callback_on_writable(mosq->ws_context, mosq->wsi); } else if (rc) { do_disconnect(db, mosq, MOSQ_ERR_CONN_LOST); return -1; } } break; default: break; } return 0; } static char *http__canonical_filename( #ifndef LWS_LIBRARY_VERSION_NUMBER struct libwebsocket_context *context, #endif struct libwebsocket *wsi, const char *in, const char *http_dir) { size_t inlen, slen; char *filename, *filename_canonical; inlen = strlen(in); if(in[inlen-1] == '/'){ slen = strlen(http_dir) + inlen + strlen("/index.html") + 2; }else{ slen = strlen(http_dir) + inlen + 2; } filename = mosquitto__malloc(slen); if(!filename){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_INTERNAL_SERVER_ERROR, NULL); return NULL; } if(((char *)in)[inlen-1] == '/'){ snprintf(filename, slen, "%s%sindex.html", http_dir, (char *)in); }else{ snprintf(filename, slen, "%s%s", http_dir, (char *)in); } /* Get canonical path and check it is within our http_dir */ #ifdef WIN32 filename_canonical = _fullpath(NULL, filename, 0); mosquitto__free(filename); if(!filename_canonical){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_INTERNAL_SERVER_ERROR, NULL); return NULL; } #else filename_canonical = realpath(filename, NULL); mosquitto__free(filename); if(!filename_canonical){ if(errno == EACCES){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_FORBIDDEN, NULL); }else if(errno == EINVAL || errno == EIO || errno == ELOOP){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_INTERNAL_SERVER_ERROR, NULL); }else if(errno == ENAMETOOLONG){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_REQ_URI_TOO_LONG, NULL); }else if(errno == ENOENT || errno == ENOTDIR){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_NOT_FOUND, NULL); } return NULL; } #endif if(strncmp(http_dir, filename_canonical, strlen(http_dir))){ /* Requested file isn't within http_dir, deny access. */ free(filename_canonical); libwebsockets_return_http_status(context, wsi, HTTP_STATUS_FORBIDDEN, NULL); return NULL; } return filename_canonical; } #if defined(LWS_LIBRARY_VERSION_NUMBER) static int callback_http( #else static int callback_http(struct libwebsocket_context *context, #endif struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { struct libws_http_data *u = (struct libws_http_data *)user; struct libws_mqtt_hack *hack; char *http_dir; size_t buflen; size_t wlen; char *filename_canonical; unsigned char buf[4096]; struct stat filestat; struct mosquitto_db *db = &int_db; struct mosquitto *mosq; struct lws_pollargs *pollargs = (struct lws_pollargs *)in; /* FIXME - ssl cert verification is done here. */ switch (reason) { case LWS_CALLBACK_HTTP: if(!u){ return -1; } #if defined(LWS_LIBRARY_VERSION_NUMBER) hack = (struct libws_mqtt_hack *)lws_context_user(lws_get_context(wsi)); #else hack = (struct libws_mqtt_hack *)libwebsocket_context_user(context); #endif if(!hack){ return -1; } http_dir = hack->http_dir; if(!http_dir){ /* http disabled */ return -1; } /* Forbid POST */ if(lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_METHOD_NOT_ALLOWED, NULL); return -1; } #if defined(LWS_LIBRARY_VERSION_NUMBER) filename_canonical = http__canonical_filename(wsi, (char *)in, http_dir); #else filename_canonical = http__canonical_filename(context, wsi, (char *)in, http_dir); #endif if(!filename_canonical) return -1; u->fptr = fopen(filename_canonical, "rb"); if(!u->fptr){ free(filename_canonical); libwebsockets_return_http_status(context, wsi, HTTP_STATUS_NOT_FOUND, NULL); return -1; } if(fstat(fileno(u->fptr), &filestat) < 0){ free(filename_canonical); libwebsockets_return_http_status(context, wsi, HTTP_STATUS_INTERNAL_SERVER_ERROR, NULL); fclose(u->fptr); u->fptr = NULL; return -1; } if((filestat.st_mode & S_IFDIR) == S_IFDIR){ fclose(u->fptr); u->fptr = NULL; free(filename_canonical); /* FIXME - use header functions from lws 2.x */ buflen = snprintf((char *)buf, 4096, "HTTP/1.0 302 OK\r\n" "Location: %s/\r\n\r\n", (char *)in); return libwebsocket_write(wsi, buf, buflen, LWS_WRITE_HTTP); } if((filestat.st_mode & S_IFREG) != S_IFREG){ libwebsockets_return_http_status(context, wsi, HTTP_STATUS_FORBIDDEN, NULL); fclose(u->fptr); u->fptr = NULL; free(filename_canonical); return -1; } log__printf(NULL, MOSQ_LOG_DEBUG, "http serving file \"%s\".", filename_canonical); free(filename_canonical); /* FIXME - use header functions from lws 2.x */ buflen = snprintf((char *)buf, 4096, "HTTP/1.0 200 OK\r\n" "Server: mosquitto\r\n" "Content-Length: %u\r\n\r\n", (unsigned int)filestat.st_size); if(libwebsocket_write(wsi, buf, buflen, LWS_WRITE_HTTP) < 0){ fclose(u->fptr); u->fptr = NULL; return -1; } libwebsocket_callback_on_writable(context, wsi); break; case LWS_CALLBACK_HTTP_BODY: /* For extra POST data? */ return -1; case LWS_CALLBACK_HTTP_BODY_COMPLETION: /* For end of extra POST data? */ return -1; case LWS_CALLBACK_FILTER_HTTP_CONNECTION: /* Access control here */ return 0; case LWS_CALLBACK_HTTP_WRITEABLE: /* Send our data here */ if(u && u->fptr){ do{ buflen = fread(buf, 1, sizeof(buf), u->fptr); if(buflen < 1){ fclose(u->fptr); u->fptr = NULL; return -1; } wlen = libwebsocket_write(wsi, buf, buflen, LWS_WRITE_HTTP); if(wlen < buflen){ if(fseek(u->fptr, buflen-wlen, SEEK_CUR) < 0){ fclose(u->fptr); u->fptr = NULL; return -1; } }else{ if(buflen < sizeof(buf)){ fclose(u->fptr); u->fptr = NULL; } } }while(u->fptr && !lws_send_pipe_choked(wsi)); libwebsocket_callback_on_writable(context, wsi); }else{ return -1; } break; case LWS_CALLBACK_CLOSED: case LWS_CALLBACK_CLOSED_HTTP: case LWS_CALLBACK_HTTP_FILE_COMPLETION: if(u && u->fptr){ fclose(u->fptr); u->fptr = NULL; } break; case LWS_CALLBACK_ADD_POLL_FD: case LWS_CALLBACK_DEL_POLL_FD: case LWS_CALLBACK_CHANGE_MODE_POLL_FD: HASH_FIND(hh_sock, db->contexts_by_sock, &pollargs->fd, sizeof(pollargs->fd), mosq); if(mosq && (pollargs->events & POLLOUT)){ mosq->ws_want_write = true; } break; #ifdef WITH_TLS case LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if(!len || (SSL_get_verify_result((SSL*)in) != X509_V_OK)){ return 1; } break; #endif default: return 0; } return 0; } static void log_wrap(int level, const char *line) { char *l = (char *)line; l[strlen(line)-1] = '\0'; // Remove \n log__printf(NULL, MOSQ_LOG_WEBSOCKETS, "%s", l); } struct libwebsocket_context *mosq_websockets_init(struct mosquitto__listener *listener, const struct mosquitto__config *conf) { struct lws_context_creation_info info; struct libwebsocket_protocols *p; int protocol_count; int i; struct libws_mqtt_hack *user; /* Count valid protocols */ for(protocol_count=0; protocols[protocol_count].name; protocol_count++); p = mosquitto__calloc(protocol_count+1, sizeof(struct libwebsocket_protocols)); if(!p){ log__printf(NULL, MOSQ_LOG_ERR, "Out of memory."); return NULL; } for(i=0; protocols[i].name; i++){ p[i].name = protocols[i].name; p[i].callback = protocols[i].callback; p[i].per_session_data_size = protocols[i].per_session_data_size; p[i].rx_buffer_size = protocols[i].rx_buffer_size; p[i].user = listener; } memset(&info, 0, sizeof(info)); info.iface = listener->host; info.port = listener->port; info.protocols = p; info.gid = -1; info.uid = -1; #ifdef WITH_TLS info.ssl_ca_filepath = listener->cafile; info.ssl_cert_filepath = listener->certfile; info.ssl_private_key_filepath = listener->keyfile; info.ssl_cipher_list = listener->ciphers; if(listener->require_certificate){ info.options |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT; } #endif #if LWS_LIBRARY_VERSION_MAJOR>1 info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; #endif if(listener->socket_domain == AF_INET){ info.options |= LWS_SERVER_OPTION_DISABLE_IPV6; } #if defined(LWS_LIBRARY_VERSION_NUMBER) && LWS_LIBRARY_VERSION_NUMBER>=1007000 info.max_http_header_data = conf->websockets_headers_size; #endif user = mosquitto__calloc(1, sizeof(struct libws_mqtt_hack)); if(!user){ mosquitto__free(p); log__printf(NULL, MOSQ_LOG_ERR, "Out of memory."); return NULL; } if(listener->http_dir){ #ifdef WIN32 user->http_dir = _fullpath(NULL, listener->http_dir, 0); #else user->http_dir = realpath(listener->http_dir, NULL); #endif if(!user->http_dir){ mosquitto__free(user); mosquitto__free(p); log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open http dir \"%s\".", listener->http_dir); return NULL; } } info.user = user; #if defined(LWS_LIBRARY_VERSION_NUMBER) && LWS_LIBRARY_VERSION_NUMBER>=2004000 info.pt_serv_buf_size = WS_SERV_BUF_SIZE; #endif listener->ws_protocol = p; lws_set_log_level(conf->websockets_log_level, log_wrap); log__printf(NULL, MOSQ_LOG_INFO, "Opening websockets listen socket on port %d.", listener->port); return libwebsocket_create_context(&info); } #endif mosquitto-1.6.9/src/property_broker.c0000664000175000017500000000637513626052637017023 0ustar rogerroger/* Copyright (c) 2018-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "property_mosq.h" /* Process the incoming properties, we should be able to assume that only valid * properties for CONNECT are present here. */ int property__process_connect(struct mosquitto *context, mosquitto_property **props) { mosquitto_property *p; p = *props; while(p){ if(p->identifier == MQTT_PROP_SESSION_EXPIRY_INTERVAL){ context->session_expiry_interval = p->value.i32; }else if(p->identifier == MQTT_PROP_RECEIVE_MAXIMUM){ if(p->value.i16 == 0){ return MOSQ_ERR_PROTOCOL; } context->msgs_out.inflight_maximum = p->value.i16; context->msgs_out.inflight_quota = context->msgs_out.inflight_maximum; }else if(p->identifier == MQTT_PROP_MAXIMUM_PACKET_SIZE){ if(p->value.i32 == 0){ return MOSQ_ERR_PROTOCOL; } context->maximum_packet_size = p->value.i32; } p = p->next; } return MOSQ_ERR_SUCCESS; } int property__process_will(struct mosquitto *context, struct mosquitto_message_all *msg, mosquitto_property **props) { mosquitto_property *p, *p_prev; mosquitto_property *msg_properties, *msg_properties_last; p = *props; p_prev = NULL; msg_properties = NULL; msg_properties_last = NULL; while(p){ switch(p->identifier){ case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_CORRELATION_DATA: case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_USER_PROPERTY: if(msg_properties){ msg_properties_last->next = p; msg_properties_last = p; }else{ msg_properties = p; msg_properties_last = p; } if(p_prev){ p_prev->next = p->next; p = p_prev->next; }else{ *props = p->next; p = *props; } msg_properties_last->next = NULL; break; case MQTT_PROP_WILL_DELAY_INTERVAL: context->will_delay_interval = p->value.i32; p_prev = p; p = p->next; break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: msg->expiry_interval = p->value.i32; p_prev = p; p = p->next; break; default: return MOSQ_ERR_PROTOCOL; break; } } msg->properties = msg_properties; return MOSQ_ERR_SUCCESS; } /* Process the incoming properties, we should be able to assume that only valid * properties for DISCONNECT are present here. */ int property__process_disconnect(struct mosquitto *context, mosquitto_property **props) { mosquitto_property *p; p = *props; while(p){ if(p->identifier == MQTT_PROP_SESSION_EXPIRY_INTERVAL){ if(context->session_expiry_interval == 0 && p->value.i32 != 0){ return MOSQ_ERR_PROTOCOL; } context->session_expiry_interval = p->value.i32; } p = p->next; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/src/plugin.c0000664000175000017500000000442213626052637015060 0ustar rogerroger/* Copyright (c) 2016-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "mosquitto_broker.h" #include "memory_mosq.h" #ifdef WITH_TLS # include #endif const char *mosquitto_client_address(const struct mosquitto *client) { return client->address; } bool mosquitto_client_clean_session(const struct mosquitto *client) { return client->clean_start; } const char *mosquitto_client_id(const struct mosquitto *client) { return client->id; } int mosquitto_client_keepalive(const struct mosquitto *client) { return client->keepalive; } void *mosquitto_client_certificate(const struct mosquitto *client) { #ifdef WITH_TLS if(client->ssl){ return SSL_get_peer_certificate(client->ssl); }else{ return NULL; } #else return NULL; #endif } int mosquitto_client_protocol(const struct mosquitto *client) { #ifdef WITH_WEBSOCKETS if(client->wsi){ return mp_websockets; }else #endif { return mp_mqtt; } } int mosquitto_client_sub_count(const struct mosquitto *client) { return client->sub_count; } const char *mosquitto_client_username(const struct mosquitto *context) { #ifdef WITH_BRIDGE if(context->bridge){ return context->bridge->local_username; }else #endif { return context->username; } } int mosquitto_set_username(struct mosquitto *client, const char *username) { char *u_dup; char *old; int rc; if(!client) return MOSQ_ERR_INVAL; if(username){ u_dup = mosquitto__strdup(username); if(!u_dup) return MOSQ_ERR_NOMEM; }else{ u_dup = NULL; } old = client->username; client->username = u_dup; rc = acl__find_acls(mosquitto__get_db(), client); if(rc){ client->username = old; mosquitto__free(u_dup); return rc; }else{ mosquitto__free(old); return MOSQ_ERR_SUCCESS; } } mosquitto-1.6.9/src/persist_read_v5.c0000664000175000017500000001530013626052637016655 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_PERSISTENCE #ifndef WIN32 #include #endif #include #include #include #include #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "persist.h" #include "property_mosq.h" #include "time_mosq.h" #include "util_mosq.h" int persist__chunk_header_read_v5(FILE *db_fptr, int *chunk, int *length) { size_t rlen; struct PF_header header; rlen = fread(&header, sizeof(struct PF_header), 1, db_fptr); if(rlen != 1) return 1; *chunk = ntohl(header.chunk); *length = ntohl(header.length); return MOSQ_ERR_SUCCESS; } int persist__chunk_cfg_read_v5(FILE *db_fptr, struct PF_cfg *chunk) { if(fread(chunk, sizeof(struct PF_cfg), 1, db_fptr) != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } return MOSQ_ERR_SUCCESS; } int persist__chunk_client_read_v5(FILE *db_fptr, struct P_client *chunk) { int rc; read_e(db_fptr, &chunk->F, sizeof(struct PF_client)); chunk->F.session_expiry_interval = ntohl(chunk->F.session_expiry_interval); chunk->F.last_mid = ntohs(chunk->F.last_mid); chunk->F.id_len = ntohs(chunk->F.id_len); rc = persist__read_string_len(db_fptr, &chunk->client_id, chunk->F.id_len); if(rc || !chunk->client_id){ return 1; }else{ return MOSQ_ERR_SUCCESS; } error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_client_msg_read_v5(FILE *db_fptr, struct P_client_msg *chunk, uint32_t length) { mosquitto_property *properties = NULL; struct mosquitto__packet prop_packet; int rc; read_e(db_fptr, &chunk->F, sizeof(struct PF_client_msg)); chunk->F.mid = ntohs(chunk->F.mid); chunk->F.id_len = ntohs(chunk->F.id_len); length -= (sizeof(struct PF_client_msg) + chunk->F.id_len); rc = persist__read_string_len(db_fptr, &chunk->client_id, chunk->F.id_len); if(rc){ return rc; } if(length > 0){ memset(&prop_packet, 0, sizeof(struct mosquitto__packet)); prop_packet.remaining_length = length; prop_packet.payload = mosquitto__malloc(length); if(!prop_packet.payload){ return MOSQ_ERR_NOMEM; } read_e(db_fptr, prop_packet.payload, length); rc = property__read_all(CMD_PUBLISH, &prop_packet, &properties); mosquitto__free(prop_packet.payload); if(rc){ return rc; } } chunk->properties = properties; return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_msg_store_read_v5(FILE *db_fptr, struct P_msg_store *chunk, uint32_t length) { int rc = 0; mosquitto_property *properties = NULL; struct mosquitto__packet prop_packet; memset(&prop_packet, 0, sizeof(struct mosquitto__packet)); read_e(db_fptr, &chunk->F, sizeof(struct PF_msg_store)); chunk->F.payloadlen = ntohl(chunk->F.payloadlen); if(chunk->F.payloadlen > MQTT_MAX_PAYLOAD){ return MOSQ_ERR_INVAL; } chunk->F.source_mid = ntohs(chunk->F.source_mid); chunk->F.source_id_len = ntohs(chunk->F.source_id_len); chunk->F.source_username_len = ntohs(chunk->F.source_username_len); chunk->F.topic_len = ntohs(chunk->F.topic_len); chunk->F.source_port = ntohs(chunk->F.source_port); length -= (sizeof(struct PF_msg_store) + chunk->F.payloadlen + chunk->F.source_id_len + chunk->F.source_username_len + chunk->F.topic_len); if(chunk->F.source_id_len){ rc = persist__read_string_len(db_fptr, &chunk->source.id, chunk->F.source_id_len); if(rc){ return rc; } } if(chunk->F.source_username_len){ rc = persist__read_string_len(db_fptr, &chunk->source.username, chunk->F.source_username_len); if(rc){ mosquitto__free(chunk->source.id); chunk->source.id = NULL; return rc; } } rc = persist__read_string_len(db_fptr, &chunk->topic, chunk->F.topic_len); if(rc){ mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); chunk->source.id = NULL; chunk->source.username = NULL; return rc; } if(chunk->F.payloadlen > 0){ if(UHPA_ALLOC(chunk->payload, chunk->F.payloadlen) == 0){ mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); mosquitto__free(chunk->topic); chunk->source.id = NULL; chunk->source.username = NULL; chunk->topic = NULL; log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } read_e(db_fptr, UHPA_ACCESS(chunk->payload, chunk->F.payloadlen), chunk->F.payloadlen); } if(length > 0){ prop_packet.remaining_length = length; prop_packet.payload = mosquitto__malloc(length); if(!prop_packet.payload){ mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); mosquitto__free(chunk->topic); return MOSQ_ERR_NOMEM; } read_e(db_fptr, prop_packet.payload, length); rc = property__read_all(CMD_PUBLISH, &prop_packet, &properties); mosquitto__free(prop_packet.payload); if(rc){ mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); mosquitto__free(chunk->topic); return rc; } } chunk->properties = properties; return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); mosquitto__free(chunk->source.id); mosquitto__free(chunk->source.username); mosquitto__free(chunk->topic); mosquitto__free(prop_packet.payload); return 1; } int persist__chunk_retain_read_v5(FILE *db_fptr, struct P_retain *chunk) { if(fread(&chunk->F, sizeof(struct P_retain), 1, db_fptr) != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } return MOSQ_ERR_SUCCESS; } int persist__chunk_sub_read_v5(FILE *db_fptr, struct P_sub *chunk) { int rc; read_e(db_fptr, &chunk->F, sizeof(struct PF_sub)); chunk->F.identifier = ntohl(chunk->F.identifier); chunk->F.id_len = ntohs(chunk->F.id_len); chunk->F.topic_len = ntohs(chunk->F.topic_len); rc = persist__read_string_len(db_fptr, &chunk->client_id, chunk->F.id_len); if(rc){ return rc; } rc = persist__read_string_len(db_fptr, &chunk->topic, chunk->F.topic_len); if(rc){ mosquitto__free(chunk->client_id); chunk->client_id = NULL; return rc; } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } #endif mosquitto-1.6.9/src/persist_write_v5.c0000664000175000017500000001467613626052637017113 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_PERSISTENCE #ifndef WIN32 #include #endif #include #include #include #include #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "persist.h" #include "packet_mosq.h" #include "property_mosq.h" #include "time_mosq.h" #include "util_mosq.h" int persist__chunk_cfg_write_v5(FILE *db_fptr, struct PF_cfg *chunk) { struct PF_header header; header.chunk = htonl(DB_CHUNK_CFG); header.length = htonl(sizeof(struct PF_cfg)); write_e(db_fptr, &header, sizeof(struct PF_header)); write_e(db_fptr, chunk, sizeof(struct PF_cfg)); return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_client_write_v5(FILE *db_fptr, struct P_client *chunk) { struct PF_header header; uint16_t id_len = chunk->F.id_len; chunk->F.session_expiry_interval = htonl(chunk->F.session_expiry_interval); chunk->F.last_mid = htons(chunk->F.last_mid); chunk->F.id_len = htons(chunk->F.id_len); header.chunk = htonl(DB_CHUNK_CLIENT); header.length = htonl(sizeof(struct PF_client)+id_len); write_e(db_fptr, &header, sizeof(struct PF_header)); write_e(db_fptr, &chunk->F, sizeof(struct PF_client)); write_e(db_fptr, chunk->client_id, id_len); return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_client_msg_write_v5(FILE *db_fptr, struct P_client_msg *chunk) { struct PF_header header; struct mosquitto__packet prop_packet; uint16_t id_len = chunk->F.id_len; uint32_t proplen = 0; int rc; memset(&prop_packet, 0, sizeof(struct mosquitto__packet)); if(chunk->properties){ proplen = property__get_length_all(chunk->properties); proplen += packet__varint_bytes(proplen); } chunk->F.mid = htons(chunk->F.mid); chunk->F.id_len = htons(chunk->F.id_len); header.chunk = htonl(DB_CHUNK_CLIENT_MSG); header.length = htonl(sizeof(struct PF_client_msg) + id_len + proplen); write_e(db_fptr, &header, sizeof(struct PF_header)); write_e(db_fptr, &chunk->F, sizeof(struct PF_client_msg)); write_e(db_fptr, chunk->client_id, id_len); if(chunk->properties){ if(proplen > 0){ prop_packet.remaining_length = proplen; prop_packet.packet_length = proplen; prop_packet.payload = mosquitto__malloc(proplen); if(!prop_packet.payload){ return MOSQ_ERR_NOMEM; } rc = property__write_all(&prop_packet, chunk->properties, true); if(rc) return rc; write_e(db_fptr, prop_packet.payload, proplen); mosquitto__free(prop_packet.payload); } } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_message_store_write_v5(FILE *db_fptr, struct P_msg_store *chunk) { struct PF_header header; uint32_t payloadlen = chunk->F.payloadlen; uint16_t source_id_len = chunk->F.source_id_len; uint16_t source_username_len = chunk->F.source_username_len; uint16_t topic_len = chunk->F.topic_len; uint32_t proplen = 0; struct mosquitto__packet prop_packet; int rc; memset(&prop_packet, 0, sizeof(struct mosquitto__packet)); if(chunk->properties){ proplen = property__get_length_all(chunk->properties); proplen += packet__varint_bytes(proplen); } chunk->F.payloadlen = htonl(chunk->F.payloadlen); chunk->F.source_mid = htons(chunk->F.source_mid); chunk->F.source_id_len = htons(chunk->F.source_id_len); chunk->F.source_username_len = htons(chunk->F.source_username_len); chunk->F.topic_len = htons(chunk->F.topic_len); chunk->F.source_port = htons(chunk->F.source_port); header.chunk = htonl(DB_CHUNK_MSG_STORE); header.length = htonl(sizeof(struct PF_msg_store) + topic_len + payloadlen + source_id_len + source_username_len + proplen); write_e(db_fptr, &header, sizeof(struct PF_header)); write_e(db_fptr, &chunk->F, sizeof(struct PF_msg_store)); if(source_id_len){ write_e(db_fptr, chunk->source.id, source_id_len); } if(source_username_len){ write_e(db_fptr, chunk->source.username, source_username_len); } write_e(db_fptr, chunk->topic, topic_len); if(payloadlen){ write_e(db_fptr, UHPA_ACCESS(chunk->payload, payloadlen), (unsigned int)payloadlen); } if(chunk->properties){ if(proplen > 0){ prop_packet.remaining_length = proplen; prop_packet.packet_length = proplen; prop_packet.payload = mosquitto__malloc(proplen); if(!prop_packet.payload){ return MOSQ_ERR_NOMEM; } rc = property__write_all(&prop_packet, chunk->properties, true); if(rc) return rc; write_e(db_fptr, prop_packet.payload, proplen); mosquitto__free(prop_packet.payload); } } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); mosquitto__free(prop_packet.payload); return 1; } int persist__chunk_retain_write_v5(FILE *db_fptr, struct P_retain *chunk) { struct PF_header header; header.chunk = htonl(DB_CHUNK_RETAIN); header.length = htonl(sizeof(struct PF_retain)); write_e(db_fptr, &header, sizeof(struct PF_header)); write_e(db_fptr, &chunk->F, sizeof(struct PF_retain)); return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_sub_write_v5(FILE *db_fptr, struct P_sub *chunk) { struct PF_header header; uint16_t id_len = chunk->F.id_len; uint16_t topic_len = chunk->F.topic_len; chunk->F.identifier = htonl(chunk->F.identifier); chunk->F.id_len = htons(chunk->F.id_len); chunk->F.topic_len = htons(chunk->F.topic_len); header.chunk = htonl(DB_CHUNK_SUB); header.length = htonl(sizeof(struct PF_sub) + id_len + topic_len); write_e(db_fptr, &header, sizeof(struct PF_header)); write_e(db_fptr, &chunk->F, sizeof(struct PF_sub)); write_e(db_fptr, chunk->client_id, id_len); write_e(db_fptr, chunk->topic, topic_len); return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } #endif mosquitto-1.6.9/src/sys_tree.h0000664000175000017500000000413013626052637015420 0ustar rogerroger/* Copyright (c) 2015-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef SYS_TREE_H #define SYS_TREE_H #if defined(WITH_SYS_TREE) && defined(WITH_BROKER) extern uint64_t g_bytes_received; extern uint64_t g_bytes_sent; extern uint64_t g_pub_bytes_received; extern uint64_t g_pub_bytes_sent; extern unsigned long g_msgs_received; extern unsigned long g_msgs_sent; extern unsigned long g_pub_msgs_received; extern unsigned long g_pub_msgs_sent; extern unsigned long g_msgs_dropped; extern int g_clients_expired; extern unsigned int g_socket_connections; extern unsigned int g_connection_count; #define G_BYTES_RECEIVED_INC(A) (g_bytes_received+=(A)) #define G_BYTES_SENT_INC(A) (g_bytes_sent+=(A)) #define G_PUB_BYTES_RECEIVED_INC(A) (g_pub_bytes_received+=(A)) #define G_PUB_BYTES_SENT_INC(A) (g_pub_bytes_sent+=(A)) #define G_MSGS_RECEIVED_INC(A) (g_msgs_received+=(A)) #define G_MSGS_SENT_INC(A) (g_msgs_sent+=(A)) #define G_PUB_MSGS_RECEIVED_INC(A) (g_pub_msgs_received+=(A)) #define G_PUB_MSGS_SENT_INC(A) (g_pub_msgs_sent+=(A)) #define G_MSGS_DROPPED_INC() (g_msgs_dropped++) #define G_CLIENTS_EXPIRED_INC() (g_clients_expired++) #define G_SOCKET_CONNECTIONS_INC() (g_socket_connections++) #define G_CONNECTION_COUNT_INC() (g_connection_count++) #else #define G_BYTES_RECEIVED_INC(A) #define G_BYTES_SENT_INC(A) #define G_PUB_BYTES_RECEIVED_INC(A) #define G_PUB_BYTES_SENT_INC(A) #define G_MSGS_RECEIVED_INC(A) #define G_MSGS_SENT_INC(A) #define G_PUB_MSGS_RECEIVED_INC(A) #define G_PUB_MSGS_SENT_INC(A) #define G_MSGS_DROPPED_INC(A) #define G_CLIENTS_EXPIRED_INC(A) #define G_SOCKET_CONNECTIONS_INC(A) #define G_CONNECTION_COUNT_INC(A) #endif #endif mosquitto-1.6.9/src/handle_auth.c0000664000175000017500000001145713626052637016044 0ustar rogerroger/* Copyright (c) 2018-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "util_mosq.h" #include "will_mosq.h" int handle__auth(struct mosquitto_db *db, struct mosquitto *context) { int rc = 0; uint8_t reason_code = 0; mosquitto_property *properties = NULL; char *auth_method = NULL; void *auth_data = NULL; uint16_t auth_data_len = 0; void *auth_data_out = NULL; uint16_t auth_data_out_len = 0; if(!context) return MOSQ_ERR_INVAL; if(context->protocol != mosq_p_mqtt5 || context->auth_method == NULL){ return MOSQ_ERR_PROTOCOL; } if(context->in_packet.remaining_length > 0){ if(packet__read_byte(&context->in_packet, &reason_code)) return 1; if(reason_code != MQTT_RC_CONTINUE_AUTHENTICATION && reason_code != MQTT_RC_REAUTHENTICATE){ send__disconnect(context, MQTT_RC_PROTOCOL_ERROR, NULL); return MOSQ_ERR_PROTOCOL; } if((reason_code == MQTT_RC_REAUTHENTICATE && context->state != mosq_cs_active) || (reason_code == MQTT_RC_CONTINUE_AUTHENTICATION && context->state != mosq_cs_authenticating && context->state != mosq_cs_reauthenticating)){ send__disconnect(context, MQTT_RC_PROTOCOL_ERROR, NULL); return MOSQ_ERR_PROTOCOL; } rc = property__read_all(CMD_AUTH, &context->in_packet, &properties); if(rc){ send__disconnect(context, MQTT_RC_UNSPECIFIED, NULL); return rc; } if(mosquitto_property_read_string(properties, MQTT_PROP_AUTHENTICATION_METHOD, &auth_method, false) == NULL){ mosquitto_property_free_all(&properties); send__disconnect(context, MQTT_RC_UNSPECIFIED, NULL); return MOSQ_ERR_PROTOCOL; } if(!auth_method || strcmp(auth_method, context->auth_method)){ /* No method, or non-matching method */ mosquitto__free(auth_method); mosquitto_property_free_all(&properties); send__disconnect(context, MQTT_RC_PROTOCOL_ERROR, NULL); return MOSQ_ERR_PROTOCOL; } mosquitto__free(auth_method); mosquitto_property_read_binary(properties, MQTT_PROP_AUTHENTICATION_DATA, &auth_data, &auth_data_len, false); mosquitto_property_free_all(&properties); /* FIXME - TEMPORARY UNTIL PROPERTIES PROCESSED */ } log__printf(NULL, MOSQ_LOG_DEBUG, "Received AUTH from %s (rc%d, %s)", context->id, reason_code, context->auth_method); if(reason_code == MQTT_RC_REAUTHENTICATE){ /* This is a re-authentication attempt */ mosquitto__set_state(context, mosq_cs_reauthenticating); rc = mosquitto_security_auth_start(db, context, true, auth_data, auth_data_len, &auth_data_out, &auth_data_out_len); }else{ if(context->state != mosq_cs_reauthenticating){ mosquitto__set_state(context, mosq_cs_authenticating); } rc = mosquitto_security_auth_continue(db, context, auth_data, auth_data_len, &auth_data_out, &auth_data_out_len); } mosquitto__free(auth_data); if(rc == MOSQ_ERR_SUCCESS){ if(context->state == mosq_cs_authenticating){ return connect__on_authorised(db, context, auth_data_out, auth_data_out_len); }else{ mosquitto__set_state(context, mosq_cs_active); rc = send__auth(db, context, MQTT_RC_SUCCESS, auth_data_out, auth_data_out_len); free(auth_data_out); return rc; } }else if(rc == MOSQ_ERR_AUTH_CONTINUE){ rc = send__auth(db, context, MQTT_RC_CONTINUE_AUTHENTICATION, auth_data_out, auth_data_out_len); free(auth_data_out); return rc; }else{ free(auth_data_out); if(context->state == mosq_cs_authenticating && context->will){ /* Free will without sending if this is our first authentication attempt */ will__clear(context); } if(rc == MOSQ_ERR_AUTH){ send__connack(db, context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); if(context->state == mosq_cs_authenticating){ mosquitto__free(context->id); context->id = NULL; } return MOSQ_ERR_PROTOCOL; }else if(rc == MOSQ_ERR_NOT_SUPPORTED){ /* Client has requested extended authentication, but we don't support it. */ send__connack(db, context, 0, MQTT_RC_BAD_AUTHENTICATION_METHOD, NULL); if(context->state == mosq_cs_authenticating){ mosquitto__free(context->id); context->id = NULL; } return MOSQ_ERR_PROTOCOL; }else{ if(context->state == mosq_cs_authenticating){ mosquitto__free(context->id); context->id = NULL; } return rc; } } } mosquitto-1.6.9/src/handle_unsubscribe.c0000664000175000017500000000701313626052637017420 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "send_mosq.h" int handle__unsubscribe(struct mosquitto_db *db, struct mosquitto *context) { uint16_t mid; char *sub; int slen; int rc; uint8_t reason; int reason_code_count = 0; int reason_code_max; uint8_t *reason_codes = NULL, *reason_tmp; mosquitto_property *properties = NULL; if(!context) return MOSQ_ERR_INVAL; if(context->state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received UNSUBSCRIBE from %s", context->id); if(context->protocol != mosq_p_mqtt31){ if((context->in_packet.command&0x0F) != 0x02){ return MOSQ_ERR_PROTOCOL; } } if(packet__read_uint16(&context->in_packet, &mid)) return 1; if(mid == 0) return MOSQ_ERR_PROTOCOL; if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_UNSUBSCRIBE, &context->in_packet, &properties); if(rc) return rc; /* Immediately free, we don't do anything with User Property at the moment */ mosquitto_property_free_all(&properties); } if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ if(context->in_packet.pos == context->in_packet.remaining_length){ /* No topic specified, protocol error. */ return MOSQ_ERR_PROTOCOL; } } reason_code_max = 10; reason_codes = mosquitto__malloc(reason_code_max); if(!reason_codes){ return MOSQ_ERR_NOMEM; } while(context->in_packet.pos < context->in_packet.remaining_length){ sub = NULL; if(packet__read_string(&context->in_packet, &sub, &slen)){ mosquitto__free(reason_codes); return 1; } if(!slen){ log__printf(NULL, MOSQ_LOG_INFO, "Empty unsubscription string from %s, disconnecting.", context->id); mosquitto__free(sub); mosquitto__free(reason_codes); return 1; } if(mosquitto_sub_topic_check(sub)){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid unsubscription string from %s, disconnecting.", context->id); mosquitto__free(sub); mosquitto__free(reason_codes); return 1; } log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s", sub); rc = sub__remove(db, context, sub, db->subs, &reason); log__printf(NULL, MOSQ_LOG_UNSUBSCRIBE, "%s %s", context->id, sub); mosquitto__free(sub); if(rc){ mosquitto__free(reason_codes); return rc; } reason_codes[reason_code_count] = reason; reason_code_count++; if(reason_code_count == reason_code_max){ reason_tmp = mosquitto__realloc(reason_codes, reason_code_max*2); if(!reason_tmp){ mosquitto__free(reason_codes); return MOSQ_ERR_NOMEM; } reason_codes = reason_tmp; reason_code_max *= 2; } } #ifdef WITH_PERSISTENCE db->persistence_changes++; #endif log__printf(NULL, MOSQ_LOG_DEBUG, "Sending UNSUBACK to %s", context->id); /* We don't use Reason String or User Property yet. */ rc = send__unsuback(context, mid, reason_code_count, reason_codes, NULL); mosquitto__free(reason_codes); return rc; } mosquitto-1.6.9/src/will_delay.c0000664000175000017500000000470413626052637015712 0ustar rogerroger/* Copyright (c) 2019-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "time_mosq.h" static struct will_delay_list *delay_list = NULL; static time_t last_check = 0; static int will_delay__cmp(struct will_delay_list *i1, struct will_delay_list *i2) { return i1->context->will_delay_interval - i2->context->will_delay_interval; } int will_delay__add(struct mosquitto *context) { struct will_delay_list *item; item = mosquitto__calloc(1, sizeof(struct will_delay_list)); if(!item) return MOSQ_ERR_NOMEM; item->context = context; context->will_delay_entry = item; item->context->will_delay_time = time(NULL) + item->context->will_delay_interval; DL_INSERT_INORDER(delay_list, item, will_delay__cmp); return MOSQ_ERR_SUCCESS; } /* Call on broker shutdown only */ void will_delay__send_all(struct mosquitto_db *db) { struct will_delay_list *item, *tmp; DL_FOREACH_SAFE(delay_list, item, tmp){ DL_DELETE(delay_list, item); item->context->will_delay_interval = 0; item->context->will_delay_entry = NULL; context__send_will(db, item->context); mosquitto__free(item); } } void will_delay__check(struct mosquitto_db *db, time_t now) { struct will_delay_list *item, *tmp; if(now <= last_check) return; last_check = now; DL_FOREACH_SAFE(delay_list, item, tmp){ if(item->context->will_delay_time < now){ DL_DELETE(delay_list, item); item->context->will_delay_interval = 0; item->context->will_delay_entry = NULL; context__send_will(db, item->context); if(item->context->session_expiry_interval == 0){ context__add_to_disused(db, item->context); } mosquitto__free(item); }else{ return; } } } void will_delay__remove(struct mosquitto *mosq) { if(mosq->will_delay_entry != NULL){ DL_DELETE(delay_list, mosq->will_delay_entry); mosquitto__free(mosq->will_delay_entry); mosq->will_delay_entry = NULL; } } mosquitto-1.6.9/src/conf_includedir.c0000664000175000017500000001051513626052637016711 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #ifdef WIN32 #else # include #endif #ifndef WIN32 # include # include # include #else # include # include #endif #if !defined(WIN32) && !defined(__CYGWIN__) && !defined(__QNX__) # include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #include "mqtt_protocol.h" int scmp_p(const void *p1, const void *p2) { const char *s1 = *(const char **)p1; const char *s2 = *(const char **)p2; int result; while(s1[0] && s2[0]){ /* Sort by case insensitive part first */ result = toupper(s1[0]) - toupper(s2[0]); if(result == 0){ /* Case insensitive part matched, now distinguish between case */ result = s1[0] - s2[0]; if(result != 0){ return result; } }else{ /* Return case insensitive match fail */ return result; } s1++; s2++; } return s1[0] - s2[0]; } #ifdef WIN32 int config__get_dir_files(const char *include_dir, char ***files, int *file_count) { int len; int i; char **l_files = NULL; int l_file_count = 0; char **files_tmp; HANDLE fh; char dirpath[MAX_PATH]; WIN32_FIND_DATA find_data; snprintf(dirpath, MAX_PATH, "%s\\*.conf", include_dir); fh = FindFirstFile(dirpath, &find_data); if(fh == INVALID_HANDLE_VALUE){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open include_dir '%s'.", include_dir); return 1; } do{ len = strlen(include_dir)+1+strlen(find_data.cFileName)+1; l_file_count++; files_tmp = mosquitto__realloc(l_files, l_file_count*sizeof(char *)); if(!files_tmp){ for(i=0; id_name) > 5){ if(!strcmp(&de->d_name[strlen(de->d_name)-5], ".conf")){ len = strlen(include_dir)+1+strlen(de->d_name)+1; l_file_count++; files_tmp = mosquitto__realloc(l_files, l_file_count*sizeof(char *)); if(!files_tmp){ for(i=0; id_name); l_files[l_file_count-1][len] = '\0'; } } } closedir(dh); if(l_files){ qsort(l_files, l_file_count, sizeof(char *), scmp_p); } *files = l_files; *file_count = l_file_count; return 0; } #endif mosquitto-1.6.9/src/deps/0000775000175000017500000000000013626052637014347 5ustar rogerrogermosquitto-1.6.9/src/deps/uthash.h0000664000175000017500000016751613626052637016034 0ustar rogerroger/* Copyright (c) 2003-2013, Troy D. Hanson http://troydhanson.github.com/uthash/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTHASH_H #define UTHASH_H #include /* memcmp,strlen */ #include /* ptrdiff_t */ #include /* exit() */ /* These macros use decltype or the earlier __typeof GNU extension. As decltype is only available in newer compilers (VS2010 or gcc 4.3+ when compiling c++ source) this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ #ifdef _MSC_VER /* MS compiler */ #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ #define DECLTYPE(x) (decltype(x)) #else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE #define DECLTYPE(x) #endif #else /* GNU, Sun and other compilers */ #define DECLTYPE(x) (__typeof(x)) #endif #ifdef NO_DECLTYPE #define DECLTYPE_ASSIGN(dst,src) \ do { \ char **_da_dst = (char**)(&(dst)); \ *_da_dst = (char*)(src); \ } while(0) #else #define DECLTYPE_ASSIGN(dst,src) \ do { \ (dst) = DECLTYPE(dst)(src); \ } while(0) #endif /* a number of the hash function use uint32_t which isn't defined on win32 */ #ifdef _MSC_VER typedef unsigned int uint32_t; typedef unsigned char uint8_t; #else #include /* uint32_t */ #endif #define UTHASH_VERSION 1.9.8 #ifndef uthash_fatal #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ #endif #ifndef uthash_malloc #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ #endif #ifndef uthash_free #define uthash_free(ptr,sz) free(ptr) /* free fcn */ #endif #ifndef uthash_noexpand_fyi #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ #endif #ifndef uthash_expand_fyi #define uthash_expand_fyi(tbl) /* can be defined to log expands */ #endif /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ #define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ /* calculate the element whose hash handle address is hhe */ #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) #define HASH_FIND(hh,head,keyptr,keylen,out) \ do { \ unsigned _hf_bkt,_hf_hashv; \ out=NULL; \ if (head) { \ HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ keyptr,keylen,out); \ } \ } \ } while (0) #ifdef HASH_BLOOM #define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) #define HASH_BLOOM_MAKE(tbl) \ do { \ (tbl)->bloom_nbits = HASH_BLOOM; \ (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ } while (0) #define HASH_BLOOM_FREE(tbl) \ do { \ uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ } while (0) #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) #define HASH_BLOOM_ADD(tbl,hashv) \ HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) #define HASH_BLOOM_TEST(tbl,hashv) \ HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) #else #define HASH_BLOOM_MAKE(tbl) #define HASH_BLOOM_FREE(tbl) #define HASH_BLOOM_ADD(tbl,hashv) #define HASH_BLOOM_TEST(tbl,hashv) (1) #define HASH_BLOOM_BYTELEN 0 #endif #define HASH_MAKE_TABLE(hh,head) \ do { \ (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ sizeof(UT_hash_table)); \ if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ (head)->hh.tbl->tail = &((head)->hh); \ (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ memset((head)->hh.tbl->buckets, 0, \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_MAKE((head)->hh.tbl); \ (head)->hh.tbl->signature = HASH_SIGNATURE; \ } while(0) #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ HASH_ADD_KEYPTR(hh,head,&((add)->fieldname),keylen_in,add) #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ do { \ replaced=NULL; \ HASH_FIND(hh,head,&((add)->fieldname),keylen_in,replaced); \ if (replaced!=NULL) { \ HASH_DELETE(hh,head,replaced); \ }; \ HASH_ADD(hh,head,fieldname,keylen_in,add); \ } while(0) #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ do { \ unsigned _ha_bkt; \ (add)->hh.next = NULL; \ (add)->hh.key = (char*)keyptr; \ (add)->hh.keylen = (unsigned)keylen_in; \ if (!(head)) { \ head = (add); \ (head)->hh.prev = NULL; \ HASH_MAKE_TABLE(hh,head); \ } else { \ (head)->hh.tbl->tail->next = (add); \ (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ (head)->hh.tbl->tail = &((add)->hh); \ } \ (head)->hh.tbl->num_items++; \ (add)->hh.tbl = (head)->hh.tbl; \ HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ (add)->hh.hashv, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ HASH_FSCK(hh,head); \ } while(0) #define HASH_TO_BKT( hashv, num_bkts, bkt ) \ do { \ bkt = ((hashv) & ((num_bkts) - 1)); \ } while(0) /* delete "delptr" from the hash table. * "the usual" patch-up process for the app-order doubly-linked-list. * The use of _hd_hh_del below deserves special explanation. * These used to be expressed using (delptr) but that led to a bug * if someone used the same symbol for the head and deletee, like * HASH_DELETE(hh,users,users); * We want that to work, but by changing the head (users) below * we were forfeiting our ability to further refer to the deletee (users) * in the patch-up process. Solution: use scratch space to * copy the deletee pointer, then the latter references are via that * scratch pointer rather than through the repointed (users) symbol. */ #define HASH_DELETE(hh,head,delptr) \ do { \ unsigned _hd_bkt; \ struct UT_hash_handle *_hd_hh_del; \ if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ head = NULL; \ } else { \ _hd_hh_del = &((delptr)->hh); \ if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ (head)->hh.tbl->tail = \ (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ (head)->hh.tbl->hho); \ } \ if ((delptr)->hh.prev) { \ ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ } else { \ DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ } \ if (_hd_hh_del->next) { \ ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ (head)->hh.tbl->hho))->prev = \ _hd_hh_del->prev; \ } \ HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ (head)->hh.tbl->num_items--; \ } \ HASH_FSCK(hh,head); \ } while (0) /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ #define HASH_FIND_STR(head,findstr,out) \ HASH_FIND(hh,head,findstr,strlen(findstr),out) #define HASH_ADD_STR(head,strfield,add) \ HASH_ADD(hh,head,strfield,strlen(add->strfield),add) #define HASH_REPLACE_STR(head,strfield,add,replaced) \ HASH_REPLACE(hh,head,strfield,strlen(add->strfield),add,replaced) #define HASH_FIND_INT(head,findint,out) \ HASH_FIND(hh,head,findint,sizeof(int),out) #define HASH_ADD_INT(head,intfield,add) \ HASH_ADD(hh,head,intfield,sizeof(int),add) #define HASH_REPLACE_INT(head,intfield,add,replaced) \ HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) #define HASH_FIND_PTR(head,findptr,out) \ HASH_FIND(hh,head,findptr,sizeof(void *),out) #define HASH_ADD_PTR(head,ptrfield,add) \ HASH_ADD(hh,head,ptrfield,sizeof(void *),add) #define HASH_REPLACE_PTR(head,ptrfield,add) \ HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) #define HASH_DEL(head,delptr) \ HASH_DELETE(hh,head,delptr) /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. */ #ifdef HASH_DEBUG #define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) #define HASH_FSCK(hh,head) \ do { \ unsigned _bkt_i; \ unsigned _count, _bkt_count; \ char *_prev; \ struct UT_hash_handle *_thh; \ if (head) { \ _count = 0; \ for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ _bkt_count = 0; \ _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ _prev = NULL; \ while (_thh) { \ if (_prev != (char*)(_thh->hh_prev)) { \ HASH_OOPS("invalid hh_prev %p, actual %p\n", \ _thh->hh_prev, _prev ); \ } \ _bkt_count++; \ _prev = (char*)(_thh); \ _thh = _thh->hh_next; \ } \ _count += _bkt_count; \ if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ HASH_OOPS("invalid bucket count %d, actual %d\n", \ (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ } \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid hh item count %d, actual %d\n", \ (head)->hh.tbl->num_items, _count ); \ } \ /* traverse hh in app order; check next/prev integrity, count */ \ _count = 0; \ _prev = NULL; \ _thh = &(head)->hh; \ while (_thh) { \ _count++; \ if (_prev !=(char*)(_thh->prev)) { \ HASH_OOPS("invalid prev %p, actual %p\n", \ _thh->prev, _prev ); \ } \ _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ (head)->hh.tbl->hho) : NULL ); \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid app item count %d, actual %d\n", \ (head)->hh.tbl->num_items, _count ); \ } \ } \ } while (0) #else #define HASH_FSCK(hh,head) #endif /* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to * the descriptor to which this macro is defined for tuning the hash function. * The app can #include to get the prototype for write(2). */ #ifdef HASH_EMIT_KEYS #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ do { \ unsigned _klen = fieldlen; \ write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ write(HASH_EMIT_KEYS, keyptr, fieldlen); \ } while (0) #else #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) #endif /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ #ifdef HASH_FUNCTION #define HASH_FCN HASH_FUNCTION #else #define HASH_FCN HASH_JEN #endif /* The Bernstein hash function, used in Perl prior to v5.6 */ #define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _hb_keylen=keylen; \ char *_hb_key=(char*)(key); \ (hashv) = 0; \ while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ bkt = (hashv) & (num_bkts-1); \ } while (0) /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ #define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _sx_i; \ char *_hs_key=(char*)(key); \ hashv = 0; \ for(_sx_i=0; _sx_i < keylen; _sx_i++) \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ bkt = hashv & (num_bkts-1); \ } while (0) #define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _fn_i; \ char *_hf_key=(char*)(key); \ hashv = 2166136261UL; \ for(_fn_i=0; _fn_i < keylen; _fn_i++) \ hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ bkt = hashv & (num_bkts-1); \ } while(0) #define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _ho_i; \ char *_ho_key=(char*)(key); \ hashv = 0; \ for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ hashv += _ho_key[_ho_i]; \ hashv += (hashv << 10); \ hashv ^= (hashv >> 6); \ } \ hashv += (hashv << 3); \ hashv ^= (hashv >> 11); \ hashv += (hashv << 15); \ bkt = hashv & (num_bkts-1); \ } while(0) #define HASH_JEN_MIX(a,b,c) \ do { \ a -= b; a -= c; a ^= ( c >> 13 ); \ b -= c; b -= a; b ^= ( a << 8 ); \ c -= a; c -= b; c ^= ( b >> 13 ); \ a -= b; a -= c; a ^= ( c >> 12 ); \ b -= c; b -= a; b ^= ( a << 16 ); \ c -= a; c -= b; c ^= ( b >> 5 ); \ a -= b; a -= c; a ^= ( c >> 3 ); \ b -= c; b -= a; b ^= ( a << 10 ); \ c -= a; c -= b; c ^= ( b >> 15 ); \ } while (0) #define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _hj_i,_hj_j,_hj_k; \ unsigned char *_hj_key=(unsigned char*)(key); \ hashv = 0xfeedbeef; \ _hj_i = _hj_j = 0x9e3779b9; \ _hj_k = (unsigned)keylen; \ while (_hj_k >= 12) { \ _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + ( (unsigned)_hj_key[2] << 16 ) \ + ( (unsigned)_hj_key[3] << 24 ) ); \ _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + ( (unsigned)_hj_key[6] << 16 ) \ + ( (unsigned)_hj_key[7] << 24 ) ); \ hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + ( (unsigned)_hj_key[10] << 16 ) \ + ( (unsigned)_hj_key[11] << 24 ) ); \ \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ \ _hj_key += 12; \ _hj_k -= 12; \ } \ hashv += keylen; \ switch ( _hj_k ) { \ case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ case 5: _hj_j += _hj_key[4]; \ case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ case 1: _hj_i += _hj_key[0]; \ } \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ bkt = hashv & (num_bkts-1); \ } while(0) /* The Paul Hsieh hash function */ #undef get16bits #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) #define get16bits(d) (*((const uint16_t *) (d))) #endif #if !defined (get16bits) #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ +(uint32_t)(((const uint8_t *)(d))[0]) ) #endif #define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned char *_sfh_key=(unsigned char*)(key); \ uint32_t _sfh_tmp, _sfh_len = keylen; \ \ int _sfh_rem = _sfh_len & 3; \ _sfh_len >>= 2; \ hashv = 0xcafebabe; \ \ /* Main loop */ \ for (;_sfh_len > 0; _sfh_len--) { \ hashv += get16bits (_sfh_key); \ _sfh_tmp = (uint32_t)(get16bits (_sfh_key+2)) << 11 ^ hashv; \ hashv = (hashv << 16) ^ _sfh_tmp; \ _sfh_key += 2*sizeof (uint16_t); \ hashv += hashv >> 11; \ } \ \ /* Handle end cases */ \ switch (_sfh_rem) { \ case 3: hashv += get16bits (_sfh_key); \ hashv ^= hashv << 16; \ hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)] << 18); \ hashv += hashv >> 11; \ break; \ case 2: hashv += get16bits (_sfh_key); \ hashv ^= hashv << 11; \ hashv += hashv >> 17; \ break; \ case 1: hashv += *_sfh_key; \ hashv ^= hashv << 10; \ hashv += hashv >> 1; \ } \ \ /* Force "avalanching" of final 127 bits */ \ hashv ^= hashv << 3; \ hashv += hashv >> 5; \ hashv ^= hashv << 4; \ hashv += hashv >> 17; \ hashv ^= hashv << 25; \ hashv += hashv >> 6; \ bkt = hashv & (num_bkts-1); \ } while(0) #ifdef HASH_USING_NO_STRICT_ALIASING /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. * MurmurHash uses the faster approach only on CPU's where we know it's safe. * * Note the preprocessor built-in defines can be emitted using: * * gcc -m64 -dM -E - < /dev/null (on gcc) * cc -## a.c (where a.c is a simple test file) (Sun Studio) */ #if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) #define MUR_GETBLOCK(p,i) p[i] #else /* non intel */ #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 0x3) == 0) #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 0x3) == 1) #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 0x3) == 2) #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 0x3) == 3) #define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) #if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) #define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) #define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) #define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) #else /* assume little endian non-intel */ #define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) #define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) #define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) #endif #define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ MUR_ONE_THREE(p)))) #endif #define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) #define MUR_FMIX(_h) \ do { \ _h ^= _h >> 16; \ _h *= 0x85ebca6b; \ _h ^= _h >> 13; \ _h *= 0xc2b2ae35l; \ _h ^= _h >> 16; \ } while(0) #define HASH_MUR(key,keylen,num_bkts,hashv,bkt) \ do { \ const uint8_t *_mur_data = (const uint8_t*)(key); \ const int _mur_nblocks = (keylen) / 4; \ uint32_t _mur_h1 = 0xf88D5353; \ uint32_t _mur_c1 = 0xcc9e2d51; \ uint32_t _mur_c2 = 0x1b873593; \ uint32_t _mur_k1 = 0; \ const uint8_t *_mur_tail; \ const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+_mur_nblocks*4); \ int _mur_i; \ for(_mur_i = -_mur_nblocks; _mur_i; _mur_i++) { \ _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ \ _mur_h1 ^= _mur_k1; \ _mur_h1 = MUR_ROTL32(_mur_h1,13); \ _mur_h1 = _mur_h1*5+0xe6546b64; \ } \ _mur_tail = (const uint8_t*)(_mur_data + _mur_nblocks*4); \ _mur_k1=0; \ switch((keylen) & 3) { \ case 3: _mur_k1 ^= _mur_tail[2] << 16; \ case 2: _mur_k1 ^= _mur_tail[1] << 8; \ case 1: _mur_k1 ^= _mur_tail[0]; \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ _mur_h1 ^= _mur_k1; \ } \ _mur_h1 ^= (keylen); \ MUR_FMIX(_mur_h1); \ hashv = _mur_h1; \ bkt = hashv & (num_bkts-1); \ } while(0) #endif /* HASH_USING_NO_STRICT_ALIASING */ /* key comparison function; return 0 if keys equal */ #define HASH_KEYCMP(a,b,len) memcmp(a,b,len) /* iterate over items in a known bucket to find desired item */ #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ do { \ if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ else out=NULL; \ while (out) { \ if ((out)->hh.keylen == keylen_in) { \ if ((HASH_KEYCMP((out)->hh.key,keyptr,keylen_in)) == 0) break; \ } \ if ((out)->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,(out)->hh.hh_next)); \ else out = NULL; \ } \ } while(0) /* add an item to a bucket */ #define HASH_ADD_TO_BKT(head,addhh) \ do { \ head.count++; \ (addhh)->hh_next = head.hh_head; \ (addhh)->hh_prev = NULL; \ if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ (head).hh_head=addhh; \ if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ && (addhh)->tbl->noexpand != 1) { \ HASH_EXPAND_BUCKETS((addhh)->tbl); \ } \ } while(0) /* remove an item from a given bucket */ #define HASH_DEL_IN_BKT(hh,head,hh_del) \ (head).count--; \ if ((head).hh_head == hh_del) { \ (head).hh_head = hh_del->hh_next; \ } \ if (hh_del->hh_prev) { \ hh_del->hh_prev->hh_next = hh_del->hh_next; \ } \ if (hh_del->hh_next) { \ hh_del->hh_next->hh_prev = hh_del->hh_prev; \ } /* Bucket expansion has the effect of doubling the number of buckets * and redistributing the items into the new buckets. Ideally the * items will distribute more or less evenly into the new buckets * (the extent to which this is true is a measure of the quality of * the hash function as it applies to the key domain). * * With the items distributed into more buckets, the chain length * (item count) in each bucket is reduced. Thus by expanding buckets * the hash keeps a bound on the chain length. This bounded chain * length is the essence of how a hash provides constant time lookup. * * The calculation of tbl->ideal_chain_maxlen below deserves some * explanation. First, keep in mind that we're calculating the ideal * maximum chain length based on the *new* (doubled) bucket count. * In fractions this is just n/b (n=number of items,b=new num buckets). * Since the ideal chain length is an integer, we want to calculate * ceil(n/b). We don't depend on floating point arithmetic in this * hash, so to calculate ceil(n/b) with integers we could write * * ceil(n/b) = (n/b) + ((n%b)?1:0) * * and in fact a previous version of this hash did just that. * But now we have improved things a bit by recognizing that b is * always a power of two. We keep its base 2 log handy (call it lb), * so now we can write this with a bit shift and logical AND: * * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) * */ #define HASH_EXPAND_BUCKETS(tbl) \ do { \ unsigned _he_bkt; \ unsigned _he_bkt_i; \ struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ memset(_he_new_buckets, 0, \ 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ tbl->ideal_chain_maxlen = \ (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ tbl->nonideal_items = 0; \ for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ { \ _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ while (_he_thh) { \ _he_hh_nxt = _he_thh->hh_next; \ HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ tbl->nonideal_items++; \ _he_newbkt->expand_mult = _he_newbkt->count / \ tbl->ideal_chain_maxlen; \ } \ _he_thh->hh_prev = NULL; \ _he_thh->hh_next = _he_newbkt->hh_head; \ if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ _he_thh; \ _he_newbkt->hh_head = _he_thh; \ _he_thh = _he_hh_nxt; \ } \ } \ uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ tbl->num_buckets *= 2; \ tbl->log2_num_buckets++; \ tbl->buckets = _he_new_buckets; \ tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ (tbl->ineff_expands+1) : 0; \ if (tbl->ineff_expands > 1) { \ tbl->noexpand=1; \ uthash_noexpand_fyi(tbl); \ } \ uthash_expand_fyi(tbl); \ } while(0) /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ /* Note that HASH_SORT assumes the hash handle name to be hh. * HASH_SRT was added to allow the hash handle name to be passed in. */ #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) #define HASH_SRT(hh,head,cmpfcn) \ do { \ unsigned _hs_i; \ unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ if (head) { \ _hs_insize = 1; \ _hs_looping = 1; \ _hs_list = &((head)->hh); \ while (_hs_looping) { \ _hs_p = _hs_list; \ _hs_list = NULL; \ _hs_tail = NULL; \ _hs_nmerges = 0; \ while (_hs_p) { \ _hs_nmerges++; \ _hs_q = _hs_p; \ _hs_psize = 0; \ for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ _hs_psize++; \ _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ if (! (_hs_q) ) break; \ } \ _hs_qsize = _hs_insize; \ while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ if (_hs_psize == 0) { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ _hs_e = _hs_p; \ if (_hs_p){ \ _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ ((void*)((char*)(_hs_p->next) + \ (head)->hh.tbl->hho)) : NULL); \ } \ _hs_psize--; \ } else if (( \ cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ ) <= 0) { \ _hs_e = _hs_p; \ if (_hs_p){ \ _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ ((void*)((char*)(_hs_p->next) + \ (head)->hh.tbl->hho)) : NULL); \ } \ _hs_psize--; \ } else { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } \ if ( _hs_tail ) { \ _hs_tail->next = ((_hs_e) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ } else { \ _hs_list = _hs_e; \ } \ if (_hs_e) { \ _hs_e->prev = ((_hs_tail) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ } \ _hs_tail = _hs_e; \ } \ _hs_p = _hs_q; \ } \ if (_hs_tail){ \ _hs_tail->next = NULL; \ } \ if ( _hs_nmerges <= 1 ) { \ _hs_looping=0; \ (head)->hh.tbl->tail = _hs_tail; \ DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ } \ _hs_insize *= 2; \ } \ HASH_FSCK(hh,head); \ } \ } while (0) /* This function selects items from one hash into another hash. * The end result is that the selected items have dual presence * in both hashes. There is no copy of the items made; rather * they are added into the new hash through a secondary hash * hash handle that must be present in the structure. */ #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ do { \ unsigned _src_bkt, _dst_bkt; \ void *_last_elt=NULL, *_elt; \ UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ if (src) { \ for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ _src_hh; \ _src_hh = _src_hh->hh_next) { \ _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ if (cond(_elt)) { \ _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ _dst_hh->key = _src_hh->key; \ _dst_hh->keylen = _src_hh->keylen; \ _dst_hh->hashv = _src_hh->hashv; \ _dst_hh->prev = _last_elt; \ _dst_hh->next = NULL; \ if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ if (!dst) { \ DECLTYPE_ASSIGN(dst,_elt); \ HASH_MAKE_TABLE(hh_dst,dst); \ } else { \ _dst_hh->tbl = (dst)->hh_dst.tbl; \ } \ HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ (dst)->hh_dst.tbl->num_items++; \ _last_elt = _elt; \ _last_elt_hh = _dst_hh; \ } \ } \ } \ } \ HASH_FSCK(hh_dst,dst); \ } while (0) #define HASH_CLEAR(hh,head) \ do { \ if (head) { \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ (head)=NULL; \ } \ } while(0) #define HASH_OVERHEAD(hh,head) \ (size_t)((((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ (sizeof(UT_hash_table)) + \ (HASH_BLOOM_BYTELEN))) #ifdef NO_DECLTYPE #define HASH_ITER(hh,head,el,tmp) \ for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) #else #define HASH_ITER(hh,head,el,tmp) \ for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) #endif /* obtain a count of items in the hash */ #define HASH_COUNT(head) HASH_CNT(hh,head) #define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; unsigned count; /* expand_mult is normally set to 0. In this situation, the max chain length * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If * the bucket's chain exceeds this length, bucket expansion is triggered). * However, setting expand_mult to a non-zero value delays bucket expansion * (that would be triggered by additions to this particular bucket) * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. * (The multiplier is simply expand_mult+1). The whole idea of this * multiplier is to reduce bucket expansions, since they are expensive, in * situations where we know that a particular bucket tends to be overused. * It is better to let its chain length grow to a longer yet-still-bounded * value, than to do an O(n) bucket expansion too often. */ unsigned expand_mult; } UT_hash_bucket; /* random signature used only to find hash tables in external analysis */ #define HASH_SIGNATURE 0xa0111fe1 #define HASH_BLOOM_SIGNATURE 0xb12220f2 typedef struct UT_hash_table { UT_hash_bucket *buckets; unsigned num_buckets, log2_num_buckets; unsigned num_items; struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ /* in an ideal situation (all buckets used equally), no bucket would have * more than ceil(#items/#buckets) items. that's the ideal chain length. */ unsigned ideal_chain_maxlen; /* nonideal_items is the number of items in the hash whose chain position * exceeds the ideal chain maxlen. these items pay the penalty for an uneven * hash distribution; reaching them in a chain traversal takes >ideal steps */ unsigned nonideal_items; /* ineffective expands occur when a bucket doubling was performed, but * afterward, more than half the items in the hash had nonideal chain * positions. If this happens on two consecutive expansions we inhibit any * further expansion, as it's not helping; this happens when the hash * function isn't a good fit for the key domain. When expansion is inhibited * the hash will still work, albeit no longer in constant time. */ unsigned ineff_expands, noexpand; uint32_t signature; /* used only to find hash tables in external analysis */ #ifdef HASH_BLOOM uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ uint8_t *bloom_bv; char bloom_nbits; #endif } UT_hash_table; typedef struct UT_hash_handle { struct UT_hash_table *tbl; void *prev; /* prev element in app order */ void *next; /* next element in app order */ struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ struct UT_hash_handle *hh_next; /* next hh in bucket order */ void *key; /* ptr to enclosing struct's key */ unsigned keylen; /* enclosing struct's key len */ unsigned hashv; /* result of hash-fcn(key) */ } UT_hash_handle; #endif /* UTHASH_H */ mosquitto-1.6.9/src/deps/utlist.h0000664000175000017500000023714013626052637016053 0ustar rogerroger/* Copyright (c) 2007-2018, Troy D. Hanson http://troydhanson.github.com/uthash/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTLIST_H #define UTLIST_H #define UTLIST_VERSION 2.1.0 #include /* * This file contains macros to manipulate singly and doubly-linked lists. * * 1. LL_ macros: singly-linked lists. * 2. DL_ macros: doubly-linked lists. * 3. CDL_ macros: circular doubly-linked lists. * * To use singly-linked lists, your structure must have a "next" pointer. * To use doubly-linked lists, your structure must "prev" and "next" pointers. * Either way, the pointer to the head of the list must be initialized to NULL. * * ----------------.EXAMPLE ------------------------- * struct item { * int id; * struct item *prev, *next; * } * * struct item *list = NULL: * * int main() { * struct item *item; * ... allocate and populate item ... * DL_APPEND(list, item); * } * -------------------------------------------------- * * For doubly-linked lists, the append and delete macros are O(1) * For singly-linked lists, append and delete are O(n) but prepend is O(1) * The sort macro is O(n log(n)) for all types of single/double/circular lists. */ /* These macros use decltype or the earlier __typeof GNU extension. As decltype is only available in newer compilers (VS2010 or gcc 4.3+ when compiling c++ source) this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ #if !defined(LDECLTYPE) && !defined(NO_DECLTYPE) #if defined(_MSC_VER) /* MS compiler */ #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ #define LDECLTYPE(x) decltype(x) #else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE #endif #elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) #define NO_DECLTYPE #else /* GNU, Sun and other compilers */ #define LDECLTYPE(x) __typeof(x) #endif #endif /* for VS2008 we use some workarounds to get around the lack of decltype, * namely, we always reassign our tmp variable to the list head if we need * to dereference its prev/next pointers, and save/restore the real head.*/ #ifdef NO_DECLTYPE #define IF_NO_DECLTYPE(x) x #define LDECLTYPE(x) char* #define UTLIST_SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } #define UTLIST_NEXT(elt,list,next) ((char*)((list)->next)) #define UTLIST_NEXTASGN(elt,list,to,next) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } /* #define UTLIST_PREV(elt,list,prev) ((char*)((list)->prev)) */ #define UTLIST_PREVASGN(elt,list,to,prev) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } #define UTLIST_RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } #define UTLIST_CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } #else #define IF_NO_DECLTYPE(x) #define UTLIST_SV(elt,list) #define UTLIST_NEXT(elt,list,next) ((elt)->next) #define UTLIST_NEXTASGN(elt,list,to,next) ((elt)->next)=(to) /* #define UTLIST_PREV(elt,list,prev) ((elt)->prev) */ #define UTLIST_PREVASGN(elt,list,to,prev) ((elt)->prev)=(to) #define UTLIST_RS(list) #define UTLIST_CASTASGN(a,b) (a)=(b) #endif /****************************************************************************** * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * * Unwieldy variable names used here to avoid shadowing passed-in variables. * *****************************************************************************/ #define LL_SORT(list, cmp) \ LL_SORT2(list, cmp, next) #define LL_SORT2(list, cmp, next) \ do { \ LDECLTYPE(list) _ls_p; \ LDECLTYPE(list) _ls_q; \ LDECLTYPE(list) _ls_e; \ LDECLTYPE(list) _ls_tail; \ IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ if (list) { \ _ls_insize = 1; \ _ls_looping = 1; \ while (_ls_looping) { \ UTLIST_CASTASGN(_ls_p,list); \ (list) = NULL; \ _ls_tail = NULL; \ _ls_nmerges = 0; \ while (_ls_p) { \ _ls_nmerges++; \ _ls_q = _ls_p; \ _ls_psize = 0; \ for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ _ls_psize++; \ UTLIST_SV(_ls_q,list); _ls_q = UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); \ if (!_ls_q) break; \ } \ _ls_qsize = _ls_insize; \ while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ if (_ls_psize == 0) { \ _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ } else if (_ls_qsize == 0 || !_ls_q) { \ _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ } else if (cmp(_ls_p,_ls_q) <= 0) { \ _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ } else { \ _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ } \ if (_ls_tail) { \ UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_ls_e,next); UTLIST_RS(list); \ } else { \ UTLIST_CASTASGN(list,_ls_e); \ } \ _ls_tail = _ls_e; \ } \ _ls_p = _ls_q; \ } \ if (_ls_tail) { \ UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,NULL,next); UTLIST_RS(list); \ } \ if (_ls_nmerges <= 1) { \ _ls_looping=0; \ } \ _ls_insize *= 2; \ } \ } \ } while (0) #define DL_SORT(list, cmp) \ DL_SORT2(list, cmp, prev, next) #define DL_SORT2(list, cmp, prev, next) \ do { \ LDECLTYPE(list) _ls_p; \ LDECLTYPE(list) _ls_q; \ LDECLTYPE(list) _ls_e; \ LDECLTYPE(list) _ls_tail; \ IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ if (list) { \ _ls_insize = 1; \ _ls_looping = 1; \ while (_ls_looping) { \ UTLIST_CASTASGN(_ls_p,list); \ (list) = NULL; \ _ls_tail = NULL; \ _ls_nmerges = 0; \ while (_ls_p) { \ _ls_nmerges++; \ _ls_q = _ls_p; \ _ls_psize = 0; \ for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ _ls_psize++; \ UTLIST_SV(_ls_q,list); _ls_q = UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); \ if (!_ls_q) break; \ } \ _ls_qsize = _ls_insize; \ while ((_ls_psize > 0) || ((_ls_qsize > 0) && _ls_q)) { \ if (_ls_psize == 0) { \ _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ } else if ((_ls_qsize == 0) || (!_ls_q)) { \ _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ } else if (cmp(_ls_p,_ls_q) <= 0) { \ _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ } else { \ _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ } \ if (_ls_tail) { \ UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_ls_e,next); UTLIST_RS(list); \ } else { \ UTLIST_CASTASGN(list,_ls_e); \ } \ UTLIST_SV(_ls_e,list); UTLIST_PREVASGN(_ls_e,list,_ls_tail,prev); UTLIST_RS(list); \ _ls_tail = _ls_e; \ } \ _ls_p = _ls_q; \ } \ UTLIST_CASTASGN((list)->prev, _ls_tail); \ UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,NULL,next); UTLIST_RS(list); \ if (_ls_nmerges <= 1) { \ _ls_looping=0; \ } \ _ls_insize *= 2; \ } \ } \ } while (0) #define CDL_SORT(list, cmp) \ CDL_SORT2(list, cmp, prev, next) #define CDL_SORT2(list, cmp, prev, next) \ do { \ LDECLTYPE(list) _ls_p; \ LDECLTYPE(list) _ls_q; \ LDECLTYPE(list) _ls_e; \ LDECLTYPE(list) _ls_tail; \ LDECLTYPE(list) _ls_oldhead; \ LDECLTYPE(list) _tmp; \ int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ if (list) { \ _ls_insize = 1; \ _ls_looping = 1; \ while (_ls_looping) { \ UTLIST_CASTASGN(_ls_p,list); \ UTLIST_CASTASGN(_ls_oldhead,list); \ (list) = NULL; \ _ls_tail = NULL; \ _ls_nmerges = 0; \ while (_ls_p) { \ _ls_nmerges++; \ _ls_q = _ls_p; \ _ls_psize = 0; \ for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ _ls_psize++; \ UTLIST_SV(_ls_q,list); \ if (UTLIST_NEXT(_ls_q,list,next) == _ls_oldhead) { \ _ls_q = NULL; \ } else { \ _ls_q = UTLIST_NEXT(_ls_q,list,next); \ } \ UTLIST_RS(list); \ if (!_ls_q) break; \ } \ _ls_qsize = _ls_insize; \ while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ if (_ls_psize == 0) { \ _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ } else if (_ls_qsize == 0 || !_ls_q) { \ _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ } else if (cmp(_ls_p,_ls_q) <= 0) { \ _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ } else { \ _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ } \ if (_ls_tail) { \ UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_ls_e,next); UTLIST_RS(list); \ } else { \ UTLIST_CASTASGN(list,_ls_e); \ } \ UTLIST_SV(_ls_e,list); UTLIST_PREVASGN(_ls_e,list,_ls_tail,prev); UTLIST_RS(list); \ _ls_tail = _ls_e; \ } \ _ls_p = _ls_q; \ } \ UTLIST_CASTASGN((list)->prev,_ls_tail); \ UTLIST_CASTASGN(_tmp,list); \ UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_tmp,next); UTLIST_RS(list); \ if (_ls_nmerges <= 1) { \ _ls_looping=0; \ } \ _ls_insize *= 2; \ } \ } \ } while (0) /****************************************************************************** * singly linked list macros (non-circular) * *****************************************************************************/ #define LL_PREPEND(head,add) \ LL_PREPEND2(head,add,next) #define LL_PREPEND2(head,add,next) \ do { \ (add)->next = (head); \ (head) = (add); \ } while (0) #define LL_CONCAT(head1,head2) \ LL_CONCAT2(head1,head2,next) #define LL_CONCAT2(head1,head2,next) \ do { \ LDECLTYPE(head1) _tmp; \ if (head1) { \ _tmp = (head1); \ while (_tmp->next) { _tmp = _tmp->next; } \ _tmp->next=(head2); \ } else { \ (head1)=(head2); \ } \ } while (0) #define LL_APPEND(head,add) \ LL_APPEND2(head,add,next) #define LL_APPEND2(head,add,next) \ do { \ LDECLTYPE(head) _tmp; \ (add)->next=NULL; \ if (head) { \ _tmp = (head); \ while (_tmp->next) { _tmp = _tmp->next; } \ _tmp->next=(add); \ } else { \ (head)=(add); \ } \ } while (0) #define LL_INSERT_INORDER(head,add,cmp) \ LL_INSERT_INORDER2(head,add,cmp,next) #define LL_INSERT_INORDER2(head,add,cmp,next) \ do { \ LDECLTYPE(head) _tmp; \ if (head) { \ LL_LOWER_BOUND2(head, _tmp, add, cmp, next); \ LL_APPEND_ELEM2(head, _tmp, add, next); \ } else { \ (head) = (add); \ (head)->next = NULL; \ } \ } while (0) #define LL_LOWER_BOUND(head,elt,like,cmp) \ LL_LOWER_BOUND2(head,elt,like,cmp,next) #define LL_LOWER_BOUND2(head,elt,like,cmp,next) \ do { \ if ((head) == NULL || (cmp(head, like)) >= 0) { \ (elt) = NULL; \ } else { \ for ((elt) = (head); (elt)->next != NULL; (elt) = (elt)->next) { \ if (cmp((elt)->next, like) >= 0) { \ break; \ } \ } \ } \ } while (0) #define LL_DELETE(head,del) \ LL_DELETE2(head,del,next) #define LL_DELETE2(head,del,next) \ do { \ LDECLTYPE(head) _tmp; \ if ((head) == (del)) { \ (head)=(head)->next; \ } else { \ _tmp = (head); \ while (_tmp->next && (_tmp->next != (del))) { \ _tmp = _tmp->next; \ } \ if (_tmp->next) { \ _tmp->next = (del)->next; \ } \ } \ } while (0) #define LL_COUNT(head,el,counter) \ LL_COUNT2(head,el,counter,next) \ #define LL_COUNT2(head,el,counter,next) \ do { \ (counter) = 0; \ LL_FOREACH2(head,el,next) { ++(counter); } \ } while (0) #define LL_FOREACH(head,el) \ LL_FOREACH2(head,el,next) #define LL_FOREACH2(head,el,next) \ for ((el) = (head); el; (el) = (el)->next) #define LL_FOREACH_SAFE(head,el,tmp) \ LL_FOREACH_SAFE2(head,el,tmp,next) #define LL_FOREACH_SAFE2(head,el,tmp,next) \ for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) #define LL_SEARCH_SCALAR(head,out,field,val) \ LL_SEARCH_SCALAR2(head,out,field,val,next) #define LL_SEARCH_SCALAR2(head,out,field,val,next) \ do { \ LL_FOREACH2(head,out,next) { \ if ((out)->field == (val)) break; \ } \ } while (0) #define LL_SEARCH(head,out,elt,cmp) \ LL_SEARCH2(head,out,elt,cmp,next) #define LL_SEARCH2(head,out,elt,cmp,next) \ do { \ LL_FOREACH2(head,out,next) { \ if ((cmp(out,elt))==0) break; \ } \ } while (0) #define LL_REPLACE_ELEM2(head, el, add, next) \ do { \ LDECLTYPE(head) _tmp; \ assert((head) != NULL); \ assert((el) != NULL); \ assert((add) != NULL); \ (add)->next = (el)->next; \ if ((head) == (el)) { \ (head) = (add); \ } else { \ _tmp = (head); \ while (_tmp->next && (_tmp->next != (el))) { \ _tmp = _tmp->next; \ } \ if (_tmp->next) { \ _tmp->next = (add); \ } \ } \ } while (0) #define LL_REPLACE_ELEM(head, el, add) \ LL_REPLACE_ELEM2(head, el, add, next) #define LL_PREPEND_ELEM2(head, el, add, next) \ do { \ if (el) { \ LDECLTYPE(head) _tmp; \ assert((head) != NULL); \ assert((add) != NULL); \ (add)->next = (el); \ if ((head) == (el)) { \ (head) = (add); \ } else { \ _tmp = (head); \ while (_tmp->next && (_tmp->next != (el))) { \ _tmp = _tmp->next; \ } \ if (_tmp->next) { \ _tmp->next = (add); \ } \ } \ } else { \ LL_APPEND2(head, add, next); \ } \ } while (0) \ #define LL_PREPEND_ELEM(head, el, add) \ LL_PREPEND_ELEM2(head, el, add, next) #define LL_APPEND_ELEM2(head, el, add, next) \ do { \ if (el) { \ assert((head) != NULL); \ assert((add) != NULL); \ (add)->next = (el)->next; \ (el)->next = (add); \ } else { \ LL_PREPEND2(head, add, next); \ } \ } while (0) \ #define LL_APPEND_ELEM(head, el, add) \ LL_APPEND_ELEM2(head, el, add, next) #ifdef NO_DECLTYPE /* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ #undef LL_CONCAT2 #define LL_CONCAT2(head1,head2,next) \ do { \ char *_tmp; \ if (head1) { \ _tmp = (char*)(head1); \ while ((head1)->next) { (head1) = (head1)->next; } \ (head1)->next = (head2); \ UTLIST_RS(head1); \ } else { \ (head1)=(head2); \ } \ } while (0) #undef LL_APPEND2 #define LL_APPEND2(head,add,next) \ do { \ if (head) { \ (add)->next = head; /* use add->next as a temp variable */ \ while ((add)->next->next) { (add)->next = (add)->next->next; } \ (add)->next->next=(add); \ } else { \ (head)=(add); \ } \ (add)->next=NULL; \ } while (0) #undef LL_INSERT_INORDER2 #define LL_INSERT_INORDER2(head,add,cmp,next) \ do { \ if ((head) == NULL || (cmp(head, add)) >= 0) { \ (add)->next = (head); \ (head) = (add); \ } else { \ char *_tmp = (char*)(head); \ while ((head)->next != NULL && (cmp((head)->next, add)) < 0) { \ (head) = (head)->next; \ } \ (add)->next = (head)->next; \ (head)->next = (add); \ UTLIST_RS(head); \ } \ } while (0) #undef LL_DELETE2 #define LL_DELETE2(head,del,next) \ do { \ if ((head) == (del)) { \ (head)=(head)->next; \ } else { \ char *_tmp = (char*)(head); \ while ((head)->next && ((head)->next != (del))) { \ (head) = (head)->next; \ } \ if ((head)->next) { \ (head)->next = ((del)->next); \ } \ UTLIST_RS(head); \ } \ } while (0) #undef LL_REPLACE_ELEM2 #define LL_REPLACE_ELEM2(head, el, add, next) \ do { \ assert((head) != NULL); \ assert((el) != NULL); \ assert((add) != NULL); \ if ((head) == (el)) { \ (head) = (add); \ } else { \ (add)->next = head; \ while ((add)->next->next && ((add)->next->next != (el))) { \ (add)->next = (add)->next->next; \ } \ if ((add)->next->next) { \ (add)->next->next = (add); \ } \ } \ (add)->next = (el)->next; \ } while (0) #undef LL_PREPEND_ELEM2 #define LL_PREPEND_ELEM2(head, el, add, next) \ do { \ if (el) { \ assert((head) != NULL); \ assert((add) != NULL); \ if ((head) == (el)) { \ (head) = (add); \ } else { \ (add)->next = (head); \ while ((add)->next->next && ((add)->next->next != (el))) { \ (add)->next = (add)->next->next; \ } \ if ((add)->next->next) { \ (add)->next->next = (add); \ } \ } \ (add)->next = (el); \ } else { \ LL_APPEND2(head, add, next); \ } \ } while (0) \ #endif /* NO_DECLTYPE */ /****************************************************************************** * doubly linked list macros (non-circular) * *****************************************************************************/ #define DL_PREPEND(head,add) \ DL_PREPEND2(head,add,prev,next) #define DL_PREPEND2(head,add,prev,next) \ do { \ (add)->next = (head); \ if (head) { \ (add)->prev = (head)->prev; \ (head)->prev = (add); \ } else { \ (add)->prev = (add); \ } \ (head) = (add); \ } while (0) #define DL_APPEND(head,add) \ DL_APPEND2(head,add,prev,next) #define DL_APPEND2(head,add,prev,next) \ do { \ if (head) { \ (add)->prev = (head)->prev; \ (head)->prev->next = (add); \ (head)->prev = (add); \ (add)->next = NULL; \ } else { \ (head)=(add); \ (head)->prev = (head); \ (head)->next = NULL; \ } \ } while (0) #define DL_INSERT_INORDER(head,add,cmp) \ DL_INSERT_INORDER2(head,add,cmp,prev,next) #define DL_INSERT_INORDER2(head,add,cmp,prev,next) \ do { \ LDECLTYPE(head) _tmp; \ if (head) { \ DL_LOWER_BOUND2(head, _tmp, add, cmp, next); \ DL_APPEND_ELEM2(head, _tmp, add, prev, next); \ } else { \ (head) = (add); \ (head)->prev = (head); \ (head)->next = NULL; \ } \ } while (0) #define DL_LOWER_BOUND(head,elt,like,cmp) \ DL_LOWER_BOUND2(head,elt,like,cmp,next) #define DL_LOWER_BOUND2(head,elt,like,cmp,next) \ do { \ if ((head) == NULL || (cmp(head, like)) >= 0) { \ (elt) = NULL; \ } else { \ for ((elt) = (head); (elt)->next != NULL; (elt) = (elt)->next) { \ if ((cmp((elt)->next, like)) >= 0) { \ break; \ } \ } \ } \ } while (0) #define DL_CONCAT(head1,head2) \ DL_CONCAT2(head1,head2,prev,next) #define DL_CONCAT2(head1,head2,prev,next) \ do { \ LDECLTYPE(head1) _tmp; \ if (head2) { \ if (head1) { \ UTLIST_CASTASGN(_tmp, (head2)->prev); \ (head2)->prev = (head1)->prev; \ (head1)->prev->next = (head2); \ UTLIST_CASTASGN((head1)->prev, _tmp); \ } else { \ (head1)=(head2); \ } \ } \ } while (0) #define DL_DELETE(head,del) \ DL_DELETE2(head,del,prev,next) #define DL_DELETE2(head,del,prev,next) \ do { \ assert((head) != NULL); \ assert((del)->prev != NULL); \ if ((del)->prev == (del)) { \ (head)=NULL; \ } else if ((del)==(head)) { \ (del)->next->prev = (del)->prev; \ (head) = (del)->next; \ } else { \ (del)->prev->next = (del)->next; \ if ((del)->next) { \ (del)->next->prev = (del)->prev; \ } else { \ (head)->prev = (del)->prev; \ } \ } \ } while (0) #define DL_COUNT(head,el,counter) \ DL_COUNT2(head,el,counter,next) \ #define DL_COUNT2(head,el,counter,next) \ do { \ (counter) = 0; \ DL_FOREACH2(head,el,next) { ++(counter); } \ } while (0) #define DL_FOREACH(head,el) \ DL_FOREACH2(head,el,next) #define DL_FOREACH2(head,el,next) \ for ((el) = (head); el; (el) = (el)->next) /* this version is safe for deleting the elements during iteration */ #define DL_FOREACH_SAFE(head,el,tmp) \ DL_FOREACH_SAFE2(head,el,tmp,next) #define DL_FOREACH_SAFE2(head,el,tmp,next) \ for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) /* these are identical to their singly-linked list counterparts */ #define DL_SEARCH_SCALAR LL_SEARCH_SCALAR #define DL_SEARCH LL_SEARCH #define DL_SEARCH_SCALAR2 LL_SEARCH_SCALAR2 #define DL_SEARCH2 LL_SEARCH2 #define DL_REPLACE_ELEM2(head, el, add, prev, next) \ do { \ assert((head) != NULL); \ assert((el) != NULL); \ assert((add) != NULL); \ if ((head) == (el)) { \ (head) = (add); \ (add)->next = (el)->next; \ if ((el)->next == NULL) { \ (add)->prev = (add); \ } else { \ (add)->prev = (el)->prev; \ (add)->next->prev = (add); \ } \ } else { \ (add)->next = (el)->next; \ (add)->prev = (el)->prev; \ (add)->prev->next = (add); \ if ((el)->next == NULL) { \ (head)->prev = (add); \ } else { \ (add)->next->prev = (add); \ } \ } \ } while (0) #define DL_REPLACE_ELEM(head, el, add) \ DL_REPLACE_ELEM2(head, el, add, prev, next) #define DL_PREPEND_ELEM2(head, el, add, prev, next) \ do { \ if (el) { \ assert((head) != NULL); \ assert((add) != NULL); \ (add)->next = (el); \ (add)->prev = (el)->prev; \ (el)->prev = (add); \ if ((head) == (el)) { \ (head) = (add); \ } else { \ (add)->prev->next = (add); \ } \ } else { \ DL_APPEND2(head, add, prev, next); \ } \ } while (0) \ #define DL_PREPEND_ELEM(head, el, add) \ DL_PREPEND_ELEM2(head, el, add, prev, next) #define DL_APPEND_ELEM2(head, el, add, prev, next) \ do { \ if (el) { \ assert((head) != NULL); \ assert((add) != NULL); \ (add)->next = (el)->next; \ (add)->prev = (el); \ (el)->next = (add); \ if ((add)->next) { \ (add)->next->prev = (add); \ } else { \ (head)->prev = (add); \ } \ } else { \ DL_PREPEND2(head, add, prev, next); \ } \ } while (0) \ #define DL_APPEND_ELEM(head, el, add) \ DL_APPEND_ELEM2(head, el, add, prev, next) #ifdef NO_DECLTYPE /* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ #undef DL_INSERT_INORDER2 #define DL_INSERT_INORDER2(head,add,cmp,prev,next) \ do { \ if ((head) == NULL) { \ (add)->prev = (add); \ (add)->next = NULL; \ (head) = (add); \ } else if ((cmp(head, add)) >= 0) { \ (add)->prev = (head)->prev; \ (add)->next = (head); \ (head)->prev = (add); \ (head) = (add); \ } else { \ char *_tmp = (char*)(head); \ while ((head)->next && (cmp((head)->next, add)) < 0) { \ (head) = (head)->next; \ } \ (add)->prev = (head); \ (add)->next = (head)->next; \ (head)->next = (add); \ UTLIST_RS(head); \ if ((add)->next) { \ (add)->next->prev = (add); \ } else { \ (head)->prev = (add); \ } \ } \ } while (0) #endif /* NO_DECLTYPE */ /****************************************************************************** * circular doubly linked list macros * *****************************************************************************/ #define CDL_APPEND(head,add) \ CDL_APPEND2(head,add,prev,next) #define CDL_APPEND2(head,add,prev,next) \ do { \ if (head) { \ (add)->prev = (head)->prev; \ (add)->next = (head); \ (head)->prev = (add); \ (add)->prev->next = (add); \ } else { \ (add)->prev = (add); \ (add)->next = (add); \ (head) = (add); \ } \ } while (0) #define CDL_PREPEND(head,add) \ CDL_PREPEND2(head,add,prev,next) #define CDL_PREPEND2(head,add,prev,next) \ do { \ if (head) { \ (add)->prev = (head)->prev; \ (add)->next = (head); \ (head)->prev = (add); \ (add)->prev->next = (add); \ } else { \ (add)->prev = (add); \ (add)->next = (add); \ } \ (head) = (add); \ } while (0) #define CDL_INSERT_INORDER(head,add,cmp) \ CDL_INSERT_INORDER2(head,add,cmp,prev,next) #define CDL_INSERT_INORDER2(head,add,cmp,prev,next) \ do { \ LDECLTYPE(head) _tmp; \ if (head) { \ CDL_LOWER_BOUND2(head, _tmp, add, cmp, next); \ CDL_APPEND_ELEM2(head, _tmp, add, prev, next); \ } else { \ (head) = (add); \ (head)->next = (head); \ (head)->prev = (head); \ } \ } while (0) #define CDL_LOWER_BOUND(head,elt,like,cmp) \ CDL_LOWER_BOUND2(head,elt,like,cmp,next) #define CDL_LOWER_BOUND2(head,elt,like,cmp,next) \ do { \ if ((head) == NULL || (cmp(head, like)) >= 0) { \ (elt) = NULL; \ } else { \ for ((elt) = (head); (elt)->next != (head); (elt) = (elt)->next) { \ if ((cmp((elt)->next, like)) >= 0) { \ break; \ } \ } \ } \ } while (0) #define CDL_DELETE(head,del) \ CDL_DELETE2(head,del,prev,next) #define CDL_DELETE2(head,del,prev,next) \ do { \ if (((head)==(del)) && ((head)->next == (head))) { \ (head) = NULL; \ } else { \ (del)->next->prev = (del)->prev; \ (del)->prev->next = (del)->next; \ if ((del) == (head)) (head)=(del)->next; \ } \ } while (0) #define CDL_COUNT(head,el,counter) \ CDL_COUNT2(head,el,counter,next) \ #define CDL_COUNT2(head, el, counter,next) \ do { \ (counter) = 0; \ CDL_FOREACH2(head,el,next) { ++(counter); } \ } while (0) #define CDL_FOREACH(head,el) \ CDL_FOREACH2(head,el,next) #define CDL_FOREACH2(head,el,next) \ for ((el)=(head);el;(el)=(((el)->next==(head)) ? NULL : (el)->next)) #define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ CDL_FOREACH_SAFE2(head,el,tmp1,tmp2,prev,next) #define CDL_FOREACH_SAFE2(head,el,tmp1,tmp2,prev,next) \ for ((el) = (head), (tmp1) = (head) ? (head)->prev : NULL; \ (el) && ((tmp2) = (el)->next, 1); \ (el) = ((el) == (tmp1) ? NULL : (tmp2))) #define CDL_SEARCH_SCALAR(head,out,field,val) \ CDL_SEARCH_SCALAR2(head,out,field,val,next) #define CDL_SEARCH_SCALAR2(head,out,field,val,next) \ do { \ CDL_FOREACH2(head,out,next) { \ if ((out)->field == (val)) break; \ } \ } while (0) #define CDL_SEARCH(head,out,elt,cmp) \ CDL_SEARCH2(head,out,elt,cmp,next) #define CDL_SEARCH2(head,out,elt,cmp,next) \ do { \ CDL_FOREACH2(head,out,next) { \ if ((cmp(out,elt))==0) break; \ } \ } while (0) #define CDL_REPLACE_ELEM2(head, el, add, prev, next) \ do { \ assert((head) != NULL); \ assert((el) != NULL); \ assert((add) != NULL); \ if ((el)->next == (el)) { \ (add)->next = (add); \ (add)->prev = (add); \ (head) = (add); \ } else { \ (add)->next = (el)->next; \ (add)->prev = (el)->prev; \ (add)->next->prev = (add); \ (add)->prev->next = (add); \ if ((head) == (el)) { \ (head) = (add); \ } \ } \ } while (0) #define CDL_REPLACE_ELEM(head, el, add) \ CDL_REPLACE_ELEM2(head, el, add, prev, next) #define CDL_PREPEND_ELEM2(head, el, add, prev, next) \ do { \ if (el) { \ assert((head) != NULL); \ assert((add) != NULL); \ (add)->next = (el); \ (add)->prev = (el)->prev; \ (el)->prev = (add); \ (add)->prev->next = (add); \ if ((head) == (el)) { \ (head) = (add); \ } \ } else { \ CDL_APPEND2(head, add, prev, next); \ } \ } while (0) #define CDL_PREPEND_ELEM(head, el, add) \ CDL_PREPEND_ELEM2(head, el, add, prev, next) #define CDL_APPEND_ELEM2(head, el, add, prev, next) \ do { \ if (el) { \ assert((head) != NULL); \ assert((add) != NULL); \ (add)->next = (el)->next; \ (add)->prev = (el); \ (el)->next = (add); \ (add)->next->prev = (add); \ } else { \ CDL_PREPEND2(head, add, prev, next); \ } \ } while (0) #define CDL_APPEND_ELEM(head, el, add) \ CDL_APPEND_ELEM2(head, el, add, prev, next) #ifdef NO_DECLTYPE /* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ #undef CDL_INSERT_INORDER2 #define CDL_INSERT_INORDER2(head,add,cmp,prev,next) \ do { \ if ((head) == NULL) { \ (add)->prev = (add); \ (add)->next = (add); \ (head) = (add); \ } else if ((cmp(head, add)) >= 0) { \ (add)->prev = (head)->prev; \ (add)->next = (head); \ (add)->prev->next = (add); \ (head)->prev = (add); \ (head) = (add); \ } else { \ char *_tmp = (char*)(head); \ while ((char*)(head)->next != _tmp && (cmp((head)->next, add)) < 0) { \ (head) = (head)->next; \ } \ (add)->prev = (head); \ (add)->next = (head)->next; \ (add)->next->prev = (add); \ (head)->next = (add); \ UTLIST_RS(head); \ } \ } while (0) #endif /* NO_DECLTYPE */ #endif /* UTLIST_H */ mosquitto-1.6.9/src/signals.c0000664000175000017500000000600313626052637015217 0ustar rogerroger/* Copyright (c) 2016-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. Dmitry Kaukov - windows named events implementation. */ #include "config.h" #ifndef WIN32 # include # include # include #endif #ifndef WIN32 #include #else #include #include #include #endif #ifndef WIN32 # include #endif #include #include #include #include #ifdef WITH_SYSTEMD # include #endif #ifdef WITH_WRAP #include #endif #ifdef WITH_WEBSOCKETS # include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "util_mosq.h" extern bool flag_reload; #ifdef WITH_PERSISTENCE extern bool flag_db_backup; #endif extern bool flag_tree_print; extern int run; #ifdef SIGHUP /* Signal handler for SIGHUP - flag a config reload. */ void handle_sighup(int signal) { UNUSED(signal); flag_reload = true; } #endif /* Signal handler for SIGINT and SIGTERM - just stop gracefully. */ void handle_sigint(int signal) { UNUSED(signal); run = 0; } /* Signal handler for SIGUSR1 - backup the db. */ void handle_sigusr1(int signal) { UNUSED(signal); #ifdef WITH_PERSISTENCE flag_db_backup = true; #endif } /* Signal handler for SIGUSR2 - print subscription / retained tree. */ void handle_sigusr2(int signal) { UNUSED(signal); flag_tree_print = true; } /* * * Signalling mosquitto process on Win32. * * On Windows we we can use named events to pass signals to the mosquitto process. * List of events : * * mosqPID_shutdown * mosqPID_reload * mosqPID_backup * * (where PID is the PID of the mosquitto process). */ #ifdef WIN32 DWORD WINAPI SigThreadProc(void* data) { TCHAR evt_name[MAX_PATH]; static HANDLE evt[3]; int pid = GetCurrentProcessId(); sprintf_s(evt_name, MAX_PATH, "mosq%d_shutdown", pid); evt[0] = CreateEvent(NULL, TRUE, FALSE, evt_name); sprintf_s(evt_name, MAX_PATH, "mosq%d_reload", pid); evt[1] = CreateEvent(NULL, FALSE, FALSE, evt_name); sprintf_s(evt_name, MAX_PATH, "mosq%d_backup", pid); evt[2] = CreateEvent(NULL, FALSE, FALSE, evt_name); while (true) { int wr = WaitForMultipleObjects(sizeof(evt) / sizeof(HANDLE), evt, FALSE, INFINITE); switch (wr) { case WAIT_OBJECT_0 + 0: handle_sigint(SIGINT); break; case WAIT_OBJECT_0 + 1: flag_reload = true; continue; case WAIT_OBJECT_0 + 2: handle_sigusr1(0); continue; break; } } CloseHandle(evt[0]); CloseHandle(evt[1]); CloseHandle(evt[2]); return 0; } #endif mosquitto-1.6.9/src/mosquitto_broker.h0000664000175000017500000001043613626052637017201 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_BROKER_H #define MOSQUITTO_BROKER_H #ifdef __cplusplus extern "C" { #endif #include struct mosquitto; enum mosquitto_protocol { mp_mqtt, mp_mqttsn, mp_websockets }; /* ========================================================================= * * Utility Functions * * Use these functions from within your plugin. * * There are also very useful functions in libmosquitto. * * ========================================================================= */ /* * Function: mosquitto_log_printf * * Write a log message using the broker configured logging. * * Parameters: * level - Log message priority. Can currently be one of: * * MOSQ_LOG_INFO * MOSQ_LOG_NOTICE * MOSQ_LOG_WARNING * MOSQ_LOG_ERR * MOSQ_LOG_DEBUG * MOSQ_LOG_SUBSCRIBE (not recommended for use by plugins) * MOSQ_LOG_UNSUBSCRIBE (not recommended for use by plugins) * * These values are defined in mosquitto.h. * * fmt, ... - printf style format and arguments. */ void mosquitto_log_printf(int level, const char *fmt, ...); /* ========================================================================= * * Client Functions * * Use these functions to access client information. * * ========================================================================= */ /* * Function: mosquitto_client_address * * Retrieve the IP address of the client as a string. */ const char *mosquitto_client_address(const struct mosquitto *client); /* * Function: mosquitto_client_clean_session * * Retrieve the clean session flag value for a client. */ bool mosquitto_client_clean_session(const struct mosquitto *client); /* * Function: mosquitto_client_id * * Retrieve the client id associated with a client. */ const char *mosquitto_client_id(const struct mosquitto *client); /* * Function: mosquitto_client_keepalive * * Retrieve the keepalive value for a client. */ int mosquitto_client_keepalive(const struct mosquitto *client); /* * Function: mosquitto_client_certificate * * If TLS support is enabled, return the certificate provided by a client as an * X509 pointer from openssl. If the client did not provide a certificate, then * NULL will be returned. This function will only ever return a non-NULL value * if the `require_certificate` option is set to true. * * If TLS is not supported, this function will always return NULL. */ void *mosquitto_client_certificate(const struct mosquitto *client); /* * Function: mosquitto_client_protocol * * Retrieve the protocol with which the client has connected. Can be one of: * * mp_mqtt (MQTT over TCP) * mp_mqttsn (MQTT-SN) * mp_websockets (MQTT over Websockets) */ int mosquitto_client_protocol(const struct mosquitto *client); /* * Function: mosquitto_client_sub_count * * Retrieve the number of subscriptions that have been made by a client. */ int mosquitto_client_sub_count(const struct mosquitto *client); /* * Function: mosquitto_client_username * * Retrieve the username associated with a client. */ const char *mosquitto_client_username(const struct mosquitto *client); /* Function: mosquitto_set_username * * Set the username for a client. * * This removes and replaces the current username for a client and hence * updates its access. * * username can be NULL, in which case the client will become anonymous, but * must not be zero length. * * In the case of error, the client will be left with its original username. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client is NULL, or if username is zero length * MOSQ_ERR_NOMEM - on out of memory */ int mosquitto_set_username(struct mosquitto *client, const char *username); #ifdef __cplusplus } #endif #endif mosquitto-1.6.9/src/subs.c0000664000175000017500000007273613626052637014553 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ /* A note on matching topic subscriptions. * * Topics can be up to 32767 characters in length. The / character is used as a * hierarchy delimiter. Messages are published to a particular topic. * Clients may subscribe to particular topics directly, but may also use * wildcards in subscriptions. The + and # characters are used as wildcards. * The # wildcard can be used at the end of a subscription only, and is a * wildcard for the level of hierarchy at which it is placed and all subsequent * levels. * The + wildcard may be used at any point within the subscription and is a * wildcard for only the level of hierarchy at which it is placed. * Neither wildcard may be used as part of a substring. * Valid: * a/b/+ * a/+/c * a/# * a/b/# * # * +/b/c * +/+/+ * Invalid: * a/#/c * a+/b/c * Valid but non-matching: * a/b * a/+ * +/b * b/c/a * a/b/d */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "util_mosq.h" #include "utlist.h" struct sub__token { struct sub__token *next; char *topic; uint16_t topic_len; }; static int subs__send(struct mosquitto_db *db, struct mosquitto__subleaf *leaf, const char *topic, int qos, int retain, struct mosquitto_msg_store *stored) { bool client_retain; uint16_t mid; int client_qos, msg_qos; mosquitto_property *properties = NULL; int rc2; /* Check for ACL topic access. */ rc2 = mosquitto_acl_check(db, leaf->context, topic, stored->payloadlen, UHPA_ACCESS(stored->payload, stored->payloadlen), stored->qos, stored->retain, MOSQ_ACL_READ); if(rc2 == MOSQ_ERR_ACL_DENIED){ return MOSQ_ERR_SUCCESS; }else if(rc2 == MOSQ_ERR_SUCCESS){ client_qos = leaf->qos; if(db->config->upgrade_outgoing_qos){ msg_qos = client_qos; }else{ if(qos > client_qos){ msg_qos = client_qos; }else{ msg_qos = qos; } } if(msg_qos){ mid = mosquitto__mid_generate(leaf->context); }else{ mid = 0; } if(leaf->retain_as_published){ client_retain = retain; }else{ client_retain = false; } if(leaf->identifier){ mosquitto_property_add_varint(&properties, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, leaf->identifier); } if(db__message_insert(db, leaf->context, mid, mosq_md_out, msg_qos, client_retain, stored, properties) == 1){ return 1; } }else{ return 1; /* Application error */ } return 0; } static int subs__shared_process(struct mosquitto_db *db, struct mosquitto__subhier *hier, const char *topic, int qos, int retain, struct mosquitto_msg_store *stored) { int rc = 0, rc2; struct mosquitto__subshared *shared, *shared_tmp; struct mosquitto__subleaf *leaf; HASH_ITER(hh, hier->shared, shared, shared_tmp){ leaf = shared->subs; rc2 = subs__send(db, leaf, topic, qos, retain, stored); /* Remove current from the top, add back to the bottom */ DL_DELETE(shared->subs, leaf); DL_APPEND(shared->subs, leaf); if(rc2) rc = 1; } return rc; } static int subs__process(struct mosquitto_db *db, struct mosquitto__subhier *hier, const char *source_id, const char *topic, int qos, int retain, struct mosquitto_msg_store *stored, bool set_retain) { int rc = 0; int rc2; struct mosquitto__subleaf *leaf; if(retain && set_retain){ #ifdef WITH_PERSISTENCE if(strncmp(topic, "$SYS", 4)){ /* Retained messages count as a persistence change, but only if * they aren't for $SYS. */ db->persistence_changes++; } #endif if(hier->retained){ db__msg_store_ref_dec(db, &hier->retained); #ifdef WITH_SYS_TREE db->retained_count--; #endif } if(stored->payloadlen){ hier->retained = stored; db__msg_store_ref_inc(hier->retained); #ifdef WITH_SYS_TREE db->retained_count++; #endif }else{ hier->retained = NULL; } } rc = subs__shared_process(db, hier, topic, qos, retain, stored); leaf = hier->subs; while(source_id && leaf){ if(!leaf->context->id || (leaf->no_local && !strcmp(leaf->context->id, source_id))){ leaf = leaf->next; continue; } rc2 = subs__send(db, leaf, topic, qos, retain, stored); if(rc2){ rc = 1; } leaf = leaf->next; } if(hier->subs || hier->shared){ return rc; }else{ return MOSQ_ERR_NO_SUBSCRIBERS; } } static struct sub__token *sub__topic_append(struct sub__token **tail, struct sub__token **topics, char *topic) { struct sub__token *new_topic; if(!topic){ return NULL; } new_topic = mosquitto__malloc(sizeof(struct sub__token)); if(!new_topic){ return NULL; } new_topic->next = NULL; new_topic->topic_len = strlen(topic); new_topic->topic = mosquitto__malloc(new_topic->topic_len+1); if(!new_topic->topic){ mosquitto__free(new_topic); return NULL; } strncpy(new_topic->topic, topic, new_topic->topic_len+1); if(*tail){ (*tail)->next = new_topic; *tail = (*tail)->next; }else{ *topics = new_topic; *tail = new_topic; } return new_topic; } static int sub__topic_tokenise(const char *subtopic, struct sub__token **topics) { struct sub__token *new_topic, *tail = NULL; size_t len; size_t start, stop, tlen; int i; char *topic; int count = 0; assert(subtopic); assert(topics); len = strlen(subtopic); if(len == 0){ return 1; } if(subtopic[0] != '$'){ new_topic = sub__topic_append(&tail, topics, ""); if(!new_topic) goto cleanup; } if(subtopic[0] == '/'){ new_topic = sub__topic_append(&tail, topics, ""); if(!new_topic) goto cleanup; start = 1; }else{ start = 0; } for(i=start; i TOPIC_HIERARCHY_LIMIT){ /* Set limit on hierarchy levels, to restrict stack usage. */ goto cleanup; } if(*topics != NULL){ return MOSQ_ERR_SUCCESS; }else{ return 1; } cleanup: tail = *topics; *topics = NULL; while(tail){ mosquitto__free(tail->topic); new_topic = tail->next; mosquitto__free(tail); tail = new_topic; } return 1; } static void sub__topic_tokens_free(struct sub__token *tokens) { struct sub__token *tail; while(tokens){ tail = tokens->next; mosquitto__free(tokens->topic); mosquitto__free(tokens); tokens = tail; } } static int sub__add_leaf(struct mosquitto *context, int qos, uint32_t identifier, int options, struct mosquitto__subleaf **head, struct mosquitto__subleaf **newleaf) { struct mosquitto__subleaf *leaf; *newleaf = NULL; leaf = *head; while(leaf){ if(leaf->context && leaf->context->id && !strcmp(leaf->context->id, context->id)){ /* Client making a second subscription to same topic. Only * need to update QoS. Return MOSQ_ERR_SUB_EXISTS to * indicate this to the calling function. */ leaf->qos = qos; leaf->identifier = identifier; return MOSQ_ERR_SUB_EXISTS; } leaf = leaf->next; } leaf = mosquitto__calloc(1, sizeof(struct mosquitto__subleaf)); if(!leaf) return MOSQ_ERR_NOMEM; leaf->context = context; leaf->qos = qos; leaf->identifier = identifier; leaf->no_local = ((options & MQTT_SUB_OPT_NO_LOCAL) != 0); leaf->retain_as_published = ((options & MQTT_SUB_OPT_RETAIN_AS_PUBLISHED) != 0); DL_APPEND(*head, leaf); *newleaf = leaf; return MOSQ_ERR_SUCCESS; } static void sub__remove_shared_leaf(struct mosquitto__subhier *subhier, struct mosquitto__subshared *shared, struct mosquitto__subleaf *leaf) { DL_DELETE(shared->subs, leaf); if(shared->subs == NULL){ HASH_DELETE(hh, subhier->shared, shared); mosquitto__free(shared->name); mosquitto__free(shared); } mosquitto__free(leaf); } static int sub__add_shared(struct mosquitto_db *db, struct mosquitto *context, int qos, uint32_t identifier, int options, struct mosquitto__subhier *subhier, char *sharename) { struct mosquitto__subleaf *newleaf; struct mosquitto__subshared *shared = NULL; struct mosquitto__subshared_ref **shared_subs; struct mosquitto__subshared_ref *shared_ref; int i; unsigned int slen; int rc; slen = strlen(sharename); HASH_FIND(hh, subhier->shared, sharename, slen, shared); if(shared){ mosquitto__free(sharename); }else{ shared = mosquitto__calloc(1, sizeof(struct mosquitto__subshared)); if(!shared){ mosquitto__free(sharename); return MOSQ_ERR_NOMEM; } shared->name = sharename; HASH_ADD_KEYPTR(hh, subhier->shared, shared->name, slen, shared); } rc = sub__add_leaf(context, qos, identifier, options, &shared->subs, &newleaf); if(rc > 0){ if(shared->subs == NULL){ HASH_DELETE(hh, subhier->shared, shared); mosquitto__free(shared->name); mosquitto__free(shared); } return rc; } if(rc != MOSQ_ERR_SUB_EXISTS){ shared_ref = mosquitto__calloc(1, sizeof(struct mosquitto__subshared_ref)); if(!shared_ref){ sub__remove_shared_leaf(subhier, shared, newleaf); return MOSQ_ERR_NOMEM; } shared_ref->hier = subhier; shared_ref->shared = shared; for(i=0; ishared_sub_count; i++){ if(!context->shared_subs[i]){ context->shared_subs[i] = shared_ref; break; } } if(i == context->shared_sub_count){ shared_subs = mosquitto__realloc(context->shared_subs, sizeof(struct mosquitto__subhier_ref *)*(context->shared_sub_count + 1)); if(!shared_subs){ sub__remove_shared_leaf(subhier, shared, newleaf); return MOSQ_ERR_NOMEM; } context->shared_subs = shared_subs; context->shared_sub_count++; context->shared_subs[context->shared_sub_count-1] = shared_ref; } #ifdef WITH_SYS_TREE db->shared_subscription_count++; #endif } if(context->protocol == mosq_p_mqtt31 || context->protocol == mosq_p_mqtt5){ return rc; }else{ /* mqttv311/mqttv5 requires retained messages are resent on * resubscribe. */ return MOSQ_ERR_SUCCESS; } } static int sub__add_normal(struct mosquitto_db *db, struct mosquitto *context, int qos, uint32_t identifier, int options, struct mosquitto__subhier *subhier) { struct mosquitto__subleaf *newleaf = NULL; struct mosquitto__subhier **subs; int i; int rc; rc = sub__add_leaf(context, qos, identifier, options, &subhier->subs, &newleaf); if(rc > 0){ return rc; } if(rc != MOSQ_ERR_SUB_EXISTS){ for(i=0; isub_count; i++){ if(!context->subs[i]){ context->subs[i] = subhier; break; } } if(i == context->sub_count){ subs = mosquitto__realloc(context->subs, sizeof(struct mosquitto__subhier *)*(context->sub_count + 1)); if(!subs){ DL_DELETE(subhier->subs, newleaf); mosquitto__free(newleaf); return MOSQ_ERR_NOMEM; } context->subs = subs; context->sub_count++; context->subs[context->sub_count-1] = subhier; } #ifdef WITH_SYS_TREE db->subscription_count++; #endif } if(context->protocol == mosq_p_mqtt31 || context->protocol == mosq_p_mqtt5){ return rc; }else{ /* mqttv311/mqttv5 requires retained messages are resent on * resubscribe. */ return MOSQ_ERR_SUCCESS; } } static int sub__add_context(struct mosquitto_db *db, struct mosquitto *context, int qos, uint32_t identifier, int options, struct mosquitto__subhier *subhier, struct sub__token *tokens, char *sharename) { struct mosquitto__subhier *branch; /* Find leaf node */ while(tokens){ HASH_FIND(hh, subhier->children, tokens->topic, tokens->topic_len, branch); if(!branch){ /* Not found */ branch = sub__add_hier_entry(subhier, &subhier->children, tokens->topic, tokens->topic_len); if(!branch) return MOSQ_ERR_NOMEM; } subhier = branch; tokens = tokens ->next; } /* Add add our context */ if(context && context->id){ if(sharename){ return sub__add_shared(db, context, qos, identifier, options, subhier, sharename); }else{ return sub__add_normal(db, context, qos, identifier, options, subhier); } }else{ return MOSQ_ERR_SUCCESS; } } static int sub__remove_normal(struct mosquitto_db *db, struct mosquitto *context, struct mosquitto__subhier *subhier, uint8_t *reason) { struct mosquitto__subleaf *leaf; int i; leaf = subhier->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db->subscription_count--; #endif DL_DELETE(subhier->subs, leaf); mosquitto__free(leaf); /* Remove the reference to the sub that the client is keeping. * It would be nice to be able to use the reference directly, * but that would involve keeping a copy of the topic string in * each subleaf. Might be worth considering though. */ for(i=0; isub_count; i++){ if(context->subs[i] == subhier){ context->subs[i] = NULL; break; } } *reason = 0; return MOSQ_ERR_SUCCESS; } leaf = leaf->next; } return MOSQ_ERR_NO_SUBSCRIBERS; } static int sub__remove_shared(struct mosquitto_db *db, struct mosquitto *context, struct mosquitto__subhier *subhier, uint8_t *reason, char *sharename) { struct mosquitto__subshared *shared; struct mosquitto__subleaf *leaf; int i; HASH_FIND(hh, subhier->shared, sharename, strlen(sharename), shared); mosquitto__free(sharename); if(shared){ leaf = shared->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db->shared_subscription_count--; #endif DL_DELETE(shared->subs, leaf); mosquitto__free(leaf); /* Remove the reference to the sub that the client is keeping. * It would be nice to be able to use the reference directly, * but that would involve keeping a copy of the topic string in * each subleaf. Might be worth considering though. */ for(i=0; ishared_sub_count; i++){ if(context->shared_subs[i] && context->shared_subs[i]->hier == subhier && context->shared_subs[i]->shared == shared){ mosquitto__free(context->shared_subs[i]); context->shared_subs[i] = NULL; break; } } if(shared->subs == NULL){ HASH_DELETE(hh, subhier->shared, shared); mosquitto__free(shared->name); mosquitto__free(shared); } *reason = 0; return MOSQ_ERR_SUCCESS; } leaf = leaf->next; } return MOSQ_ERR_NO_SUBSCRIBERS; }else{ return MOSQ_ERR_NO_SUBSCRIBERS; } } static int sub__remove_recurse(struct mosquitto_db *db, struct mosquitto *context, struct mosquitto__subhier *subhier, struct sub__token *tokens, uint8_t *reason, char *sharename) { struct mosquitto__subhier *branch; if(!tokens){ if(sharename){ return sub__remove_shared(db, context, subhier, reason, sharename); }else{ return sub__remove_normal(db, context, subhier, reason); } } HASH_FIND(hh, subhier->children, tokens->topic, tokens->topic_len, branch); if(branch){ sub__remove_recurse(db, context, branch, tokens->next, reason, sharename); if(!branch->children && !branch->subs && !branch->retained && !branch->shared){ HASH_DELETE(hh, subhier->children, branch); mosquitto__free(branch->topic); mosquitto__free(branch); } } return MOSQ_ERR_SUCCESS; } static int sub__search(struct mosquitto_db *db, struct mosquitto__subhier *subhier, struct sub__token *tokens, const char *source_id, const char *topic, int qos, int retain, struct mosquitto_msg_store *stored, bool set_retain) { /* FIXME - need to take into account source_id if the client is a bridge */ struct mosquitto__subhier *branch; int rc; bool have_subscribers = false; if(tokens){ /* Check for literal match */ HASH_FIND(hh, subhier->children, tokens->topic, tokens->topic_len, branch); if(branch){ rc = sub__search(db, branch, tokens->next, source_id, topic, qos, retain, stored, set_retain); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } if(!tokens->next){ rc = subs__process(db, branch, source_id, topic, qos, retain, stored, set_retain); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } } } /* Check for + match */ HASH_FIND(hh, subhier->children, "+", 1, branch); if(branch){ rc = sub__search(db, branch, tokens->next, source_id, topic, qos, retain, stored, false); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } if(!tokens->next){ rc = subs__process(db, branch, source_id, topic, qos, retain, stored, false); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } } } } /* Check for # match */ HASH_FIND(hh, subhier->children, "#", 1, branch); if(branch && !branch->children){ /* The topic matches due to a # wildcard - process the * subscriptions but *don't* return. Although this branch has ended * there may still be other subscriptions to deal with. */ rc = subs__process(db, branch, source_id, topic, qos, retain, stored, false); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } } if(have_subscribers){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NO_SUBSCRIBERS; } } struct mosquitto__subhier *sub__add_hier_entry(struct mosquitto__subhier *parent, struct mosquitto__subhier **sibling, const char *topic, size_t len) { struct mosquitto__subhier *child; assert(sibling); child = mosquitto__calloc(1, sizeof(struct mosquitto__subhier)); if(!child){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return NULL; } child->parent = parent; child->topic_len = len; child->topic = mosquitto__malloc(len+1); if(!child->topic){ child->topic_len = 0; mosquitto__free(child); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return NULL; }else{ strncpy(child->topic, topic, child->topic_len+1); } HASH_ADD_KEYPTR(hh, *sibling, child->topic, child->topic_len, child); return child; } int sub__add(struct mosquitto_db *db, struct mosquitto *context, const char *sub, int qos, uint32_t identifier, int options, struct mosquitto__subhier **root) { int rc = 0; struct mosquitto__subhier *subhier; struct sub__token *tokens = NULL, *t; char *sharename = NULL; assert(root); assert(*root); assert(sub); if(sub__topic_tokenise(sub, &tokens)) return 1; if(!strcmp(tokens->topic, "$share")){ if(!tokens->next || !tokens->next->next){ sub__topic_tokens_free(tokens); return MOSQ_ERR_PROTOCOL; } t = tokens->next; mosquitto__free(tokens->topic); mosquitto__free(tokens); tokens = t; sharename = tokens->topic; tokens->topic = mosquitto__strdup(""); if(!tokens->topic){ tokens->topic = sharename; sub__topic_tokens_free(tokens); return MOSQ_ERR_PROTOCOL; } tokens->topic_len = 0; } HASH_FIND(hh, *root, tokens->topic, tokens->topic_len, subhier); if(!subhier){ subhier = sub__add_hier_entry(NULL, root, tokens->topic, tokens->topic_len); if(!subhier){ sub__topic_tokens_free(tokens); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } rc = sub__add_context(db, context, qos, identifier, options, subhier, tokens, sharename); sub__topic_tokens_free(tokens); return rc; } int sub__remove(struct mosquitto_db *db, struct mosquitto *context, const char *sub, struct mosquitto__subhier *root, uint8_t *reason) { int rc = 0; struct mosquitto__subhier *subhier; struct sub__token *tokens = NULL, *t; char *sharename = NULL; assert(root); assert(sub); if(sub__topic_tokenise(sub, &tokens)) return 1; if(!strcmp(tokens->topic, "$share")){ if(!tokens->next || !tokens->next->next){ sub__topic_tokens_free(tokens); return MOSQ_ERR_PROTOCOL; } t = tokens->next; mosquitto__free(tokens->topic); mosquitto__free(tokens); tokens = t; sharename = tokens->topic; tokens->topic = mosquitto__strdup(""); if(!tokens->topic){ tokens->topic = sharename; sub__topic_tokens_free(tokens); return MOSQ_ERR_PROTOCOL; } tokens->topic_len = 0; } HASH_FIND(hh, root, tokens->topic, tokens->topic_len, subhier); if(subhier){ *reason = MQTT_RC_NO_SUBSCRIPTION_EXISTED; rc = sub__remove_recurse(db, context, subhier, tokens, reason, sharename); } sub__topic_tokens_free(tokens); return rc; } int sub__messages_queue(struct mosquitto_db *db, const char *source_id, const char *topic, int qos, int retain, struct mosquitto_msg_store **stored) { int rc = 0; struct mosquitto__subhier *subhier; struct sub__token *tokens = NULL; assert(db); assert(topic); if(sub__topic_tokenise(topic, &tokens)) return 1; /* Protect this message until we have sent it to all clients - this is required because websockets client calls db__message_write(), which could remove the message if ref_count==0. */ db__msg_store_ref_inc(*stored); HASH_FIND(hh, db->subs, tokens->topic, tokens->topic_len, subhier); if(subhier){ if(retain){ /* We have a message that needs to be retained, so ensure that the subscription * tree for its topic exists. */ sub__add_context(db, NULL, 0, 0, 0, subhier, tokens, NULL); } rc = sub__search(db, subhier, tokens, source_id, topic, qos, retain, *stored, true); } sub__topic_tokens_free(tokens); /* Remove our reference and free if needed. */ db__msg_store_ref_dec(db, stored); return rc; } /* Remove a subhier element, and return its parent if that needs freeing as well. */ static struct mosquitto__subhier *tmp_remove_subs(struct mosquitto__subhier *sub) { struct mosquitto__subhier *parent; if(!sub || !sub->parent){ return NULL; } if(sub->children || sub->subs || sub->retained){ return NULL; } parent = sub->parent; HASH_DELETE(hh, parent->children, sub); mosquitto__free(sub->topic); mosquitto__free(sub); if(parent->subs == NULL && parent->children == NULL && parent->retained == NULL && parent->shared == NULL && parent->parent){ return parent; }else{ return NULL; } } static int sub__clean_session_shared(struct mosquitto_db *db, struct mosquitto *context) { int i; struct mosquitto__subleaf *leaf; struct mosquitto__subhier *hier; for(i=0; ishared_sub_count; i++){ if(context->shared_subs[i] == NULL){ continue; } leaf = context->shared_subs[i]->shared->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db->shared_subscription_count--; #endif sub__remove_shared_leaf(context->shared_subs[i]->hier, context->shared_subs[i]->shared, leaf); break; } leaf = leaf->next; } if(context->shared_subs[i]->hier->subs == NULL && context->shared_subs[i]->hier->children == NULL && context->shared_subs[i]->hier->retained == NULL && context->shared_subs[i]->hier->shared == NULL && context->shared_subs[i]->hier->parent){ hier = context->shared_subs[i]->hier; context->shared_subs[i]->hier = NULL; do{ hier = tmp_remove_subs(hier); }while(hier); } mosquitto__free(context->shared_subs[i]); } mosquitto__free(context->shared_subs); context->shared_subs = NULL; context->shared_sub_count = 0; return MOSQ_ERR_SUCCESS; } /* Remove all subscriptions for a client. */ int sub__clean_session(struct mosquitto_db *db, struct mosquitto *context) { int i; struct mosquitto__subleaf *leaf; struct mosquitto__subhier *hier; for(i=0; isub_count; i++){ if(context->subs[i] == NULL){ continue; } leaf = context->subs[i]->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db->subscription_count--; #endif DL_DELETE(context->subs[i]->subs, leaf); mosquitto__free(leaf); break; } leaf = leaf->next; } if(context->subs[i]->subs == NULL && context->subs[i]->children == NULL && context->subs[i]->retained == NULL && context->subs[i]->shared == NULL && context->subs[i]->parent){ hier = context->subs[i]; context->subs[i] = NULL; do{ hier = tmp_remove_subs(hier); }while(hier); } } mosquitto__free(context->subs); context->subs = NULL; context->sub_count = 0; return sub__clean_session_shared(db, context); } void sub__tree_print(struct mosquitto__subhier *root, int level) { int i; struct mosquitto__subhier *branch, *branch_tmp; struct mosquitto__subleaf *leaf; HASH_ITER(hh, root, branch, branch_tmp){ if(level > -1){ for(i=0; i<(level+2)*2; i++){ printf(" "); } printf("%s", branch->topic); leaf = branch->subs; while(leaf){ if(leaf->context){ printf(" (%s, %d)", leaf->context->id, leaf->qos); }else{ printf(" (%s, %d)", "", leaf->qos); } leaf = leaf->next; } if(branch->retained){ printf(" (r)"); } printf("\n"); } sub__tree_print(branch->children, level+1); } } static int retain__process(struct mosquitto_db *db, struct mosquitto__subhier *branch, struct mosquitto *context, int sub_qos, uint32_t subscription_identifier, time_t now) { int rc = 0; int qos; uint16_t mid; mosquitto_property *properties = NULL; struct mosquitto_msg_store *retained; if(branch->retained->message_expiry_time > 0 && now >= branch->retained->message_expiry_time){ db__msg_store_ref_dec(db, &branch->retained); branch->retained = NULL; #ifdef WITH_SYS_TREE db->retained_count--; #endif return MOSQ_ERR_SUCCESS; } retained = branch->retained; rc = mosquitto_acl_check(db, context, retained->topic, retained->payloadlen, UHPA_ACCESS(retained->payload, retained->payloadlen), retained->qos, retained->retain, MOSQ_ACL_READ); if(rc == MOSQ_ERR_ACL_DENIED){ return MOSQ_ERR_SUCCESS; }else if(rc != MOSQ_ERR_SUCCESS){ return rc; } /* Check for original source access */ if(db->config->check_retain_source && retained->origin != mosq_mo_broker && retained->source_id){ struct mosquitto retain_ctxt; memset(&retain_ctxt, 0, sizeof(struct mosquitto)); retain_ctxt.id = retained->source_id; retain_ctxt.username = retained->source_username; retain_ctxt.listener = retained->source_listener; rc = acl__find_acls(db, &retain_ctxt); if(rc) return rc; rc = mosquitto_acl_check(db, &retain_ctxt, retained->topic, retained->payloadlen, UHPA_ACCESS(retained->payload, retained->payloadlen), retained->qos, retained->retain, MOSQ_ACL_WRITE); if(rc == MOSQ_ERR_ACL_DENIED){ return MOSQ_ERR_SUCCESS; }else if(rc != MOSQ_ERR_SUCCESS){ return rc; } } if (db->config->upgrade_outgoing_qos){ qos = sub_qos; } else { qos = retained->qos; if(qos > sub_qos) qos = sub_qos; } if(qos > 0){ mid = mosquitto__mid_generate(context); }else{ mid = 0; } if(subscription_identifier > 0){ mosquitto_property_add_varint(&properties, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, subscription_identifier); } return db__message_insert(db, context, mid, mosq_md_out, qos, true, retained, properties); } static int retain__search(struct mosquitto_db *db, struct mosquitto__subhier *subhier, struct sub__token *tokens, struct mosquitto *context, const char *sub, int sub_qos, uint32_t subscription_identifier, time_t now, int level) { struct mosquitto__subhier *branch, *branch_tmp; int flag = 0; if(!strcmp(tokens->topic, "#") && !tokens->next){ HASH_ITER(hh, subhier->children, branch, branch_tmp){ /* Set flag to indicate that we should check for retained messages * on "foo" when we are subscribing to e.g. "foo/#" and then exit * this function and return to an earlier retain__search(). */ flag = -1; if(branch->retained){ retain__process(db, branch, context, sub_qos, subscription_identifier, now); } if(branch->children){ retain__search(db, branch, tokens, context, sub, sub_qos, subscription_identifier, now, level+1); } } }else{ if(!strcmp(tokens->topic, "+")){ HASH_ITER(hh, subhier->children, branch, branch_tmp){ if(tokens->next){ if(retain__search(db, branch, tokens->next, context, sub, sub_qos, subscription_identifier, now, level+1) == -1 || (tokens->next && !strcmp(tokens->next->topic, "#") && level>0)){ if(branch->retained){ retain__process(db, branch, context, sub_qos, subscription_identifier, now); } } }else{ if(branch->retained){ retain__process(db, branch, context, sub_qos, subscription_identifier, now); } } } }else{ HASH_FIND(hh, subhier->children, tokens->topic, tokens->topic_len, branch); if(branch){ if(tokens->next){ if(retain__search(db, branch, tokens->next, context, sub, sub_qos, subscription_identifier, now, level+1) == -1 || (tokens->next && !strcmp(tokens->next->topic, "#") && level>0)){ if(branch->retained){ retain__process(db, branch, context, sub_qos, subscription_identifier, now); } } }else{ if(branch->retained){ retain__process(db, branch, context, sub_qos, subscription_identifier, now); } } } } } return flag; } int sub__retain_queue(struct mosquitto_db *db, struct mosquitto *context, const char *sub, int sub_qos, uint32_t subscription_identifier) { struct mosquitto__subhier *subhier; struct sub__token *tokens = NULL, *tail; time_t now; assert(db); assert(context); assert(sub); if(sub__topic_tokenise(sub, &tokens)) return 1; HASH_FIND(hh, db->subs, tokens->topic, tokens->topic_len, subhier); if(subhier){ now = time(NULL); retain__search(db, subhier, tokens, context, sub, sub_qos, subscription_identifier, now, 0); } while(tokens){ tail = tokens->next; mosquitto__free(tokens->topic); mosquitto__free(tokens); tokens = tail; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/src/persist_read.c0000664000175000017500000003152313626052637016250 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_PERSISTENCE #ifndef WIN32 #include #endif #include #include #include #include #include #include #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "persist.h" #include "time_mosq.h" #include "misc_mosq.h" #include "util_mosq.h" uint32_t db_version; const unsigned char magic[15] = {0x00, 0xB5, 0x00, 'm','o','s','q','u','i','t','t','o',' ','d','b'}; static int persist__restore_sub(struct mosquitto_db *db, const char *client_id, const char *sub, int qos, uint32_t identifier, int options); static struct mosquitto *persist__find_or_add_context(struct mosquitto_db *db, const char *client_id, uint16_t last_mid) { struct mosquitto *context; if(!client_id) return NULL; context = NULL; HASH_FIND(hh_id, db->contexts_by_id, client_id, strlen(client_id), context); if(!context){ context = context__init(db, -1); if(!context) return NULL; context->id = mosquitto__strdup(client_id); if(!context->id){ mosquitto__free(context); return NULL; } context->clean_start = false; HASH_ADD_KEYPTR(hh_id, db->contexts_by_id, context->id, strlen(context->id), context); } if(last_mid){ context->last_mid = last_mid; } return context; } int persist__read_string_len(FILE *db_fptr, char **str, uint16_t len) { char *s = NULL; if(len){ s = mosquitto__malloc(len+1); if(!s){ fclose(db_fptr); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } if(fread(s, 1, len, db_fptr) != len){ mosquitto__free(s); return MOSQ_ERR_NOMEM; } s[len] = '\0'; } *str = s; return MOSQ_ERR_SUCCESS; } int persist__read_string(FILE *db_fptr, char **str) { uint16_t i16temp; uint16_t slen; if(fread(&i16temp, 1, sizeof(uint16_t), db_fptr) != sizeof(uint16_t)){ return MOSQ_ERR_INVAL; } slen = ntohs(i16temp); return persist__read_string_len(db_fptr, str, slen); } static int persist__client_msg_restore(struct mosquitto_db *db, struct P_client_msg *chunk) { struct mosquitto_client_msg *cmsg; struct mosquitto_msg_store_load *load; struct mosquitto *context; struct mosquitto_msg_data *msg_data; HASH_FIND(hh, db->msg_store_load, &chunk->F.store_id, sizeof(dbid_t), load); if(!load){ /* Can't find message - probably expired */ return MOSQ_ERR_SUCCESS; } cmsg = mosquitto__calloc(1, sizeof(struct mosquitto_client_msg)); if(!cmsg){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cmsg->next = NULL; cmsg->store = NULL; cmsg->mid = chunk->F.mid; cmsg->qos = chunk->F.qos; cmsg->retain = (chunk->F.retain_dup&0xF0)>>4; cmsg->timestamp = 0; cmsg->direction = chunk->F.direction; cmsg->state = chunk->F.state; cmsg->dup = chunk->F.retain_dup&0x0F; cmsg->properties = chunk->properties; cmsg->store = load->store; db__msg_store_ref_inc(cmsg->store); context = persist__find_or_add_context(db, chunk->client_id, 0); if(!context){ mosquitto__free(cmsg); log__printf(NULL, MOSQ_LOG_ERR, "Error restoring persistent database, message store corrupt."); return 1; } if(cmsg->direction == mosq_md_out){ msg_data = &context->msgs_out; }else{ msg_data = &context->msgs_in; } if(chunk->F.state == mosq_ms_queued || (chunk->F.qos > 0 && msg_data->inflight_quota == 0)){ DL_APPEND(msg_data->queued, cmsg); }else{ DL_APPEND(msg_data->inflight, cmsg); if(chunk->F.qos > 0 && msg_data->inflight_quota > 0){ msg_data->inflight_quota--; } } msg_data->msg_count++; msg_data->msg_bytes += cmsg->store->payloadlen; if(chunk->F.qos > 0){ msg_data->msg_count12++; msg_data->msg_bytes12 += cmsg->store->payloadlen; } return MOSQ_ERR_SUCCESS; } static int persist__client_chunk_restore(struct mosquitto_db *db, FILE *db_fptr) { int rc = 0; struct mosquitto *context; struct P_client chunk; memset(&chunk, 0, sizeof(struct P_client)); if(db_version == 5){ rc = persist__chunk_client_read_v5(db_fptr, &chunk); }else{ rc = persist__chunk_client_read_v234(db_fptr, &chunk, db_version); } if(rc){ fclose(db_fptr); return rc; } context = persist__find_or_add_context(db, chunk.client_id, chunk.F.last_mid); if(context){ context->session_expiry_time = chunk.F.session_expiry_time; context->session_expiry_interval = chunk.F.session_expiry_interval; /* FIXME - we should expire clients here if they have exceeded their time */ }else{ rc = 1; } mosquitto__free(chunk.client_id); return rc; } static int persist__client_msg_chunk_restore(struct mosquitto_db *db, FILE *db_fptr, uint32_t length) { struct P_client_msg chunk; int rc; memset(&chunk, 0, sizeof(struct P_client_msg)); if(db_version == 5){ rc = persist__chunk_client_msg_read_v5(db_fptr, &chunk, length); }else{ rc = persist__chunk_client_msg_read_v234(db_fptr, &chunk); } if(rc){ fclose(db_fptr); return rc; } rc = persist__client_msg_restore(db, &chunk); mosquitto__free(chunk.client_id); return rc; } static int persist__msg_store_chunk_restore(struct mosquitto_db *db, FILE *db_fptr, uint32_t length) { struct P_msg_store chunk; struct mosquitto_msg_store *stored = NULL; struct mosquitto_msg_store_load *load; int64_t message_expiry_interval64; uint32_t message_expiry_interval; int rc = 0; int i; memset(&chunk, 0, sizeof(struct P_msg_store)); if(db_version == 5){ rc = persist__chunk_msg_store_read_v5(db_fptr, &chunk, length); }else{ rc = persist__chunk_msg_store_read_v234(db_fptr, &chunk, db_version); } if(rc){ fclose(db_fptr); return rc; } if(chunk.F.source_port){ for(i=0; iconfig->listener_count; i++){ if(db->config->listeners[i].port == chunk.F.source_port){ chunk.source.listener = &db->config->listeners[i]; break; } } } load = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store_load)); if(!load){ fclose(db_fptr); mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); mosquitto__free(chunk.topic); UHPA_FREE(chunk.payload, chunk.F.payloadlen); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } if(chunk.F.expiry_time > 0){ message_expiry_interval64 = chunk.F.expiry_time - time(NULL); if(message_expiry_interval64 < 0 || message_expiry_interval64 > UINT32_MAX){ /* Expired message */ mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); mosquitto__free(chunk.topic); UHPA_FREE(chunk.payload, chunk.F.payloadlen); mosquitto__free(load); return MOSQ_ERR_SUCCESS; }else{ message_expiry_interval = (uint32_t)message_expiry_interval64; } }else{ message_expiry_interval = 0; } rc = db__message_store(db, &chunk.source, chunk.F.source_mid, chunk.topic, chunk.F.qos, chunk.F.payloadlen, &chunk.payload, chunk.F.retain, &stored, message_expiry_interval, chunk.properties, chunk.F.store_id, mosq_mo_client); mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); chunk.source.id = NULL; chunk.source.username = NULL; if(rc == MOSQ_ERR_SUCCESS){ stored->source_listener = chunk.source.listener; load->db_id = stored->db_id; load->store = stored; HASH_ADD(hh, db->msg_store_load, db_id, sizeof(dbid_t), load); return MOSQ_ERR_SUCCESS; }else{ mosquitto__free(load); fclose(db_fptr); return rc; } } static int persist__retain_chunk_restore(struct mosquitto_db *db, FILE *db_fptr) { struct mosquitto_msg_store_load *load; struct P_retain chunk; int rc; memset(&chunk, 0, sizeof(struct P_retain)); if(db_version == 5){ rc = persist__chunk_retain_read_v5(db_fptr, &chunk); }else{ rc = persist__chunk_retain_read_v234(db_fptr, &chunk); } if(rc){ fclose(db_fptr); return rc; } HASH_FIND(hh, db->msg_store_load, &chunk.F.store_id, sizeof(dbid_t), load); if(load){ sub__messages_queue(db, NULL, load->store->topic, load->store->qos, load->store->retain, &load->store); }else{ /* Can't find the message - probably expired */ } return MOSQ_ERR_SUCCESS; } static int persist__sub_chunk_restore(struct mosquitto_db *db, FILE *db_fptr) { struct P_sub chunk; int rc; memset(&chunk, 0, sizeof(struct P_sub)); if(db_version == 5){ rc = persist__chunk_sub_read_v5(db_fptr, &chunk); }else{ rc = persist__chunk_sub_read_v234(db_fptr, &chunk); } if(rc){ fclose(db_fptr); return rc; } rc = persist__restore_sub(db, chunk.client_id, chunk.topic, chunk.F.qos, chunk.F.identifier, chunk.F.options); mosquitto__free(chunk.client_id); mosquitto__free(chunk.topic); return rc; } int persist__chunk_header_read(FILE *db_fptr, int *chunk, int *length) { if(db_version == 5){ return persist__chunk_header_read_v5(db_fptr, chunk, length); }else{ return persist__chunk_header_read_v234(db_fptr, chunk, length); } } int persist__restore(struct mosquitto_db *db) { FILE *fptr; char header[15]; int rc = 0; uint32_t crc; uint32_t i32temp; int chunk, length; ssize_t rlen; char *err; struct mosquitto_msg_store_load *load, *load_tmp; struct PF_cfg cfg_chunk; assert(db); assert(db->config); if(!db->config->persistence || db->config->persistence_filepath == NULL){ return MOSQ_ERR_SUCCESS; } db->msg_store_load = NULL; fptr = mosquitto__fopen(db->config->persistence_filepath, "rb", false); if(fptr == NULL) return MOSQ_ERR_SUCCESS; rlen = fread(&header, 1, 15, fptr); if(rlen == 0){ fclose(fptr); log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Persistence file is empty."); return 0; }else if(rlen != 15){ goto error; } if(!memcmp(header, magic, 15)){ // Restore DB as normal read_e(fptr, &crc, sizeof(uint32_t)); read_e(fptr, &i32temp, sizeof(uint32_t)); db_version = ntohl(i32temp); /* IMPORTANT - this is where compatibility checks are made. * Is your DB change still compatible with previous versions? */ if(db_version > MOSQ_DB_VERSION && db_version != 0){ if(db_version == 4){ }else if(db_version == 3){ /* Addition of source_username and source_port to msg_store chunk in v4, v1.5.6 */ }else if(db_version == 2){ /* Addition of disconnect_t to client chunk in v3. */ }else{ fclose(fptr); log__printf(NULL, MOSQ_LOG_ERR, "Error: Unsupported persistent database format version %d (need version %d).", db_version, MOSQ_DB_VERSION); return 1; } } while(persist__chunk_header_read(fptr, &chunk, &length) == MOSQ_ERR_SUCCESS){ switch(chunk){ case DB_CHUNK_CFG: if(db_version == 5){ if(persist__chunk_cfg_read_v5(fptr, &cfg_chunk)){ fclose(fptr); return 1; } }else{ if(persist__chunk_cfg_read_v234(fptr, &cfg_chunk)){ fclose(fptr); return 1; } } if(cfg_chunk.dbid_size != sizeof(dbid_t)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Incompatible database configuration (dbid size is %d bytes, expected %lu)", cfg_chunk.dbid_size, (unsigned long)sizeof(dbid_t)); fclose(fptr); return 1; } db->last_db_id = cfg_chunk.last_db_id; break; case DB_CHUNK_MSG_STORE: if(persist__msg_store_chunk_restore(db, fptr, length)) return 1; break; case DB_CHUNK_CLIENT_MSG: if(persist__client_msg_chunk_restore(db, fptr, length)) return 1; break; case DB_CHUNK_RETAIN: if(persist__retain_chunk_restore(db, fptr)) return 1; break; case DB_CHUNK_SUB: if(persist__sub_chunk_restore(db, fptr)) return 1; break; case DB_CHUNK_CLIENT: if(persist__client_chunk_restore(db, fptr)) return 1; break; default: log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unsupported chunk \"%d\" in persistent database file. Ignoring.", chunk); fseek(fptr, length, SEEK_CUR); break; } } if(rlen < 0) goto error; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to restore persistent database. Unrecognised file format."); rc = 1; } fclose(fptr); HASH_ITER(hh, db->msg_store_load, load, load_tmp){ HASH_DELETE(hh, db->msg_store_load, load); mosquitto__free(load); } return rc; error: err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); if(fptr) fclose(fptr); return 1; } static int persist__restore_sub(struct mosquitto_db *db, const char *client_id, const char *sub, int qos, uint32_t identifier, int options) { struct mosquitto *context; assert(db); assert(client_id); assert(sub); context = persist__find_or_add_context(db, client_id, 0); if(!context) return 1; return sub__add(db, context, sub, qos, identifier, options, &db->subs); } #endif mosquitto-1.6.9/src/bridge.c0000664000175000017500000003775413626052637015034 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #ifndef WIN32 #include #include #else #include #include #endif #include "mqtt_protocol.h" #include "mosquitto.h" #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "net_mosq.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "send_mosq.h" #include "time_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #include "will_mosq.h" #ifdef WITH_BRIDGE static void bridge__backoff_step(struct mosquitto *context); static void bridge__backoff_reset(struct mosquitto *context); int bridge__new(struct mosquitto_db *db, struct mosquitto__bridge *bridge) { struct mosquitto *new_context = NULL; struct mosquitto **bridges; char *local_id; assert(db); assert(bridge); local_id = mosquitto__strdup(bridge->local_clientid); HASH_FIND(hh_id, db->contexts_by_id, local_id, strlen(local_id), new_context); if(new_context){ /* (possible from persistent db) */ mosquitto__free(local_id); }else{ /* id wasn't found, so generate a new context */ new_context = context__init(db, -1); if(!new_context){ mosquitto__free(local_id); return MOSQ_ERR_NOMEM; } new_context->id = local_id; HASH_ADD_KEYPTR(hh_id, db->contexts_by_id, new_context->id, strlen(new_context->id), new_context); } new_context->bridge = bridge; new_context->is_bridge = true; new_context->username = new_context->bridge->remote_username; new_context->password = new_context->bridge->remote_password; #ifdef WITH_TLS new_context->tls_cafile = new_context->bridge->tls_cafile; new_context->tls_capath = new_context->bridge->tls_capath; new_context->tls_certfile = new_context->bridge->tls_certfile; new_context->tls_keyfile = new_context->bridge->tls_keyfile; new_context->tls_cert_reqs = SSL_VERIFY_PEER; new_context->tls_ocsp_required = new_context->bridge->tls_ocsp_required; new_context->tls_version = new_context->bridge->tls_version; new_context->tls_insecure = new_context->bridge->tls_insecure; new_context->tls_alpn = new_context->bridge->tls_alpn; new_context->tls_engine = db->config->default_listener.tls_engine; new_context->tls_keyform = db->config->default_listener.tls_keyform; #ifdef FINAL_WITH_TLS_PSK new_context->tls_psk_identity = new_context->bridge->tls_psk_identity; new_context->tls_psk = new_context->bridge->tls_psk; #endif #endif bridge->try_private_accepted = true; new_context->protocol = bridge->protocol_version; bridges = mosquitto__realloc(db->bridges, (db->bridge_count+1)*sizeof(struct mosquitto *)); if(bridges){ db->bridges = bridges; db->bridge_count++; db->bridges[db->bridge_count-1] = new_context; }else{ return MOSQ_ERR_NOMEM; } #if defined(__GLIBC__) && defined(WITH_ADNS) new_context->bridge->restart_t = 1; /* force quick restart of bridge */ return bridge__connect_step1(db, new_context); #else return bridge__connect(db, new_context); #endif } #if defined(__GLIBC__) && defined(WITH_ADNS) int bridge__connect_step1(struct mosquitto_db *db, struct mosquitto *context) { int rc; char *notification_topic; int notification_topic_len; uint8_t notification_payload; int i; if(!context || !context->bridge) return MOSQ_ERR_INVAL; mosquitto__set_state(context, mosq_cs_new); context->sock = INVALID_SOCKET; context->last_msg_in = mosquitto_time(); context->next_msg_out = mosquitto_time() + context->bridge->keepalive; context->keepalive = context->bridge->keepalive; context->clean_start = context->bridge->clean_start; context->in_packet.payload = NULL; context->ping_t = 0; context->bridge->lazy_reconnect = false; bridge__packet_cleanup(context); db__message_reconnect_reset(db, context); if(context->clean_start){ db__messages_delete(db, context); } /* Delete all local subscriptions even for clean_start==false. We don't * remove any messages and the next loop carries out the resubscription * anyway. This means any unwanted subs will be removed. */ sub__clean_session(db, context); for(i=0; ibridge->topic_count; i++){ if(context->bridge->topics[i].direction == bd_out || context->bridge->topics[i].direction == bd_both){ log__printf(NULL, MOSQ_LOG_DEBUG, "Bridge %s doing local SUBSCRIBE on topic %s", context->id, context->bridge->topics[i].local_topic); if(sub__add(db, context, context->bridge->topics[i].local_topic, context->bridge->topics[i].qos, 0, MQTT_SUB_OPT_NO_LOCAL | MQTT_SUB_OPT_RETAIN_AS_PUBLISHED, &db->subs) > 0){ return 1; } sub__retain_queue(db, context, context->bridge->topics[i].local_topic, context->bridge->topics[i].qos, 0); } } /* prepare backoff for a possible failure. Restart timeout will be reset if connection gets established */ bridge__backoff_step(context); if(context->bridge->notifications){ if(context->bridge->notification_topic){ if(!context->bridge->initial_notification_done){ notification_payload = '0'; db__messages_easy_queue(db, context, context->bridge->notification_topic, 1, 1, ¬ification_payload, 1, 0, NULL); context->bridge->initial_notification_done = true; } notification_payload = '0'; rc = will__set(context, context->bridge->notification_topic, 1, ¬ification_payload, 1, true, NULL); if(rc != MOSQ_ERR_SUCCESS){ return rc; } }else{ notification_topic_len = strlen(context->bridge->remote_clientid)+strlen("$SYS/broker/connection//state"); notification_topic = mosquitto__malloc(sizeof(char)*(notification_topic_len+1)); if(!notification_topic) return MOSQ_ERR_NOMEM; snprintf(notification_topic, notification_topic_len+1, "$SYS/broker/connection/%s/state", context->bridge->remote_clientid); if(!context->bridge->initial_notification_done){ notification_payload = '0'; db__messages_easy_queue(db, context, notification_topic, 1, 1, ¬ification_payload, 1, 0, NULL); context->bridge->initial_notification_done = true; } notification_payload = '0'; rc = will__set(context, notification_topic, 1, ¬ification_payload, 1, true, NULL); mosquitto__free(notification_topic); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } } log__printf(NULL, MOSQ_LOG_NOTICE, "Connecting bridge (step 1) %s (%s:%d)", context->bridge->name, context->bridge->addresses[context->bridge->cur_address].address, context->bridge->addresses[context->bridge->cur_address].port); rc = net__try_connect_step1(context, context->bridge->addresses[context->bridge->cur_address].address); if(rc > 0 ){ if(rc == MOSQ_ERR_TLS){ net__socket_close(db, context); return rc; /* Error already printed */ }else if(rc == MOSQ_ERR_ERRNO){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", strerror(errno)); }else if(rc == MOSQ_ERR_EAI){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", gai_strerror(errno)); } return rc; } return MOSQ_ERR_SUCCESS; } int bridge__connect_step2(struct mosquitto_db *db, struct mosquitto *context) { int rc; if(!context || !context->bridge) return MOSQ_ERR_INVAL; log__printf(NULL, MOSQ_LOG_NOTICE, "Connecting bridge (step 2) %s (%s:%d)", context->bridge->name, context->bridge->addresses[context->bridge->cur_address].address, context->bridge->addresses[context->bridge->cur_address].port); rc = net__try_connect_step2(context, context->bridge->addresses[context->bridge->cur_address].port, &context->sock); if(rc > 0){ if(rc == MOSQ_ERR_TLS){ net__socket_close(db, context); return rc; /* Error already printed */ }else if(rc == MOSQ_ERR_ERRNO){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", strerror(errno)); }else if(rc == MOSQ_ERR_EAI){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", gai_strerror(errno)); } return rc; } HASH_ADD(hh_sock, db->contexts_by_sock, sock, sizeof(context->sock), context); if(rc == MOSQ_ERR_CONN_PENDING){ mosquitto__set_state(context, mosq_cs_connect_pending); } return rc; } int bridge__connect_step3(struct mosquitto_db *db, struct mosquitto *context) { int rc; rc = net__socket_connect_step3(context, context->bridge->addresses[context->bridge->cur_address].address); if(rc > 0){ if(rc == MOSQ_ERR_TLS){ net__socket_close(db, context); return rc; /* Error already printed */ }else if(rc == MOSQ_ERR_ERRNO){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", strerror(errno)); }else if(rc == MOSQ_ERR_EAI){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", gai_strerror(errno)); } return rc; } if(context->bridge->round_robin == false && context->bridge->cur_address != 0){ context->bridge->primary_retry = mosquitto_time() + 5; } rc = send__connect(context, context->keepalive, context->clean_start, NULL); if(rc == MOSQ_ERR_SUCCESS){ bridge__backoff_reset(context); return MOSQ_ERR_SUCCESS; }else if(rc == MOSQ_ERR_ERRNO && errno == ENOTCONN){ bridge__backoff_reset(context); return MOSQ_ERR_SUCCESS; }else{ if(rc == MOSQ_ERR_TLS){ return rc; /* Error already printed */ }else if(rc == MOSQ_ERR_ERRNO){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", strerror(errno)); }else if(rc == MOSQ_ERR_EAI){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", gai_strerror(errno)); } net__socket_close(db, context); return rc; } } #else int bridge__connect(struct mosquitto_db *db, struct mosquitto *context) { int rc, rc2; int i; char *notification_topic; int notification_topic_len; uint8_t notification_payload; if(!context || !context->bridge) return MOSQ_ERR_INVAL; mosquitto__set_state(context, mosq_cs_new); context->sock = INVALID_SOCKET; context->last_msg_in = mosquitto_time(); context->next_msg_out = mosquitto_time() + context->bridge->keepalive; context->keepalive = context->bridge->keepalive; context->clean_start = context->bridge->clean_start; context->in_packet.payload = NULL; context->ping_t = 0; context->bridge->lazy_reconnect = false; bridge__packet_cleanup(context); db__message_reconnect_reset(db, context); if(context->clean_start){ db__messages_delete(db, context); } /* Delete all local subscriptions even for clean_start==false. We don't * remove any messages and the next loop carries out the resubscription * anyway. This means any unwanted subs will be removed. */ sub__clean_session(db, context); for(i=0; ibridge->topic_count; i++){ if(context->bridge->topics[i].direction == bd_out || context->bridge->topics[i].direction == bd_both){ log__printf(NULL, MOSQ_LOG_DEBUG, "Bridge %s doing local SUBSCRIBE on topic %s", context->id, context->bridge->topics[i].local_topic); if(sub__add(db, context, context->bridge->topics[i].local_topic, context->bridge->topics[i].qos, 0, MQTT_SUB_OPT_NO_LOCAL | MQTT_SUB_OPT_RETAIN_AS_PUBLISHED, &db->subs) > 0){ return 1; } } } /* prepare backoff for a possible failure. Restart timeout will be reset if connection gets established */ bridge__backoff_step(context); if(context->bridge->notifications){ if(context->bridge->notification_topic){ if(!context->bridge->initial_notification_done){ notification_payload = '0'; db__messages_easy_queue(db, context, context->bridge->notification_topic, 1, 1, ¬ification_payload, 1, 0, NULL); context->bridge->initial_notification_done = true; } if (!context->bridge->notifications_local_only) { notification_payload = '0'; rc = will__set(context, context->bridge->notification_topic, 1, ¬ification_payload, 1, true, NULL); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } }else{ notification_topic_len = strlen(context->bridge->remote_clientid)+strlen("$SYS/broker/connection//state"); notification_topic = mosquitto__malloc(sizeof(char)*(notification_topic_len+1)); if(!notification_topic) return MOSQ_ERR_NOMEM; snprintf(notification_topic, notification_topic_len+1, "$SYS/broker/connection/%s/state", context->bridge->remote_clientid); if(!context->bridge->initial_notification_done){ notification_payload = '0'; db__messages_easy_queue(db, context, notification_topic, 1, 1, ¬ification_payload, 1, 0, NULL); context->bridge->initial_notification_done = true; } if (!context->bridge->notifications_local_only) { notification_payload = '0'; rc = will__set(context, notification_topic, 1, ¬ification_payload, 1, true, NULL); mosquitto__free(notification_topic); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } } } log__printf(NULL, MOSQ_LOG_NOTICE, "Connecting bridge %s (%s:%d)", context->bridge->name, context->bridge->addresses[context->bridge->cur_address].address, context->bridge->addresses[context->bridge->cur_address].port); rc = net__socket_connect(context, context->bridge->addresses[context->bridge->cur_address].address, context->bridge->addresses[context->bridge->cur_address].port, NULL, false); if(rc > 0){ if(rc == MOSQ_ERR_TLS){ net__socket_close(db, context); return rc; /* Error already printed */ }else if(rc == MOSQ_ERR_ERRNO){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", strerror(errno)); }else if(rc == MOSQ_ERR_EAI){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", gai_strerror(errno)); } return rc; }else if(rc == MOSQ_ERR_CONN_PENDING){ mosquitto__set_state(context, mosq_cs_connect_pending); } HASH_ADD(hh_sock, db->contexts_by_sock, sock, sizeof(context->sock), context); rc2 = send__connect(context, context->keepalive, context->clean_start, NULL); if(rc2 == MOSQ_ERR_SUCCESS){ bridge__backoff_reset(context); return rc; }else if(rc2 == MOSQ_ERR_ERRNO && errno == ENOTCONN){ bridge__backoff_reset(context); return MOSQ_ERR_SUCCESS; }else{ if(rc2 == MOSQ_ERR_TLS){ return rc2; /* Error already printed */ }else if(rc2 == MOSQ_ERR_ERRNO){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", strerror(errno)); }else if(rc2 == MOSQ_ERR_EAI){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating bridge: %s.", gai_strerror(errno)); } net__socket_close(db, context); return rc2; } } #endif void bridge__packet_cleanup(struct mosquitto *context) { struct mosquitto__packet *packet; if(!context) return; if(context->current_out_packet){ packet__cleanup(context->current_out_packet); mosquitto__free(context->current_out_packet); context->current_out_packet = NULL; } while(context->out_packet){ packet__cleanup(context->out_packet); packet = context->out_packet; context->out_packet = context->out_packet->next; mosquitto__free(packet); } context->out_packet = NULL; context->out_packet_last = NULL; packet__cleanup(&(context->in_packet)); } static int rand_between(int base, int cap) { int r; util__random_bytes(&r, sizeof(int)); return (r % (cap - base)) + base; } static void bridge__backoff_step(struct mosquitto *context) { struct mosquitto__bridge *bridge; if(!context || !context->bridge) return; bridge = context->bridge; /* skip if not using backoff */ if(bridge->backoff_cap){ /* “Decorrelated Jitter” calculation, according to: * https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ */ bridge->restart_timeout = rand_between(bridge->backoff_base, bridge->restart_timeout * 3); if(bridge->restart_timeout > bridge->backoff_cap){ bridge->restart_timeout = bridge->backoff_cap; } } } static void bridge__backoff_reset(struct mosquitto *context) { struct mosquitto__bridge *bridge; if(!context || !context->bridge) return; bridge = context->bridge; /* skip if not using backoff */ if(bridge->backoff_cap){ bridge->restart_timeout = bridge->backoff_base; } } #endif mosquitto-1.6.9/src/send_suback.c0000664000175000017500000000334613626052637016047 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "util_mosq.h" int send__suback(struct mosquitto *context, uint16_t mid, uint32_t payloadlen, const void *payload) { struct mosquitto__packet *packet = NULL; int rc; mosquitto_property *properties = NULL; int proplen, varbytes; log__printf(NULL, MOSQ_LOG_DEBUG, "Sending SUBACK to %s", context->id); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = CMD_SUBACK; packet->remaining_length = 2+payloadlen; if(context->protocol == mosq_p_mqtt5){ proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); packet->remaining_length += proplen + varbytes; } rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } packet__write_uint16(packet, mid); if(context->protocol == mosq_p_mqtt5){ /* We don't use Reason String or User Property yet. */ property__write_all(packet, properties, true); } if(payloadlen){ packet__write_bytes(packet, payload, payloadlen); } return packet__queue(context, packet); } mosquitto-1.6.9/src/linker.syms0000664000175000017500000000043013626052637015612 0ustar rogerroger{ mosquitto_log_printf; mosquitto_client_address; mosquitto_client_clean_session; mosquitto_client_id; mosquitto_client_keepalive; mosquitto_client_certificate; mosquitto_client_protocol; mosquitto_client_sub_count; mosquitto_client_username; mosquitto_set_username; }; mosquitto-1.6.9/src/read_handle.c0000664000175000017500000000400713626052637016007 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "sys_tree.h" #include "util_mosq.h" int handle__packet(struct mosquitto_db *db, struct mosquitto *context) { if(!context) return MOSQ_ERR_INVAL; switch((context->in_packet.command)&0xF0){ case CMD_PINGREQ: return handle__pingreq(context); case CMD_PINGRESP: return handle__pingresp(context); case CMD_PUBACK: return handle__pubackcomp(db, context, "PUBACK"); case CMD_PUBCOMP: return handle__pubackcomp(db, context, "PUBCOMP"); case CMD_PUBLISH: return handle__publish(db, context); case CMD_PUBREC: return handle__pubrec(db, context); case CMD_PUBREL: return handle__pubrel(db, context); case CMD_CONNECT: return handle__connect(db, context); case CMD_DISCONNECT: return handle__disconnect(db, context); case CMD_SUBSCRIBE: return handle__subscribe(db, context); case CMD_UNSUBSCRIBE: return handle__unsubscribe(db, context); #ifdef WITH_BRIDGE case CMD_CONNACK: return handle__connack(db, context); case CMD_SUBACK: return handle__suback(context); case CMD_UNSUBACK: return handle__unsuback(context); #endif case CMD_AUTH: return handle__auth(db, context); default: /* If we don't recognise the command, return an error straight away. */ return MOSQ_ERR_PROTOCOL; } } mosquitto-1.6.9/src/service.c0000664000175000017500000001041113626052637015215 0ustar rogerroger/* Copyright (c) 2011-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #if defined(WIN32) || defined(__CYGWIN__) #include "config.h" #include #include "memory_mosq.h" extern int run; SERVICE_STATUS_HANDLE service_handle = 0; static SERVICE_STATUS service_status; int main(int argc, char *argv[]); static void print_error(void) { char *buf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), LANG_NEUTRAL, &buf, 0, NULL); fprintf(stderr, "Error: %s\n", buf); LocalFree(buf); } /* Service control callback */ void __stdcall service_handler(DWORD fdwControl) { switch(fdwControl){ case SERVICE_CONTROL_CONTINUE: /* Continue from Paused state. */ break; case SERVICE_CONTROL_PAUSE: /* Pause service. */ break; case SERVICE_CONTROL_SHUTDOWN: /* System is shutting down. */ case SERVICE_CONTROL_STOP: /* Service should stop. */ service_status.dwCurrentState = SERVICE_STOP_PENDING; SetServiceStatus(service_handle, &service_status); run = 0; break; } } /* Function called when started as a service. */ void __stdcall service_main(DWORD dwArgc, LPTSTR *lpszArgv) { char **argv; int argc = 1; char conf_path[MAX_PATH + 20]; int rc; service_handle = RegisterServiceCtrlHandler("mosquitto", service_handler); if(service_handle){ memset(conf_path, 0, MAX_PATH + 20); rc = GetEnvironmentVariable("MOSQUITTO_DIR", conf_path, MAX_PATH); if(!rc || rc == MAX_PATH){ service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_handle, &service_status); return; } strcat(conf_path, "/mosquitto.conf"); argv = mosquitto__malloc(sizeof(char *)*3); argv[0] = "mosquitto"; argv[1] = "-c"; argv[2] = conf_path; argc = 3; service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; service_status.dwCurrentState = SERVICE_RUNNING; service_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP; service_status.dwWin32ExitCode = NO_ERROR; service_status.dwCheckPoint = 0; SetServiceStatus(service_handle, &service_status); main(argc, argv); mosquitto__free(argv); service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_handle, &service_status); } } void service_install(void) { SC_HANDLE sc_manager, svc_handle; char exe_path[MAX_PATH + 5]; SERVICE_DESCRIPTION svc_desc; memset(exe_path, 0, MAX_PATH+5); if(GetModuleFileName(NULL, exe_path, MAX_PATH) == MAX_PATH){ fprintf(stderr, "Error: Path too long.\n"); return; } strcat(exe_path, " run"); sc_manager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if(sc_manager){ svc_handle = CreateService(sc_manager, "mosquitto", "Mosquitto Broker", SERVICE_START | SERVICE_STOP | SERVICE_CHANGE_CONFIG, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, exe_path, NULL, NULL, NULL, NULL, NULL); if(svc_handle){ svc_desc.lpDescription = "MQTT v3.1.1 broker"; ChangeServiceConfig2(svc_handle, SERVICE_CONFIG_DESCRIPTION, &svc_desc); CloseServiceHandle(svc_handle); }else{ print_error(); } CloseServiceHandle(sc_manager); } else { print_error(); } } void service_uninstall(void) { SC_HANDLE sc_manager, svc_handle; SERVICE_STATUS status; sc_manager = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT); if(sc_manager){ svc_handle = OpenService(sc_manager, "mosquitto", SERVICE_QUERY_STATUS | DELETE); if(svc_handle){ if(QueryServiceStatus(svc_handle, &status)){ if(status.dwCurrentState == SERVICE_STOPPED){ DeleteService(svc_handle); } } CloseServiceHandle(svc_handle); }else{ print_error(); } CloseServiceHandle(sc_manager); }else{ print_error(); } } void service_run(void) { SERVICE_TABLE_ENTRY ste[] = { { "mosquitto", service_main }, { NULL, NULL } }; StartServiceCtrlDispatcher(ste); } #endif mosquitto-1.6.9/src/db_dump/0000775000175000017500000000000013626052637015026 5ustar rogerrogermosquitto-1.6.9/src/db_dump/stubs.c0000664000175000017500000000356013626052637016336 0ustar rogerroger#include #include #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" struct mosquitto *context__init(struct mosquitto_db *db, mosq_sock_t sock) { return NULL; } int db__message_store(struct mosquitto_db *db, const struct mosquitto *source, uint16_t source_mid, char *topic, int qos, uint32_t payloadlen, mosquitto__payload_uhpa *payload, int retain, struct mosquitto_msg_store **stored, uint32_t message_expiry_interval, mosquitto_property *properties, dbid_t store_id, enum mosquitto_msg_origin origin) { return 0; } void db__msg_store_ref_inc(struct mosquitto_msg_store *store) { } int handle__packet(struct mosquitto_db *db, struct mosquitto *context) { return 0; } int log__printf(struct mosquitto *mosq, int level, const char *fmt, ...) { return 0; } void *mosquitto__calloc(size_t nmemb, size_t len) { return calloc(nmemb, len); } void mosquitto__free(void *p) { free(p); } FILE *mosquitto__fopen(const char *path, const char *mode, bool restrict_read) { return NULL; } enum mosquitto_client_state mosquitto__get_state(struct mosquitto *mosq) { return mosq_cs_new; } void *mosquitto__malloc(size_t len) { return malloc(len); } char *mosquitto__strdup(const char *s) { return strdup(s); } ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { return 0; } ssize_t net__write(struct mosquitto *mosq, void *buf, size_t count) { return 0; } int retain__store(struct mosquitto_db *db, const char *topic, struct mosquitto_msg_store *stored, char **split_topics) { return 0; } int sub__add(struct mosquitto_db *db, struct mosquitto *context, const char *sub, int qos, uint32_t identifier, int options, struct mosquitto__subhier **root) { return 0; } int sub__messages_queue(struct mosquitto_db *db, const char *source_id, const char *topic, int qos, int retain, struct mosquitto_msg_store **stored) { return 0; } mosquitto-1.6.9/src/db_dump/db_dump.c0000664000175000017500000002604113626052637016607 0ustar rogerroger/* Copyright (c) 2010-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #define mosquitto__malloc(A) malloc((A)) #define mosquitto__free(A) free((A)) #define _mosquitto_malloc(A) malloc((A)) #define _mosquitto_free(A) free((A)) #include #include "db_dump.h" struct client_data { UT_hash_handle hh_id; char *id; int subscriptions; int subscription_size; int messages; long message_size; }; struct msg_store_chunk { UT_hash_handle hh; dbid_t store_id; uint32_t length; }; extern uint32_t db_version; static int stats = 0; static int client_stats = 0; static int do_print = 1; /* Counts */ static long cfg_count = 0; static long client_count = 0; static long client_msg_count = 0; static long msg_store_count = 0; static long retain_count = 0; static long sub_count = 0; /* ====== */ struct client_data *clients_by_id = NULL; struct msg_store_chunk *msgs_by_id = NULL; static void free__sub(struct P_sub *chunk) { free(chunk->client_id); free(chunk->topic); } static void free__client(struct P_client *chunk) { free(chunk->client_id); } static void free__client_msg(struct P_client_msg *chunk) { free(chunk->client_id); mosquitto_property_free_all(&chunk->properties); } static void free__msg_store(struct P_msg_store *chunk) { //free(chunk->source_id); free(chunk->topic); UHPA_FREE(chunk->payload, chunk->F.payloadlen); mosquitto_property_free_all(&chunk->properties); } static int dump__cfg_chunk_process(struct mosquitto_db *db, FILE *db_fd, uint32_t length) { struct PF_cfg chunk; int rc; cfg_count++; memset(&chunk, 0, sizeof(struct PF_cfg)); if(db_version == 5){ rc = persist__chunk_cfg_read_v5(db_fd, &chunk); }else{ rc = persist__chunk_cfg_read_v234(db_fd, &chunk); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database."); fclose(db_fd); return rc; } if(do_print) printf("DB_CHUNK_CFG:\n"); if(do_print) printf("\tLength: %d\n", length); if(do_print) printf("\tShutdown: %d\n", chunk.shutdown); if(do_print) printf("\tDB ID size: %d\n", chunk.dbid_size); if(chunk.dbid_size != sizeof(dbid_t)){ fprintf(stderr, "Error: Incompatible database configuration (dbid size is %d bytes, expected %ld)", chunk.dbid_size, sizeof(dbid_t)); fclose(db_fd); return 1; } if(do_print) printf("\tLast DB ID: %" PRIu64 "\n", chunk.last_db_id); return 0; } static int dump__client_chunk_process(struct mosquitto_db *db, FILE *db_fd, uint32_t length) { struct P_client chunk; int rc = 0; struct client_data *cc; client_count++; memset(&chunk, 0, sizeof(struct P_client)); if(db_version == 5){ rc = persist__chunk_client_read_v5(db_fd, &chunk); }else{ rc = persist__chunk_client_read_v234(db_fd, &chunk, db_version); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database."); fclose(db_fd); return rc; } if(client_stats){ cc = calloc(1, sizeof(struct client_data)); if(!cc){ fprintf(stderr, "Error: Out of memory.\n"); fclose(db_fd); free(chunk.client_id); return 1; } cc->id = strdup(chunk.client_id); HASH_ADD_KEYPTR(hh_id, clients_by_id, cc->id, strlen(cc->id), cc); } if(do_print) { print__client(&chunk, length); } free__client(&chunk); return 0; } static int dump__client_msg_chunk_process(struct mosquitto_db *db, FILE *db_fd, uint32_t length) { struct P_client_msg chunk; struct client_data *cc; struct msg_store_chunk *msc; int rc; client_msg_count++; memset(&chunk, 0, sizeof(struct P_client_msg)); if(db_version == 5){ rc = persist__chunk_client_msg_read_v5(db_fd, &chunk, length); }else{ rc = persist__chunk_client_msg_read_v234(db_fd, &chunk); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database."); fclose(db_fd); return rc; } if(client_stats){ HASH_FIND(hh_id, clients_by_id, chunk.client_id, strlen(chunk.client_id), cc); if(cc){ cc->messages++; cc->message_size += length; HASH_FIND(hh, msgs_by_id, &chunk.F.store_id, sizeof(dbid_t), msc); if(msc){ cc->message_size += msc->length; } } } if(do_print) { print__client_msg(&chunk, length); } free__client_msg(&chunk); return 0; } static int dump__msg_store_chunk_process(struct mosquitto_db *db, FILE *db_fptr, uint32_t length) { struct P_msg_store chunk; struct mosquitto_msg_store *stored = NULL; struct mosquitto_msg_store_load *load; int64_t message_expiry_interval64; uint32_t message_expiry_interval; int rc = 0; struct msg_store_chunk *mcs; msg_store_count++; memset(&chunk, 0, sizeof(struct P_msg_store)); if(db_version == 5){ rc = persist__chunk_msg_store_read_v5(db_fptr, &chunk, length); }else{ rc = persist__chunk_msg_store_read_v234(db_fptr, &chunk, db_version); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database."); fclose(db_fptr); return rc; } load = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store_load)); if(!load){ fclose(db_fptr); mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); mosquitto__free(chunk.topic); UHPA_FREE(chunk.payload, chunk.F.payloadlen); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } if(chunk.F.expiry_time > 0){ message_expiry_interval64 = chunk.F.expiry_time - time(NULL); if(message_expiry_interval64 < 0 || message_expiry_interval64 > UINT32_MAX){ message_expiry_interval = 0; }else{ message_expiry_interval = (uint32_t)message_expiry_interval64; } }else{ message_expiry_interval = 0; } rc = db__message_store(db, &chunk.source, chunk.F.source_mid, chunk.topic, chunk.F.qos, chunk.F.payloadlen, &chunk.payload, chunk.F.retain, &stored, message_expiry_interval, chunk.properties, chunk.F.store_id, mosq_mo_client); mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); chunk.source.id = NULL; chunk.source.username = NULL; if(rc == MOSQ_ERR_SUCCESS){ /* printf("stored:%p\n", stored); stored->source_listener = chunk.source.listener; load->db_id = stored->db_id; load->store = stored; */ HASH_ADD(hh, db->msg_store_load, db_id, sizeof(dbid_t), load); }else{ mosquitto__free(load); fclose(db_fptr); return rc; } if(client_stats){ mcs = calloc(1, sizeof(struct msg_store_chunk)); if(!mcs){ errno = ENOMEM; return 1; } mcs->store_id = chunk.F.store_id; mcs->length = length; HASH_ADD(hh, msgs_by_id, store_id, sizeof(dbid_t), mcs); } if(do_print){ print__msg_store(&chunk, length); } free__msg_store(&chunk); return 0; } static int dump__retain_chunk_process(struct mosquitto_db *db, FILE *db_fd, uint32_t length) { struct P_retain chunk; int rc; retain_count++; if(do_print) printf("DB_CHUNK_RETAIN:\n"); if(do_print) printf("\tLength: %d\n", length); if(db_version == 5){ rc = persist__chunk_retain_read_v5(db_fd, &chunk); }else{ rc = persist__chunk_retain_read_v234(db_fd, &chunk); } if(rc){ fclose(db_fd); return rc; } if(do_print) printf("\tStore ID: %" PRIu64 "\n", chunk.F.store_id); return 0; } static int dump__sub_chunk_process(struct mosquitto_db *db, FILE *db_fd, uint32_t length) { int rc = 0; struct P_sub chunk; struct client_data *cc; sub_count++; memset(&chunk, 0, sizeof(struct P_sub)); if(db_version == 5){ rc = persist__chunk_sub_read_v5(db_fd, &chunk); }else{ rc = persist__chunk_sub_read_v234(db_fd, &chunk); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database."); fclose(db_fd); return rc; } if(client_stats){ HASH_FIND(hh_id, clients_by_id, chunk.client_id, strlen(chunk.client_id), cc); if(cc){ cc->subscriptions++; cc->subscription_size += length; } } if(do_print) { print__sub(&chunk, length); } free__sub(&chunk); return 0; } int main(int argc, char *argv[]) { FILE *fd; char header[15]; int rc = 0; uint32_t crc; uint32_t i32temp; int length; int chunk; struct mosquitto_db db; char *filename; struct client_data *cc, *cc_tmp; if(argc == 2){ filename = argv[1]; }else if(argc == 3 && !strcmp(argv[1], "--stats")){ stats = 1; do_print = 0; filename = argv[2]; }else if(argc == 3 && !strcmp(argv[1], "--client-stats")){ client_stats = 1; do_print = 0; filename = argv[2]; }else{ fprintf(stderr, "Usage: db_dump [--stats | --client-stats] \n"); return 1; } memset(&db, 0, sizeof(struct mosquitto_db)); fd = fopen(filename, "rb"); if(!fd) return 0; read_e(fd, &header, 15); if(!memcmp(header, magic, 15)){ if(do_print) printf("Mosquitto DB dump\n"); // Restore DB as normal read_e(fd, &crc, sizeof(uint32_t)); if(do_print) printf("CRC: %d\n", crc); read_e(fd, &i32temp, sizeof(uint32_t)); db_version = ntohl(i32temp); if(do_print) printf("DB version: %d\n", db_version); if(db_version > MOSQ_DB_VERSION){ if(do_print) printf("Warning: mosquitto_db_dump does not support this DB version, continuing but expecting errors.\n"); } while(persist__chunk_header_read(fd, &chunk, &length) == MOSQ_ERR_SUCCESS){ switch(chunk){ case DB_CHUNK_CFG: if(dump__cfg_chunk_process(&db, fd, length)) return 1; break; case DB_CHUNK_MSG_STORE: if(dump__msg_store_chunk_process(&db, fd, length)) return 1; break; case DB_CHUNK_CLIENT_MSG: if(dump__client_msg_chunk_process(&db, fd, length)) return 1; break; case DB_CHUNK_RETAIN: if(dump__retain_chunk_process(&db, fd, length)) return 1; break; case DB_CHUNK_SUB: if(dump__sub_chunk_process(&db, fd, length)) return 1; break; case DB_CHUNK_CLIENT: if(dump__client_chunk_process(&db, fd, length)) return 1; break; default: fprintf(stderr, "Warning: Unsupported chunk \"%d\" in persistent database file. Ignoring.\n", chunk); fseek(fd, length, SEEK_CUR); break; } } }else{ fprintf(stderr, "Error: Unrecognised file format."); rc = 1; } fclose(fd); if(stats){ printf("DB_CHUNK_CFG: %ld\n", cfg_count); printf("DB_CHUNK_MSG_STORE: %ld\n", msg_store_count); printf("DB_CHUNK_CLIENT_MSG: %ld\n", client_msg_count); printf("DB_CHUNK_RETAIN: %ld\n", retain_count); printf("DB_CHUNK_SUB: %ld\n", sub_count); printf("DB_CHUNK_CLIENT: %ld\n", client_count); } if(client_stats){ HASH_ITER(hh_id, clients_by_id, cc, cc_tmp){ printf("SC: %d SS: %d MC: %d MS: %ld ", cc->subscriptions, cc->subscription_size, cc->messages, cc->message_size); printf("%s\n", cc->id); free(cc->id); } } return rc; error: fprintf(stderr, "Error: %s.", strerror(errno)); if(fd >= 0) fclose(fd); return 1; } mosquitto-1.6.9/src/db_dump/db_dump.h0000664000175000017500000000150713626052637016614 0ustar rogerroger#ifndef DB_DUMP_H #define DB_DUMP_H /* Copyright (c) 2010-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include void print__client(struct P_client *chunk, int length); void print__client_msg(struct P_client_msg *chunk, int length); void print__msg_store(struct P_msg_store *chunk, int length); void print__sub(struct P_sub *chunk, int length); #endif mosquitto-1.6.9/src/db_dump/Makefile0000664000175000017500000000415013626052637016466 0ustar rogerrogerinclude ../../config.mk CFLAGS_FINAL=${CFLAGS} -I.. -I../../ -I../../lib -I../.. -I../deps -DWITH_BROKER -DWITH_PERSISTENCE OBJS = \ db_dump.o \ print.o \ \ packet_datatypes.o \ packet_mosq.o \ persist_read.o \ persist_read_v234.o \ persist_read_v5.o \ property_mosq.o \ send_disconnect.o \ stubs.o \ time_mosq.o \ utf8_mosq.o .PHONY: all clean reallyclean all : mosquitto_db_dump mosquitto_db_dump : ${OBJS} ${CROSS_COMPILE}${CC} $^ -o $@ ${LDFLAGS} ${LIBS} db_dump.o : db_dump.c db_dump.h ../persist.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ print.o : print.c db_dump.h ../persist.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ net_mosq.o : ../../lib/net_mosq.c ../../lib/net_mosq.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ packet_datatypes.o : ../../lib/packet_datatypes.c ../../lib/packet_mosq.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ packet_mosq.o : ../../lib/packet_mosq.c ../../lib/packet_mosq.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ persist_read.o : ../persist_read.c ../persist.h ../mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ persist_read_v234.o : ../persist_read_v234.c ../persist.h ../mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ persist_read_v5.o : ../persist_read_v5.c ../persist.h ../mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ property_mosq.o : ../../lib/property_mosq.c ../../lib/property_mosq.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ read_handle.o : ../../src/read_handle.c ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ stubs.o : stubs.c ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ send_disconnect.o : ../../lib/send_disconnect.c ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ time_mosq.o : ../../lib/time_mosq.c ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ topic_tok.o : ../../src/topic_tok.c ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ utf8_mosq.o : ../../lib/utf8_mosq.c ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ clean : -rm -f *.o mosquitto_db_dump mosquitto-1.6.9/src/db_dump/print.c0000664000175000017500000001515713626052637016337 0ustar rogerroger/* Copyright (c) 2010-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include #include #include #include #include #include #include static void print__properties(mosquitto_property *properties) { int i; if(properties == NULL) return; printf("\tProperties:\n"); while(properties){ switch(properties->identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: printf("\t\tPayload format indicator: %d\n", properties->value.i8); break; case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: printf("\t\tRequest problem information: %d\n", properties->value.i8); break; case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: printf("\t\tRequest response information: %d\n", properties->value.i8); break; case MQTT_PROP_MAXIMUM_QOS: printf("\t\tMaximum QoS: %d\n", properties->value.i8); break; case MQTT_PROP_RETAIN_AVAILABLE: printf("\t\tRetain available: %d\n", properties->value.i8); break; case MQTT_PROP_WILDCARD_SUB_AVAILABLE: printf("\t\tWildcard sub available: %d\n", properties->value.i8); break; case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: printf("\t\tSubscription ID available: %d\n", properties->value.i8); break; case MQTT_PROP_SHARED_SUB_AVAILABLE: printf("\t\tShared subscription available: %d\n", properties->value.i8); break; case MQTT_PROP_SERVER_KEEP_ALIVE: printf("\t\tServer keep alive: %d\n", properties->value.i16); break; case MQTT_PROP_RECEIVE_MAXIMUM: printf("\t\tReceive maximum: %d\n", properties->value.i16); break; case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: printf("\t\tTopic alias maximum: %d\n", properties->value.i16); break; case MQTT_PROP_TOPIC_ALIAS: printf("\t\tTopic alias: %d\n", properties->value.i16); break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: printf("\t\tMessage expiry interval: %d\n", properties->value.i32); break; case MQTT_PROP_SESSION_EXPIRY_INTERVAL: printf("\t\tSession expiry interval: %d\n", properties->value.i32); break; case MQTT_PROP_WILL_DELAY_INTERVAL: printf("\t\tWill delay interval: %d\n", properties->value.i32); break; case MQTT_PROP_MAXIMUM_PACKET_SIZE: printf("\t\tMaximum packet size: %d\n", properties->value.i32); break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: printf("\t\tSubscription identifier: %d\n", properties->value.varint); break; case MQTT_PROP_CONTENT_TYPE: printf("\t\tContent type: %s\n", properties->value.s.v); break; case MQTT_PROP_RESPONSE_TOPIC: printf("\t\tResponse topic: %s\n", properties->value.s.v); break; case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: printf("\t\tAssigned client identifier: %s\n", properties->value.s.v); break; case MQTT_PROP_AUTHENTICATION_METHOD: printf("\t\tAuthentication method: %s\n", properties->value.s.v); break; case MQTT_PROP_RESPONSE_INFORMATION: printf("\t\tResponse information: %s\n", properties->value.s.v); break; case MQTT_PROP_SERVER_REFERENCE: printf("\t\tServer reference: %s\n", properties->value.s.v); break; case MQTT_PROP_REASON_STRING: printf("\t\tReason string: %s\n", properties->value.s.v); break; case MQTT_PROP_AUTHENTICATION_DATA: printf("\t\tAuthentication data: "); for(i=0; ivalue.bin.len; i++){ printf("%02X", properties->value.bin.v[i]); } printf("\n"); break; case MQTT_PROP_CORRELATION_DATA: printf("\t\tCorrelation data: "); for(i=0; ivalue.bin.len; i++){ printf("%02X", properties->value.bin.v[i]); } printf("\n"); break; case MQTT_PROP_USER_PROPERTY: printf("\t\tUser property: %s , %s\n", properties->name.v, properties->value.s.v); break; default: printf("\t\tInvalid property type: %d\n", properties->identifier); break; } properties = properties->next; } } void print__client(struct P_client *chunk, int length) { printf("DB_CHUNK_CLIENT:\n"); printf("\tLength: %d\n", length); printf("\tClient ID: %s\n", chunk->client_id); printf("\tLast MID: %d\n", chunk->F.last_mid); printf("\tSession expiry time: %" PRIu64 "\n", chunk->F.session_expiry_time); printf("\tSession expiry interval: %u\n", chunk->F.session_expiry_interval); } void print__client_msg(struct P_client_msg *chunk, int length) { printf("DB_CHUNK_CLIENT_MSG:\n"); printf("\tLength: %d\n", length); printf("\tClient ID: %s\n", chunk->client_id); printf("\tStore ID: %" PRIu64 "\n", chunk->F.store_id); printf("\tMID: %d\n", chunk->F.mid); printf("\tQoS: %d\n", chunk->F.qos); printf("\tRetain: %d\n", (chunk->F.retain_dup&0xF0)>>4); printf("\tDirection: %d\n", chunk->F.direction); printf("\tState: %d\n", chunk->F.state); printf("\tDup: %d\n", chunk->F.retain_dup&0x0F); print__properties(chunk->properties); } void print__msg_store(struct P_msg_store *chunk, int length) { printf("DB_CHUNK_MSG_STORE:\n"); printf("\tLength: %d\n", length); printf("\tStore ID: %" PRIu64 "\n", chunk->F.store_id); //printf("\tSource ID: %s\n", chunk->source_id); //printf("\tSource Username: %s\n", chunk->source_username); printf("\tSource Port: %d\n", chunk->F.source_port); printf("\tSource MID: %d\n", chunk->F.source_mid); printf("\tTopic: %s\n", chunk->topic); printf("\tQoS: %d\n", chunk->F.qos); printf("\tRetain: %d\n", chunk->F.retain); printf("\tPayload Length: %d\n", chunk->F.payloadlen); printf("\tExpiry Time: %" PRIu64 "\n", chunk->F.expiry_time); uint8_t *payload; payload = UHPA_ACCESS(chunk->payload, chunk->F.payloadlen); if(chunk->F.payloadlen < 256){ /* Print payloads with UTF-8 data below an arbitrary limit of 256 bytes */ if(mosquitto_validate_utf8((char *)payload, chunk->F.payloadlen) == MOSQ_ERR_SUCCESS){ printf("\tPayload: %s\n", payload); } } print__properties(chunk->properties); } void print__sub(struct P_sub *chunk, int length) { printf("DB_CHUNK_SUB:\n"); printf("\tLength: %d\n", length); printf("\tClient ID: %s\n", chunk->client_id); printf("\tTopic: %s\n", chunk->topic); printf("\tQoS: %d\n", chunk->F.qos); printf("\tSubscription ID: %d\n", chunk->F.identifier); printf("\tOptions: 0x%02X\n", chunk->F.options); } mosquitto-1.6.9/src/loop.c0000664000175000017500000005675713626052637014555 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. Tatsuzo Osawa - Add epoll. */ #include "config.h" #ifndef WIN32 # define _GNU_SOURCE #endif #include #ifndef WIN32 #ifdef WITH_EPOLL #include #define MAX_EVENTS 1000 #endif #include #include #else #include #include #include #endif #include #include #include #include #ifndef WIN32 # include #endif #include #ifdef WITH_WEBSOCKETS # include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "send_mosq.h" #include "sys_tree.h" #include "time_mosq.h" #include "util_mosq.h" extern bool flag_reload; #ifdef WITH_PERSISTENCE extern bool flag_db_backup; #endif extern bool flag_tree_print; extern int run; #ifdef WITH_EPOLL static void loop_handle_reads_writes(struct mosquitto_db *db, mosq_sock_t sock, uint32_t events); #else static void loop_handle_reads_writes(struct mosquitto_db *db, struct pollfd *pollfds); #endif #ifdef WITH_WEBSOCKETS static void temp__expire_websockets_clients(struct mosquitto_db *db) { struct mosquitto *context, *ctxt_tmp; static time_t last_check = 0; time_t now = mosquitto_time(); char *id; if(now - last_check > 60){ HASH_ITER(hh_id, db->contexts_by_id, context, ctxt_tmp){ if(context->wsi && context->sock != INVALID_SOCKET){ if(context->keepalive && now - context->last_msg_in > (time_t)(context->keepalive)*3/2){ if(db->config->connection_messages == true){ if(context->id){ id = context->id; }else{ id = ""; } if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s has exceeded timeout, disconnecting.", id); } } /* Client has exceeded keepalive*1.5 */ do_disconnect(db, context, MOSQ_ERR_KEEPALIVE); } } } last_check = mosquitto_time(); } } #endif #if defined(WITH_WEBSOCKETS) && LWS_LIBRARY_VERSION_NUMBER == 3002000 void lws__sul_callback(struct lws_sorted_usec_list *l) { } static struct lws_sorted_usec_list sul; #endif int mosquitto_main_loop(struct mosquitto_db *db, mosq_sock_t *listensock, int listensock_count) { #ifdef WITH_SYS_TREE time_t start_time = mosquitto_time(); #endif #ifdef WITH_PERSISTENCE time_t last_backup = mosquitto_time(); #endif time_t now = 0; int time_count; int fdcount; struct mosquitto *context, *ctxt_tmp; #ifndef WIN32 sigset_t sigblock, origsig; #endif int i; #ifdef WITH_EPOLL int j; struct epoll_event ev, events[MAX_EVENTS]; #else struct pollfd *pollfds = NULL; int pollfd_index; int pollfd_max; #endif #ifdef WITH_BRIDGE int rc; int err; socklen_t len; #endif #if defined(WITH_WEBSOCKETS) && LWS_LIBRARY_VERSION_NUMBER == 3002000 memset(&sul, 0, sizeof(struct lws_sorted_usec_list)); #endif #ifndef WIN32 sigemptyset(&sigblock); sigaddset(&sigblock, SIGINT); sigaddset(&sigblock, SIGTERM); sigaddset(&sigblock, SIGUSR1); sigaddset(&sigblock, SIGUSR2); sigaddset(&sigblock, SIGHUP); #endif #ifndef WITH_EPOLL #ifdef WIN32 pollfd_max = _getmaxstdio(); #else pollfd_max = sysconf(_SC_OPEN_MAX); #endif pollfds = mosquitto__malloc(sizeof(struct pollfd)*pollfd_max); if(!pollfds){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } #endif #ifdef WITH_EPOLL db->epollfd = 0; if ((db->epollfd = epoll_create(MAX_EVENTS)) == -1) { log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll creating: %s", strerror(errno)); return MOSQ_ERR_UNKNOWN; } memset(&ev, 0, sizeof(struct epoll_event)); memset(&events, 0, sizeof(struct epoll_event)*MAX_EVENTS); for(i=0; iepollfd, EPOLL_CTL_ADD, listensock[i], &ev) == -1) { log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll initial registering: %s", strerror(errno)); (void)close(db->epollfd); db->epollfd = 0; return MOSQ_ERR_UNKNOWN; } } #ifdef WITH_BRIDGE HASH_ITER(hh_sock, db->contexts_by_sock, context, ctxt_tmp){ if(context->bridge){ ev.data.fd = context->sock; ev.events = EPOLLIN; context->events = EPOLLIN; if (epoll_ctl(db->epollfd, EPOLL_CTL_ADD, context->sock, &ev) == -1) { log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll initial registering bridge: %s", strerror(errno)); (void)close(db->epollfd); db->epollfd = 0; return MOSQ_ERR_UNKNOWN; } } } #endif #endif while(run){ context__free_disused(db); #ifdef WITH_SYS_TREE if(db->config->sys_interval > 0){ sys_tree__update(db, db->config->sys_interval, start_time); } #endif #ifndef WITH_EPOLL memset(pollfds, -1, sizeof(struct pollfd)*pollfd_max); pollfd_index = 0; for(i=0; icontexts_by_sock, context, ctxt_tmp){ if(time_count > 0){ time_count--; }else{ time_count = 1000; now = mosquitto_time(); } context->pollfd_index = -1; if(context->sock != INVALID_SOCKET){ #ifdef WITH_BRIDGE if(context->bridge){ mosquitto__check_keepalive(db, context); if(context->bridge->round_robin == false && context->bridge->cur_address != 0 && context->bridge->primary_retry && now > context->bridge->primary_retry){ if(context->bridge->primary_retry_sock == INVALID_SOCKET){ rc = net__try_connect(context->bridge->addresses[0].address, context->bridge->addresses[0].port, &context->bridge->primary_retry_sock, NULL, false); if(rc == 0){ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = 0; net__socket_close(db, context); context->bridge->cur_address = 0; } }else{ len = sizeof(int); if(!getsockopt(context->bridge->primary_retry_sock, SOL_SOCKET, SO_ERROR, (char *)&err, &len)){ if(err == 0){ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = 0; net__socket_close(db, context); context->bridge->cur_address = context->bridge->address_count-1; }else{ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = now+5; } }else{ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = now+5; } } } } #endif /* Local bridges never time out in this fashion. */ if(!(context->keepalive) || context->bridge || now - context->last_msg_in <= (time_t)(context->keepalive)*3/2){ if(db__message_write(db, context) == MOSQ_ERR_SUCCESS){ #ifdef WITH_EPOLL if(context->current_out_packet || context->state == mosq_cs_connect_pending || context->ws_want_write){ if(!(context->events & EPOLLOUT)) { ev.data.fd = context->sock; ev.events = EPOLLIN | EPOLLOUT; if(epoll_ctl(db->epollfd, EPOLL_CTL_ADD, context->sock, &ev) == -1) { if((errno != EEXIST)||(epoll_ctl(db->epollfd, EPOLL_CTL_MOD, context->sock, &ev) == -1)) { log__printf(NULL, MOSQ_LOG_DEBUG, "Error in epoll re-registering to EPOLLOUT: %s", strerror(errno)); } } context->events = EPOLLIN | EPOLLOUT; } context->ws_want_write = false; } else{ if(context->events & EPOLLOUT) { ev.data.fd = context->sock; ev.events = EPOLLIN; if(epoll_ctl(db->epollfd, EPOLL_CTL_ADD, context->sock, &ev) == -1) { if((errno != EEXIST)||(epoll_ctl(db->epollfd, EPOLL_CTL_MOD, context->sock, &ev) == -1)) { log__printf(NULL, MOSQ_LOG_DEBUG, "Error in epoll re-registering to EPOLLIN: %s", strerror(errno)); } } context->events = EPOLLIN; } } #else pollfds[pollfd_index].fd = context->sock; pollfds[pollfd_index].events = POLLIN; pollfds[pollfd_index].revents = 0; if(context->current_out_packet || context->state == mosq_cs_connect_pending || context->ws_want_write){ pollfds[pollfd_index].events |= POLLOUT; context->ws_want_write = false; } context->pollfd_index = pollfd_index; pollfd_index++; #endif }else{ do_disconnect(db, context, MOSQ_ERR_CONN_LOST); } }else{ /* Client has exceeded keepalive*1.5 */ do_disconnect(db, context, MOSQ_ERR_KEEPALIVE); } } } #ifdef WITH_BRIDGE time_count = 0; for(i=0; ibridge_count; i++){ if(!db->bridges[i]) continue; context = db->bridges[i]; if(context->sock == INVALID_SOCKET){ if(time_count > 0){ time_count--; }else{ time_count = 1000; now = mosquitto_time(); } /* Want to try to restart the bridge connection */ if(!context->bridge->restart_t){ context->bridge->restart_t = now+context->bridge->restart_timeout; context->bridge->cur_address++; if(context->bridge->cur_address == context->bridge->address_count){ context->bridge->cur_address = 0; } }else{ if((context->bridge->start_type == bst_lazy && context->bridge->lazy_reconnect) || (context->bridge->start_type == bst_automatic && now > context->bridge->restart_t)){ #if defined(__GLIBC__) && defined(WITH_ADNS) if(context->adns){ /* Connection attempted, waiting on DNS lookup */ rc = gai_error(context->adns); if(rc == EAI_INPROGRESS){ /* Just keep on waiting */ }else if(rc == 0){ rc = bridge__connect_step2(db, context); if(rc == MOSQ_ERR_SUCCESS){ #ifdef WITH_EPOLL ev.data.fd = context->sock; ev.events = EPOLLIN; if(context->current_out_packet){ ev.events |= EPOLLOUT; } if(epoll_ctl(db->epollfd, EPOLL_CTL_ADD, context->sock, &ev) == -1) { if((errno != EEXIST)||(epoll_ctl(db->epollfd, EPOLL_CTL_MOD, context->sock, &ev) == -1)) { log__printf(NULL, MOSQ_LOG_DEBUG, "Error in epoll re-registering bridge: %s", strerror(errno)); } }else{ context->events = ev.events; } #else pollfds[pollfd_index].fd = context->sock; pollfds[pollfd_index].events = POLLIN; pollfds[pollfd_index].revents = 0; if(context->current_out_packet){ pollfds[pollfd_index].events |= POLLOUT; } context->pollfd_index = pollfd_index; pollfd_index++; #endif }else if(rc == MOSQ_ERR_CONN_PENDING){ context->bridge->restart_t = 0; }else{ context->bridge->cur_address++; if(context->bridge->cur_address == context->bridge->address_count){ context->bridge->cur_address = 0; } context->bridge->restart_t = 0; } }else{ /* Need to retry */ if(context->adns->ar_result){ freeaddrinfo(context->adns->ar_result); } mosquitto__free(context->adns); context->adns = NULL; context->bridge->restart_t = 0; } }else{ #ifdef WITH_EPOLL /* clean any events triggered in previous connection */ context->events = 0; #endif rc = bridge__connect_step1(db, context); if(rc){ context->bridge->cur_address++; if(context->bridge->cur_address == context->bridge->address_count){ context->bridge->cur_address = 0; } }else{ /* Short wait for ADNS lookup */ context->bridge->restart_t = 1; } } #else { rc = bridge__connect(db, context); context->bridge->restart_t = 0; if(rc == MOSQ_ERR_SUCCESS){ if(context->bridge->round_robin == false && context->bridge->cur_address != 0){ context->bridge->primary_retry = now + 5; } #ifdef WITH_EPOLL ev.data.fd = context->sock; ev.events = EPOLLIN; if(context->current_out_packet){ ev.events |= EPOLLOUT; } if(epoll_ctl(db->epollfd, EPOLL_CTL_ADD, context->sock, &ev) == -1) { if((errno != EEXIST)||(epoll_ctl(db->epollfd, EPOLL_CTL_MOD, context->sock, &ev) == -1)) { log__printf(NULL, MOSQ_LOG_DEBUG, "Error in epoll re-registering bridge: %s", strerror(errno)); } }else{ context->events = ev.events; } #else pollfds[pollfd_index].fd = context->sock; pollfds[pollfd_index].events = POLLIN; pollfds[pollfd_index].revents = 0; if(context->current_out_packet){ pollfds[pollfd_index].events |= POLLOUT; } context->pollfd_index = pollfd_index; pollfd_index++; #endif }else{ context->bridge->cur_address++; if(context->bridge->cur_address == context->bridge->address_count){ context->bridge->cur_address = 0; } } } #endif } } } } #endif #ifndef WIN32 sigprocmask(SIG_SETMASK, &sigblock, &origsig); #ifdef WITH_EPOLL fdcount = epoll_wait(db->epollfd, events, MAX_EVENTS, 100); #else fdcount = poll(pollfds, pollfd_index, 100); #endif sigprocmask(SIG_SETMASK, &origsig, NULL); #else fdcount = WSAPoll(pollfds, pollfd_index, 100); #endif #ifdef WITH_EPOLL switch(fdcount){ case -1: if(errno != EINTR){ log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll waiting: %s.", strerror(errno)); } break; case 0: break; default: for(i=0; iepollfd, EPOLL_CTL_ADD, ev.data.fd, &ev) == -1) { log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll accepting: %s", strerror(errno)); } context = NULL; HASH_FIND(hh_sock, db->contexts_by_sock, &(ev.data.fd), sizeof(mosq_sock_t), context); if(context){ context->events = EPOLLIN; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll accepting: no context"); } } } break; } } if (j == listensock_count) { loop_handle_reads_writes(db, events[i].data.fd, events[i].events); } } } #else if(fdcount == -1){ # ifdef WIN32 if(pollfd_index == 0 && WSAGetLastError() == WSAEINVAL){ /* WSAPoll() immediately returns an error if it is not given * any sockets to wait on. This can happen if we only have * websockets listeners. Sleep a little to prevent a busy loop. */ Sleep(10); }else # endif { log__printf(NULL, MOSQ_LOG_ERR, "Error in poll: %s.", strerror(errno)); } }else{ loop_handle_reads_writes(db, pollfds); for(i=0; iconfig->persistence && db->config->autosave_interval){ if(db->config->autosave_on_changes){ if(db->persistence_changes >= db->config->autosave_interval){ persist__backup(db, false); db->persistence_changes = 0; } }else{ if(last_backup + db->config->autosave_interval < mosquitto_time()){ persist__backup(db, false); last_backup = mosquitto_time(); } } } #endif #ifdef WITH_PERSISTENCE if(flag_db_backup){ persist__backup(db, false); flag_db_backup = false; } #endif if(flag_reload){ log__printf(NULL, MOSQ_LOG_INFO, "Reloading config."); config__read(db, db->config, true); mosquitto_security_cleanup(db, true); mosquitto_security_init(db, true); mosquitto_security_apply(db); log__close(db->config); log__init(db->config); flag_reload = false; } if(flag_tree_print){ sub__tree_print(db->subs, 0); flag_tree_print = false; } #ifdef WITH_WEBSOCKETS for(i=0; iconfig->listener_count; i++){ /* Extremely hacky, should be using the lws provided external poll * interface, but their interface has changed recently and ours * will soon, so for now websockets clients are second class * citizens. */ if(db->config->listeners[i].ws_context){ #if LWS_LIBRARY_VERSION_NUMBER > 3002000 libwebsocket_service(db->config->listeners[i].ws_context, -1); #elif LWS_LIBRARY_VERSION_NUMBER == 3002000 lws_sul_schedule(db->config->listeners[i].ws_context, 0, &sul, lws__sul_callback, 10); libwebsocket_service(db->config->listeners[i].ws_context, 0); #else libwebsocket_service(db->config->listeners[i].ws_context, 0); #endif } } if(db->config->have_websockets_listener){ temp__expire_websockets_clients(db); } #endif } #ifdef WITH_EPOLL (void) close(db->epollfd); db->epollfd = 0; #else mosquitto__free(pollfds); #endif return MOSQ_ERR_SUCCESS; } void do_disconnect(struct mosquitto_db *db, struct mosquitto *context, int reason) { char *id; #ifdef WITH_EPOLL struct epoll_event ev; #endif #ifdef WITH_WEBSOCKETS bool is_duplicate = false; #endif if(context->state == mosq_cs_disconnected){ return; } #ifdef WITH_WEBSOCKETS if(context->wsi){ if(context->state == mosq_cs_duplicate){ is_duplicate = true; } if(context->state != mosq_cs_disconnecting && context->state != mosq_cs_disconnect_with_will){ mosquitto__set_state(context, mosq_cs_disconnect_ws); } if(context->wsi){ libwebsocket_callback_on_writable(context->ws_context, context->wsi); } if(context->sock != INVALID_SOCKET){ HASH_DELETE(hh_sock, db->contexts_by_sock, context); #ifdef WITH_EPOLL if (epoll_ctl(db->epollfd, EPOLL_CTL_DEL, context->sock, &ev) == -1) { log__printf(NULL, MOSQ_LOG_DEBUG, "Error in epoll disconnecting websockets: %s", strerror(errno)); } #endif context->sock = INVALID_SOCKET; context->pollfd_index = -1; } if(is_duplicate){ /* This occurs if another client is taking over the same client id. * It is important to remove this from the by_id hash here, so it * doesn't leave us with multiple clients in the hash with the same * id. Websockets doesn't actually close the connection here, * unlike for normal clients, which means there is extra time when * there could be two clients with the same id in the hash. */ context__remove_from_by_id(db, context); } }else #endif { if(db->config->connection_messages == true){ if(context->id){ id = context->id; }else{ id = ""; } if(context->state != mosq_cs_disconnecting && context->state != mosq_cs_disconnect_with_will){ switch(reason){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_PROTOCOL: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected due to protocol error.", id); break; case MOSQ_ERR_CONN_LOST: log__printf(NULL, MOSQ_LOG_NOTICE, "Socket error on client %s, disconnecting.", id); break; case MOSQ_ERR_AUTH: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected, no longer authorised.", id); break; case MOSQ_ERR_KEEPALIVE: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s has exceeded timeout, disconnecting.", id); break; default: log__printf(NULL, MOSQ_LOG_NOTICE, "Socket error on client %s, disconnecting.", id); break; } }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected.", id); } } #ifdef WITH_EPOLL if (context->sock != INVALID_SOCKET && epoll_ctl(db->epollfd, EPOLL_CTL_DEL, context->sock, &ev) == -1) { if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_DEBUG, "Error in epoll disconnecting: %s", strerror(errno)); } } #endif context__disconnect(db, context); } } #ifdef WITH_EPOLL static void loop_handle_reads_writes(struct mosquitto_db *db, mosq_sock_t sock, uint32_t events) #else static void loop_handle_reads_writes(struct mosquitto_db *db, struct pollfd *pollfds) #endif { struct mosquitto *context; #ifndef WITH_EPOLL struct mosquitto *ctxt_tmp; #endif int err; socklen_t len; int rc; #ifdef WITH_EPOLL int i; context = NULL; HASH_FIND(hh_sock, db->contexts_by_sock, &sock, sizeof(mosq_sock_t), context); if(!context) { return; } for (i=0;i<1;i++) { #else HASH_ITER(hh_sock, db->contexts_by_sock, context, ctxt_tmp){ if(context->pollfd_index < 0){ continue; } assert(pollfds[context->pollfd_index].fd == context->sock); #endif #ifdef WITH_WEBSOCKETS if(context->wsi){ struct lws_pollfd wspoll; #ifdef WITH_EPOLL wspoll.fd = context->sock; wspoll.events = context->events; wspoll.revents = events; #else wspoll.fd = pollfds[context->pollfd_index].fd; wspoll.events = pollfds[context->pollfd_index].events; wspoll.revents = pollfds[context->pollfd_index].revents; #endif #ifdef LWS_LIBRARY_VERSION_NUMBER lws_service_fd(lws_get_context(context->wsi), &wspoll); #else lws_service_fd(context->ws_context, &wspoll); #endif continue; } #endif #ifdef WITH_TLS #ifdef WITH_EPOLL if(events & EPOLLOUT || #else if(pollfds[context->pollfd_index].revents & POLLOUT || #endif context->want_write || (context->ssl && context->state == mosq_cs_new)){ #else #ifdef WITH_EPOLL if(events & EPOLLOUT){ #else if(pollfds[context->pollfd_index].revents & POLLOUT){ #endif #endif if(context->state == mosq_cs_connect_pending){ len = sizeof(int); if(!getsockopt(context->sock, SOL_SOCKET, SO_ERROR, (char *)&err, &len)){ if(err == 0){ mosquitto__set_state(context, mosq_cs_new); #if defined(WITH_ADNS) && defined(WITH_BRIDGE) if(context->bridge){ bridge__connect_step3(db, context); continue; } #endif } }else{ do_disconnect(db, context, MOSQ_ERR_CONN_LOST); continue; } } rc = packet__write(context); if(rc){ do_disconnect(db, context, rc); continue; } } } #ifdef WITH_EPOLL context = NULL; HASH_FIND(hh_sock, db->contexts_by_sock, &sock, sizeof(mosq_sock_t), context); if(!context) { return; } for (i=0;i<1;i++) { #else HASH_ITER(hh_sock, db->contexts_by_sock, context, ctxt_tmp){ if(context->pollfd_index < 0){ continue; } #endif #ifdef WITH_WEBSOCKETS if(context->wsi){ // Websocket are already handled above continue; } #endif #ifdef WITH_TLS #ifdef WITH_EPOLL if(events & EPOLLIN || #else if(pollfds[context->pollfd_index].revents & POLLIN || #endif (context->ssl && context->state == mosq_cs_new)){ #else #ifdef WITH_EPOLL if(events & EPOLLIN){ #else if(pollfds[context->pollfd_index].revents & POLLIN){ #endif #endif do{ rc = packet__read(db, context); if(rc){ do_disconnect(db, context, rc); continue; } }while(SSL_DATA_PENDING(context)); }else{ #ifdef WITH_EPOLL if(events & (EPOLLERR | EPOLLHUP)){ #else if(context->pollfd_index >= 0 && pollfds[context->pollfd_index].revents & (POLLERR | POLLNVAL | POLLHUP)){ #endif do_disconnect(db, context, MOSQ_ERR_CONN_LOST); continue; } } } } mosquitto-1.6.9/src/mosquitto_plugin.h0000664000175000017500000002656513626052637017225 0ustar rogerroger/* Copyright (c) 2012-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_PLUGIN_H #define MOSQUITTO_PLUGIN_H #ifdef __cplusplus extern "C" { #endif #define MOSQ_AUTH_PLUGIN_VERSION 4 #define MOSQ_ACL_NONE 0x00 #define MOSQ_ACL_READ 0x01 #define MOSQ_ACL_WRITE 0x02 #define MOSQ_ACL_SUBSCRIBE 0x04 #include #include struct mosquitto; struct mosquitto_opt { char *key; char *value; }; struct mosquitto_auth_opt { char *key; char *value; }; struct mosquitto_acl_msg { const char *topic; const void *payload; long payloadlen; int qos; bool retain; }; /* * To create an authentication plugin you must include this file then implement * the functions listed in the "Plugin Functions" section below. The resulting * code should then be compiled as a shared library. Using gcc this can be * achieved as follows: * * gcc -I -fPIC -shared plugin.c -o plugin.so * * On Mac OS X: * * gcc -I -fPIC -shared plugin.c -undefined dynamic_lookup -o plugin.so * * Authentication plugins can implement one or both of authentication and * access control. If your plugin does not wish to handle either of * authentication or access control it should return MOSQ_ERR_PLUGIN_DEFER. In * this case, the next plugin will handle it. If all plugins return * MOSQ_ERR_PLUGIN_DEFER, the request will be denied. * * For each check, the following flow happens: * * * The default password file and/or acl file checks are made. If either one * of these is not defined, then they are considered to be deferred. If either * one accepts the check, no further checks are made. If an error occurs, the * check is denied * * The first plugin does the check, if it returns anything other than * MOSQ_ERR_PLUGIN_DEFER, then the check returns immediately. If the plugin * returns MOSQ_ERR_PLUGIN_DEFER then the next plugin runs its check. * * If the final plugin returns MOSQ_ERR_PLUGIN_DEFER, then access will be * denied. */ /* ========================================================================= * * Helper Functions * * ========================================================================= */ /* There are functions that are available for plugin developers to use in * mosquitto_broker.h, including logging and accessor functions. */ /* ========================================================================= * * Plugin Functions * * You must implement these functions in your plugin. * * ========================================================================= */ /* * Function: mosquitto_auth_plugin_version * * The broker will call this function immediately after loading the plugin to * check it is a supported plugin version. Your code must simply return * MOSQ_AUTH_PLUGIN_VERSION. */ int mosquitto_auth_plugin_version(void); /* * Function: mosquitto_auth_plugin_init * * Called after the plugin has been loaded and * has been called. This will only ever be called once and can be used to * initialise the plugin. * * Parameters: * * user_data : The pointer set here will be passed to the other plugin * functions. Use to hold connection information for example. * opts : Pointer to an array of struct mosquitto_opt, which * provides the plugin options defined in the configuration file. * opt_count : The number of elements in the opts array. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *opts, int opt_count); /* * Function: mosquitto_auth_plugin_cleanup * * Called when the broker is shutting down. This will only ever be called once * per plugin. * Note that will be called directly before * this function. * * Parameters: * * user_data : The pointer provided in . * opts : Pointer to an array of struct mosquitto_opt, which * provides the plugin options defined in the configuration file. * opt_count : The number of elements in the opts array. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count); /* * Function: mosquitto_auth_security_init * * This function is called in two scenarios: * * 1. When the broker starts up. * 2. If the broker is requested to reload its configuration whilst running. In * this case, will be called first, then * this function will be called. In this situation, the reload parameter * will be true. * * Parameters: * * user_data : The pointer provided in . * opts : Pointer to an array of struct mosquitto_opt, which * provides the plugin options defined in the configuration file. * opt_count : The number of elements in the opts array. * reload : If set to false, this is the first time the function has * been called. If true, the broker has received a signal * asking to reload its configuration. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *opts, int opt_count, bool reload); /* * Function: mosquitto_auth_security_cleanup * * This function is called in two scenarios: * * 1. When the broker is shutting down. * 2. If the broker is requested to reload its configuration whilst running. In * this case, this function will be called, followed by * . In this situation, the reload parameter * will be true. * * Parameters: * * user_data : The pointer provided in . * opts : Pointer to an array of struct mosquitto_opt, which * provides the plugin options defined in the configuration file. * opt_count : The number of elements in the opts array. * reload : If set to false, this is the first time the function has * been called. If true, the broker has received a signal * asking to reload its configuration. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count, bool reload); /* * Function: mosquitto_auth_acl_check * * Called by the broker when topic access must be checked. access will be one * of: * MOSQ_ACL_SUBSCRIBE when a client is asking to subscribe to a topic string. * This differs from MOSQ_ACL_READ in that it allows you to * deny access to topic strings rather than by pattern. For * example, you may use MOSQ_ACL_SUBSCRIBE to deny * subscriptions to '#', but allow all topics in * MOSQ_ACL_READ. This allows clients to subscribe to any * topic they want, but not discover what topics are in use * on the server. * MOSQ_ACL_READ when a message is about to be sent to a client (i.e. whether * it can read that topic or not). * MOSQ_ACL_WRITE when a message has been received from a client (i.e. whether * it can write to that topic or not). * * Return: * MOSQ_ERR_SUCCESS if access was granted. * MOSQ_ERR_ACL_DENIED if access was not granted. * MOSQ_ERR_UNKNOWN for an application specific error. * MOSQ_ERR_PLUGIN_DEFER if your plugin does not wish to handle this check. */ int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg); /* * Function: mosquitto_auth_unpwd_check * * This function is OPTIONAL. Only include this function in your plugin if you * are making basic username/password checks. * * Called by the broker when a username/password must be checked. * * Return: * MOSQ_ERR_SUCCESS if the user is authenticated. * MOSQ_ERR_AUTH if authentication failed. * MOSQ_ERR_UNKNOWN for an application specific error. * MOSQ_ERR_PLUGIN_DEFER if your plugin does not wish to handle this check. */ int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password); /* * Function: mosquitto_psk_key_get * * This function is OPTIONAL. Only include this function in your plugin if you * are making TLS-PSK checks. * * Called by the broker when a client connects to a listener using TLS/PSK. * This is used to retrieve the pre-shared-key associated with a client * identity. * * Examine hint and identity to determine the required PSK (which must be a * hexadecimal string with no leading "0x") and copy this string into key. * * Parameters: * user_data : the pointer provided in . * hint : the psk_hint for the listener the client is connecting to. * identity : the identity string provided by the client * key : a string where the hex PSK should be copied * max_key_len : the size of key * * Return value: * Return 0 on success. * Return >0 on failure. * Return MOSQ_ERR_PLUGIN_DEFER if your plugin does not wish to handle this check. */ int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len); /* * Function: mosquitto_auth_start * * This function is OPTIONAL. Only include this function in your plugin if you * are making extended authentication checks. * * Parameters: * user_data : the pointer provided in . * method : the authentication method * reauth : this is set to false if this is the first authentication attempt * on a connection, set to true if the client is attempting to * reauthenticate. * data_in : pointer to authentication data, or NULL * data_in_len : length of data_in, in bytes * data_out : if your plugin wishes to send authentication data back to the * client, allocate some memory using malloc or friends and set * data_out. The broker will free the memory after use. * data_out_len : Set the length of data_out in bytes. * * Return value: * Return MOSQ_ERR_SUCCESS if authentication was successful. * Return MOSQ_ERR_AUTH_CONTINUE if the authentication is a multi step process and can continue. * Return MOSQ_ERR_AUTH if authentication was valid but did not succeed. * Return any other relevant positive integer MOSQ_ERR_* to produce an error. */ int mosquitto_auth_start(void *user_data, struct mosquitto *client, const char *method, bool reauth, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len); int mosquitto_auth_continue(void *user_data, struct mosquitto *client, const char *method, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len); #ifdef __cplusplus } #endif #endif mosquitto-1.6.9/src/mosquitto.c0000664000175000017500000002546513626052637015640 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifndef WIN32 /* For initgroups() */ # include # include # include #endif #ifndef WIN32 #include #else #include #include #include #endif #ifndef WIN32 # include #endif #include #include #include #include #ifdef WITH_SYSTEMD # include #endif #ifdef WITH_WRAP #include #endif #ifdef WITH_WEBSOCKETS # include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "misc_mosq.h" #include "util_mosq.h" struct mosquitto_db int_db; bool flag_reload = false; #ifdef WITH_PERSISTENCE bool flag_db_backup = false; #endif bool flag_tree_print = false; int run; #ifdef WITH_WRAP #include int allow_severity = LOG_INFO; int deny_severity = LOG_INFO; #endif void handle_sigint(int signal); void handle_sigusr1(int signal); void handle_sigusr2(int signal); #ifdef SIGHUP void handle_sighup(int signal); #endif struct mosquitto_db *mosquitto__get_db(void) { return &int_db; } /* mosquitto shouldn't run as root. * This function will attempt to change to an unprivileged user and group if * running as root. The user is given in config->user. * Returns 1 on failure (unknown user, setuid/setgid failure) * Returns 0 on success. * Note that setting config->user to "root" does not produce an error, but it * strongly discouraged. */ int drop_privileges(struct mosquitto__config *config, bool temporary) { #if !defined(__CYGWIN__) && !defined(WIN32) struct passwd *pwd; char *err; int rc; const char *snap = getenv("SNAP_NAME"); if(snap && !strcmp(snap, "mosquitto")){ /* Don't attempt to drop privileges if running as a snap */ return MOSQ_ERR_SUCCESS; } if(geteuid() == 0){ if(config->user && strcmp(config->user, "root")){ pwd = getpwnam(config->user); if(!pwd){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid user '%s'.", config->user); return 1; } if(initgroups(config->user, pwd->pw_gid) == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting groups whilst dropping privileges: %s.", err); return 1; } if(temporary){ rc = setegid(pwd->pw_gid); }else{ rc = setgid(pwd->pw_gid); } if(rc == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting gid whilst dropping privileges: %s.", err); return 1; } if(temporary){ rc = seteuid(pwd->pw_uid); }else{ rc = setuid(pwd->pw_uid); } if(rc == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting uid whilst dropping privileges: %s.", err); return 1; } } if(geteuid() == 0 || getegid() == 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Mosquitto should not be run as root/administrator."); } } #endif return MOSQ_ERR_SUCCESS; } int restore_privileges(void) { #if !defined(__CYGWIN__) && !defined(WIN32) char *err; int rc; if(getuid() == 0){ rc = setegid(0); if(rc == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting gid whilst restoring privileges: %s.", err); return 1; } rc = seteuid(0); if(rc == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting uid whilst restoring privileges: %s.", err); return 1; } } #endif return MOSQ_ERR_SUCCESS; } void mosquitto__daemonise(void) { #ifndef WIN32 char *err; pid_t pid; pid = fork(); if(pid < 0){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error in fork: %s", err); exit(1); } if(pid > 0){ exit(0); } if(setsid() < 0){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error in setsid: %s", err); exit(1); } assert(freopen("/dev/null", "r", stdin)); assert(freopen("/dev/null", "w", stdout)); assert(freopen("/dev/null", "w", stderr)); #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Can't start in daemon mode in Windows."); #endif } int main(int argc, char *argv[]) { mosq_sock_t *listensock = NULL; int listensock_count = 0; int listensock_index = 0; struct mosquitto__config config; int i, j; FILE *pid; int rc; #ifdef WIN32 SYSTEMTIME st; #else struct timeval tv; #endif struct mosquitto *ctxt, *ctxt_tmp; #if defined(WIN32) || defined(__CYGWIN__) if(argc == 2){ if(!strcmp(argv[1], "run")){ service_run(); return 0; }else if(!strcmp(argv[1], "install")){ service_install(); return 0; }else if(!strcmp(argv[1], "uninstall")){ service_uninstall(); return 0; } } #endif #ifdef WIN32 GetSystemTime(&st); srand(st.wSecond + st.wMilliseconds); #else gettimeofday(&tv, NULL); srand(tv.tv_sec + tv.tv_usec); #endif #ifdef WIN32 _setmaxstdio(2048); #endif memset(&int_db, 0, sizeof(struct mosquitto_db)); net__broker_init(); config__init(&int_db, &config); rc = config__parse_args(&int_db, &config, argc, argv); if(rc != MOSQ_ERR_SUCCESS) return rc; int_db.config = &config; if(config.daemon){ mosquitto__daemonise(); } if(config.daemon && config.pid_file){ pid = mosquitto__fopen(config.pid_file, "wt", false); if(pid){ fprintf(pid, "%d", getpid()); fclose(pid); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to write pid file."); return 1; } } rc = db__open(&config, &int_db); if(rc != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Couldn't open database."); return rc; } /* Initialise logging only after initialising the database in case we're * logging to topics */ if(log__init(&config)){ rc = 1; return rc; } log__printf(NULL, MOSQ_LOG_INFO, "mosquitto version %s starting", VERSION); if(int_db.config_file){ log__printf(NULL, MOSQ_LOG_INFO, "Config loaded from %s.", int_db.config_file); }else{ log__printf(NULL, MOSQ_LOG_INFO, "Using default config."); } rc = mosquitto_security_module_init(&int_db); if(rc) return rc; rc = mosquitto_security_init(&int_db, false); if(rc) return rc; #ifdef WITH_SYS_TREE sys_tree__init(&int_db); #endif listensock_index = 0; for(i=0; ilistener_count; i++){ if(int_db.config->listeners[i].ws_context){ libwebsocket_context_destroy(int_db.config->listeners[i].ws_context); } mosquitto__free(int_db.config->listeners[i].ws_protocol); } #endif /* FIXME - this isn't quite right, all wills with will delay zero should be * sent now, but those with positive will delay should be persisted and * restored, pending the client reconnecting in time. */ HASH_ITER(hh_id, int_db.contexts_by_id, ctxt, ctxt_tmp){ context__send_will(&int_db, ctxt); } will_delay__send_all(&int_db); #ifdef WITH_PERSISTENCE if(config.persistence){ persist__backup(&int_db, true); } #endif session_expiry__remove_all(&int_db); HASH_ITER(hh_id, int_db.contexts_by_id, ctxt, ctxt_tmp){ #ifdef WITH_WEBSOCKETS if(!ctxt->wsi){ context__cleanup(&int_db, ctxt, true); } #else context__cleanup(&int_db, ctxt, true); #endif } HASH_ITER(hh_sock, int_db.contexts_by_sock, ctxt, ctxt_tmp){ context__cleanup(&int_db, ctxt, true); } #ifdef WITH_BRIDGE for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifdef WITH_SYS_TREE #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "time_mosq.h" #define BUFLEN 100 #define SYS_TREE_QOS 2 uint64_t g_bytes_received = 0; uint64_t g_bytes_sent = 0; uint64_t g_pub_bytes_received = 0; uint64_t g_pub_bytes_sent = 0; unsigned long g_msgs_received = 0; unsigned long g_msgs_sent = 0; unsigned long g_pub_msgs_received = 0; unsigned long g_pub_msgs_sent = 0; unsigned long g_msgs_dropped = 0; int g_clients_expired = 0; unsigned int g_socket_connections = 0; unsigned int g_connection_count = 0; void sys_tree__init(struct mosquitto_db *db) { char buf[64]; if(db->config->sys_interval == 0){ return; } /* Set static $SYS messages */ snprintf(buf, 64, "mosquitto version %s", VERSION); db__messages_easy_queue(db, NULL, "$SYS/broker/version", SYS_TREE_QOS, strlen(buf), buf, 1, 0, NULL); } static void sys_tree__update_clients(struct mosquitto_db *db, char *buf) { static int client_count = -1; static int clients_expired = -1; static int client_max = 0; static int disconnected_count = -1; static int connected_count = -1; int count_total, count_by_sock; count_total = HASH_CNT(hh_id, db->contexts_by_id); count_by_sock = HASH_CNT(hh_sock, db->contexts_by_sock); if(client_count != count_total){ client_count = count_total; snprintf(buf, BUFLEN, "%d", client_count); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/total", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); if(client_count > client_max){ client_max = client_count; snprintf(buf, BUFLEN, "%d", client_max); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/maximum", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } } if(disconnected_count != count_total-count_by_sock){ disconnected_count = count_total-count_by_sock; if(disconnected_count < 0){ /* If a client has connected but not sent a CONNECT at this point, * then it is possible that count_by_sock will be bigger than * count_total, causing a negative number. This situation should * not last for long, so just cap at zero and ignore. */ disconnected_count = 0; } snprintf(buf, BUFLEN, "%d", disconnected_count); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/inactive", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/disconnected", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(connected_count != count_by_sock){ connected_count = count_by_sock; snprintf(buf, BUFLEN, "%d", connected_count); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/active", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/connected", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(g_clients_expired != clients_expired){ clients_expired = g_clients_expired; snprintf(buf, BUFLEN, "%d", clients_expired); db__messages_easy_queue(db, NULL, "$SYS/broker/clients/expired", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } } #ifdef REAL_WITH_MEMORY_TRACKING static void sys_tree__update_memory(struct mosquitto_db *db, char *buf) { static unsigned long current_heap = -1; static unsigned long max_heap = -1; unsigned long value_ul; value_ul = mosquitto__memory_used(); if(current_heap != value_ul){ current_heap = value_ul; snprintf(buf, BUFLEN, "%lu", current_heap); db__messages_easy_queue(db, NULL, "$SYS/broker/heap/current", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } value_ul =mosquitto__max_memory_used(); if(max_heap != value_ul){ max_heap = value_ul; snprintf(buf, BUFLEN, "%lu", max_heap); db__messages_easy_queue(db, NULL, "$SYS/broker/heap/maximum", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } } #endif static void calc_load(struct mosquitto_db *db, char *buf, const char *topic, bool initial, double exponent, double interval, double *current) { double new_value; if (initial) { new_value = *current; snprintf(buf, BUFLEN, "%.2f", new_value); db__messages_easy_queue(db, NULL, topic, SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } else { new_value = interval + exponent*((*current) - interval); if(fabs(new_value - (*current)) >= 0.01){ snprintf(buf, BUFLEN, "%.2f", new_value); db__messages_easy_queue(db, NULL, topic, SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } } (*current) = new_value; } /* Send messages for the $SYS hierarchy if the last update is longer than * 'interval' seconds ago. * 'interval' is the amount of seconds between updates. If 0, then no periodic * messages are sent for the $SYS hierarchy. * 'start_time' is the result of time() that the broker was started at. */ void sys_tree__update(struct mosquitto_db *db, int interval, time_t start_time) { static time_t last_update = 0; time_t now; time_t uptime; char buf[BUFLEN]; static int msg_store_count = -1; static unsigned long msg_store_bytes = -1; static unsigned long msgs_received = -1; static unsigned long msgs_sent = -1; static unsigned long publish_dropped = -1; static unsigned long pub_msgs_received = -1; static unsigned long pub_msgs_sent = -1; static unsigned long long bytes_received = -1; static unsigned long long bytes_sent = -1; static unsigned long long pub_bytes_received = -1; static unsigned long long pub_bytes_sent = -1; static int subscription_count = -1; static int shared_subscription_count = -1; static int retained_count = -1; static double msgs_received_load1 = 0; static double msgs_received_load5 = 0; static double msgs_received_load15 = 0; static double msgs_sent_load1 = 0; static double msgs_sent_load5 = 0; static double msgs_sent_load15 = 0; static double publish_dropped_load1 = 0; static double publish_dropped_load5 = 0; static double publish_dropped_load15 = 0; double msgs_received_interval, msgs_sent_interval, publish_dropped_interval; static double publish_received_load1 = 0; static double publish_received_load5 = 0; static double publish_received_load15 = 0; static double publish_sent_load1 = 0; static double publish_sent_load5 = 0; static double publish_sent_load15 = 0; double publish_received_interval, publish_sent_interval; static double bytes_received_load1 = 0; static double bytes_received_load5 = 0; static double bytes_received_load15 = 0; static double bytes_sent_load1 = 0; static double bytes_sent_load5 = 0; static double bytes_sent_load15 = 0; double bytes_received_interval, bytes_sent_interval; static double socket_load1 = 0; static double socket_load5 = 0; static double socket_load15 = 0; double socket_interval; static double connection_load1 = 0; static double connection_load5 = 0; static double connection_load15 = 0; double connection_interval; double exponent; double i_mult; now = mosquitto_time(); if(interval && now - interval > last_update){ uptime = now - start_time; snprintf(buf, BUFLEN, "%d seconds", (int)uptime); db__messages_easy_queue(db, NULL, "$SYS/broker/uptime", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); sys_tree__update_clients(db, buf); bool initial_publish = false; if(last_update == 0){ initial_publish = true; last_update = 1; } if(last_update > 0){ i_mult = 60.0/(double)(now-last_update); msgs_received_interval = (g_msgs_received - msgs_received)*i_mult; msgs_sent_interval = (g_msgs_sent - msgs_sent)*i_mult; publish_dropped_interval = (g_msgs_dropped - publish_dropped)*i_mult; publish_received_interval = (g_pub_msgs_received - pub_msgs_received)*i_mult; publish_sent_interval = (g_pub_msgs_sent - pub_msgs_sent)*i_mult; bytes_received_interval = (g_bytes_received - bytes_received)*i_mult; bytes_sent_interval = (g_bytes_sent - bytes_sent)*i_mult; socket_interval = g_socket_connections*i_mult; g_socket_connections = 0; connection_interval = g_connection_count*i_mult; g_connection_count = 0; /* 1 minute load */ exponent = exp(-1.0*(now-last_update)/60.0); calc_load(db, buf, "$SYS/broker/load/messages/received/1min", initial_publish, exponent, msgs_received_interval, &msgs_received_load1); calc_load(db, buf, "$SYS/broker/load/messages/sent/1min", initial_publish, exponent, msgs_sent_interval, &msgs_sent_load1); calc_load(db, buf, "$SYS/broker/load/publish/dropped/1min", initial_publish, exponent, publish_dropped_interval, &publish_dropped_load1); calc_load(db, buf, "$SYS/broker/load/publish/received/1min", initial_publish, exponent, publish_received_interval, &publish_received_load1); calc_load(db, buf, "$SYS/broker/load/publish/sent/1min", initial_publish, exponent, publish_sent_interval, &publish_sent_load1); calc_load(db, buf, "$SYS/broker/load/bytes/received/1min", initial_publish, exponent, bytes_received_interval, &bytes_received_load1); calc_load(db, buf, "$SYS/broker/load/bytes/sent/1min", initial_publish, exponent, bytes_sent_interval, &bytes_sent_load1); calc_load(db, buf, "$SYS/broker/load/sockets/1min", initial_publish, exponent, socket_interval, &socket_load1); calc_load(db, buf, "$SYS/broker/load/connections/1min", initial_publish, exponent, connection_interval, &connection_load1); /* 5 minute load */ exponent = exp(-1.0*(now-last_update)/300.0); calc_load(db, buf, "$SYS/broker/load/messages/received/5min", initial_publish, exponent, msgs_received_interval, &msgs_received_load5); calc_load(db, buf, "$SYS/broker/load/messages/sent/5min", initial_publish, exponent, msgs_sent_interval, &msgs_sent_load5); calc_load(db, buf, "$SYS/broker/load/publish/dropped/5min", initial_publish, exponent, publish_dropped_interval, &publish_dropped_load5); calc_load(db, buf, "$SYS/broker/load/publish/received/5min", initial_publish, exponent, publish_received_interval, &publish_received_load5); calc_load(db, buf, "$SYS/broker/load/publish/sent/5min", initial_publish, exponent, publish_sent_interval, &publish_sent_load5); calc_load(db, buf, "$SYS/broker/load/bytes/received/5min", initial_publish, exponent, bytes_received_interval, &bytes_received_load5); calc_load(db, buf, "$SYS/broker/load/bytes/sent/5min", initial_publish, exponent, bytes_sent_interval, &bytes_sent_load5); calc_load(db, buf, "$SYS/broker/load/sockets/5min", initial_publish, exponent, socket_interval, &socket_load5); calc_load(db, buf, "$SYS/broker/load/connections/5min", initial_publish, exponent, connection_interval, &connection_load5); /* 15 minute load */ exponent = exp(-1.0*(now-last_update)/900.0); calc_load(db, buf, "$SYS/broker/load/messages/received/15min", initial_publish, exponent, msgs_received_interval, &msgs_received_load15); calc_load(db, buf, "$SYS/broker/load/messages/sent/15min", initial_publish, exponent, msgs_sent_interval, &msgs_sent_load15); calc_load(db, buf, "$SYS/broker/load/publish/dropped/15min", initial_publish, exponent, publish_dropped_interval, &publish_dropped_load15); calc_load(db, buf, "$SYS/broker/load/publish/received/15min", initial_publish, exponent, publish_received_interval, &publish_received_load15); calc_load(db, buf, "$SYS/broker/load/publish/sent/15min", initial_publish, exponent, publish_sent_interval, &publish_sent_load15); calc_load(db, buf, "$SYS/broker/load/bytes/received/15min", initial_publish, exponent, bytes_received_interval, &bytes_received_load15); calc_load(db, buf, "$SYS/broker/load/bytes/sent/15min", initial_publish, exponent, bytes_sent_interval, &bytes_sent_load15); calc_load(db, buf, "$SYS/broker/load/sockets/15min", initial_publish, exponent, socket_interval, &socket_load15); calc_load(db, buf, "$SYS/broker/load/connections/15min", initial_publish, exponent, connection_interval, &connection_load15); } if(db->msg_store_count != msg_store_count){ msg_store_count = db->msg_store_count; snprintf(buf, BUFLEN, "%d", msg_store_count); db__messages_easy_queue(db, NULL, "$SYS/broker/messages/stored", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); db__messages_easy_queue(db, NULL, "$SYS/broker/store/messages/count", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if (db->msg_store_bytes != msg_store_bytes){ msg_store_bytes = db->msg_store_bytes; snprintf(buf, BUFLEN, "%lu", msg_store_bytes); db__messages_easy_queue(db, NULL, "$SYS/broker/store/messages/bytes", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(db->subscription_count != subscription_count){ subscription_count = db->subscription_count; snprintf(buf, BUFLEN, "%d", subscription_count); db__messages_easy_queue(db, NULL, "$SYS/broker/subscriptions/count", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(db->shared_subscription_count != shared_subscription_count){ shared_subscription_count = db->shared_subscription_count; snprintf(buf, BUFLEN, "%d", shared_subscription_count); db__messages_easy_queue(db, NULL, "$SYS/broker/shared_subscriptions/count", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(db->retained_count != retained_count){ retained_count = db->retained_count; snprintf(buf, BUFLEN, "%d", retained_count); db__messages_easy_queue(db, NULL, "$SYS/broker/retained messages/count", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } #ifdef REAL_WITH_MEMORY_TRACKING sys_tree__update_memory(db, buf); #endif if(msgs_received != g_msgs_received){ msgs_received = g_msgs_received; snprintf(buf, BUFLEN, "%lu", msgs_received); db__messages_easy_queue(db, NULL, "$SYS/broker/messages/received", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(msgs_sent != g_msgs_sent){ msgs_sent = g_msgs_sent; snprintf(buf, BUFLEN, "%lu", msgs_sent); db__messages_easy_queue(db, NULL, "$SYS/broker/messages/sent", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(publish_dropped != g_msgs_dropped){ publish_dropped = g_msgs_dropped; snprintf(buf, BUFLEN, "%lu", publish_dropped); db__messages_easy_queue(db, NULL, "$SYS/broker/publish/messages/dropped", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(pub_msgs_received != g_pub_msgs_received){ pub_msgs_received = g_pub_msgs_received; snprintf(buf, BUFLEN, "%lu", pub_msgs_received); db__messages_easy_queue(db, NULL, "$SYS/broker/publish/messages/received", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(pub_msgs_sent != g_pub_msgs_sent){ pub_msgs_sent = g_pub_msgs_sent; snprintf(buf, BUFLEN, "%lu", pub_msgs_sent); db__messages_easy_queue(db, NULL, "$SYS/broker/publish/messages/sent", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(bytes_received != g_bytes_received){ bytes_received = g_bytes_received; snprintf(buf, BUFLEN, "%llu", bytes_received); db__messages_easy_queue(db, NULL, "$SYS/broker/bytes/received", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(bytes_sent != g_bytes_sent){ bytes_sent = g_bytes_sent; snprintf(buf, BUFLEN, "%llu", bytes_sent); db__messages_easy_queue(db, NULL, "$SYS/broker/bytes/sent", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(pub_bytes_received != g_pub_bytes_received){ pub_bytes_received = g_pub_bytes_received; snprintf(buf, BUFLEN, "%llu", pub_bytes_received); db__messages_easy_queue(db, NULL, "$SYS/broker/publish/bytes/received", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } if(pub_bytes_sent != g_pub_bytes_sent){ pub_bytes_sent = g_pub_bytes_sent; snprintf(buf, BUFLEN, "%llu", pub_bytes_sent); db__messages_easy_queue(db, NULL, "$SYS/broker/publish/bytes/sent", SYS_TREE_QOS, strlen(buf), buf, 1, 60, NULL); } last_update = mosquitto_time(); } } #endif mosquitto-1.6.9/src/logging.c0000664000175000017500000002110213626052637015202 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifndef WIN32 #include #endif #include #ifdef WITH_DLT #include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "misc_mosq.h" #include "util_mosq.h" extern struct mosquitto_db int_db; #ifdef WIN32 HANDLE syslog_h; #endif /* Options for logging should be: * * A combination of: * Via syslog * To a file * To stdout/stderr * To topics */ /* Give option of logging timestamp. * Logging pid. */ static int log_destinations = MQTT3_LOG_STDERR; static int log_priorities = MOSQ_LOG_ERR | MOSQ_LOG_WARNING | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO; #ifdef WITH_DLT static DltContext dltContext; #endif static int get_time(struct tm **ti) { #if defined(__APPLE__) struct timeval tv; #else struct timespec ts; #endif time_t s; #ifdef WIN32 s = time(NULL); #elif defined(__APPLE__) gettimeofday(&tv, NULL); s = tv.tv_sec; #else if(clock_gettime(CLOCK_REALTIME, &ts) != 0){ fprintf(stderr, "Error obtaining system time.\n"); return 1; } s = ts.tv_sec; #endif *ti = localtime(&s); if(!(*ti)){ fprintf(stderr, "Error obtaining system time.\n"); return 1; } return 0; } int log__init(struct mosquitto__config *config) { int rc = 0; log_priorities = config->log_type; log_destinations = config->log_dest; if(log_destinations & MQTT3_LOG_SYSLOG){ #ifndef WIN32 openlog("mosquitto", LOG_PID|LOG_CONS, config->log_facility); #else syslog_h = OpenEventLog(NULL, "mosquitto"); #endif } if(log_destinations & MQTT3_LOG_FILE){ if(drop_privileges(config, true)){ return 1; } config->log_fptr = mosquitto__fopen(config->log_file, "at", true); if(!config->log_fptr){ log_destinations = MQTT3_LOG_STDERR; log_priorities = MOSQ_LOG_ERR; log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open log file %s for writing.", config->log_file); return MOSQ_ERR_INVAL; } restore_privileges(); } #ifdef WITH_DLT DLT_REGISTER_APP("MQTT","mosquitto log"); dlt_register_context(&dltContext, "MQTT", "mosquitto DLT context"); #endif return rc; } int log__close(struct mosquitto__config *config) { if(log_destinations & MQTT3_LOG_SYSLOG){ #ifndef WIN32 closelog(); #else CloseEventLog(syslog_h); #endif } if(log_destinations & MQTT3_LOG_FILE){ if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } } #ifdef WITH_DLT dlt_unregister_context(&dltContext); DLT_UNREGISTER_APP(); #endif /* FIXME - do something for all destinations! */ return MOSQ_ERR_SUCCESS; } #ifdef WITH_DLT DltLogLevelType get_dlt_level(int priority) { switch (priority) { case MOSQ_LOG_ERR: return DLT_LOG_ERROR; case MOSQ_LOG_WARNING: return DLT_LOG_WARN; case MOSQ_LOG_INFO: return DLT_LOG_INFO; case MOSQ_LOG_DEBUG: return DLT_LOG_DEBUG; case MOSQ_LOG_NOTICE: case MOSQ_LOG_SUBSCRIBE: case MOSQ_LOG_UNSUBSCRIBE: return DLT_LOG_VERBOSE; default: return DLT_LOG_DEFAULT; } } #endif int log__vprintf(int priority, const char *fmt, va_list va) { char *s; char *st; int len; #ifdef WIN32 char *sp; #endif const char *topic; int syslog_priority; time_t now = time(NULL); static time_t last_flush = 0; char time_buf[50]; bool log_timestamp = true; char *log_timestamp_format = NULL; FILE *log_fptr = NULL; if(int_db.config){ log_timestamp = int_db.config->log_timestamp; log_timestamp_format = int_db.config->log_timestamp_format; log_fptr = int_db.config->log_fptr; } if((log_priorities & priority) && log_destinations != MQTT3_LOG_NONE){ switch(priority){ case MOSQ_LOG_SUBSCRIBE: topic = "$SYS/broker/log/M/subscribe"; #ifndef WIN32 syslog_priority = LOG_NOTICE; #else syslog_priority = EVENTLOG_INFORMATION_TYPE; #endif break; case MOSQ_LOG_UNSUBSCRIBE: topic = "$SYS/broker/log/M/unsubscribe"; #ifndef WIN32 syslog_priority = LOG_NOTICE; #else syslog_priority = EVENTLOG_INFORMATION_TYPE; #endif break; case MOSQ_LOG_DEBUG: topic = "$SYS/broker/log/D"; #ifndef WIN32 syslog_priority = LOG_DEBUG; #else syslog_priority = EVENTLOG_INFORMATION_TYPE; #endif break; case MOSQ_LOG_ERR: topic = "$SYS/broker/log/E"; #ifndef WIN32 syslog_priority = LOG_ERR; #else syslog_priority = EVENTLOG_ERROR_TYPE; #endif break; case MOSQ_LOG_WARNING: topic = "$SYS/broker/log/W"; #ifndef WIN32 syslog_priority = LOG_WARNING; #else syslog_priority = EVENTLOG_WARNING_TYPE; #endif break; case MOSQ_LOG_NOTICE: topic = "$SYS/broker/log/N"; #ifndef WIN32 syslog_priority = LOG_NOTICE; #else syslog_priority = EVENTLOG_INFORMATION_TYPE; #endif break; case MOSQ_LOG_INFO: topic = "$SYS/broker/log/I"; #ifndef WIN32 syslog_priority = LOG_INFO; #else syslog_priority = EVENTLOG_INFORMATION_TYPE; #endif break; #ifdef WITH_WEBSOCKETS case MOSQ_LOG_WEBSOCKETS: topic = "$SYS/broker/log/WS"; #ifndef WIN32 syslog_priority = LOG_DEBUG; #else syslog_priority = EVENTLOG_INFORMATION_TYPE; #endif break; #endif default: topic = "$SYS/broker/log/E"; #ifndef WIN32 syslog_priority = LOG_ERR; #else syslog_priority = EVENTLOG_ERROR_TYPE; #endif } len = strlen(fmt) + 500; s = mosquitto__malloc(len*sizeof(char)); if(!s) return MOSQ_ERR_NOMEM; vsnprintf(s, len, fmt, va); s[len-1] = '\0'; /* Ensure string is null terminated. */ if(log_timestamp && log_timestamp_format){ struct tm *ti = NULL; get_time(&ti); if(strftime(time_buf, 50, log_timestamp_format, ti) == 0){ snprintf(time_buf, 50, "Time error"); } } if(log_destinations & MQTT3_LOG_STDOUT){ if(log_timestamp){ if(log_timestamp_format){ fprintf(stdout, "%s: %s\n", time_buf, s); }else{ fprintf(stdout, "%d: %s\n", (int)now, s); } }else{ fprintf(stdout, "%s\n", s); } fflush(stdout); } if(log_destinations & MQTT3_LOG_STDERR){ if(log_timestamp){ if(log_timestamp_format){ fprintf(stderr, "%s: %s\n", time_buf, s); }else{ fprintf(stderr, "%d: %s\n", (int)now, s); } }else{ fprintf(stderr, "%s\n", s); } fflush(stderr); } if(log_destinations & MQTT3_LOG_FILE && log_fptr){ if(log_timestamp){ if(log_timestamp_format){ fprintf(log_fptr, "%s: %s\n", time_buf, s); }else{ fprintf(log_fptr, "%d: %s\n", (int)now, s); } }else{ fprintf(log_fptr, "%s\n", s); } if(now - last_flush > 1){ fflush(log_fptr); last_flush = now; } } if(log_destinations & MQTT3_LOG_SYSLOG){ #ifndef WIN32 syslog(syslog_priority, "%s", s); #else sp = (char *)s; ReportEvent(syslog_h, syslog_priority, 0, 0, NULL, 1, 0, &sp, NULL); #endif } if(log_destinations & MQTT3_LOG_TOPIC && priority != MOSQ_LOG_DEBUG && priority != MOSQ_LOG_INTERNAL){ if(log_timestamp){ len += 30; st = mosquitto__malloc(len*sizeof(char)); if(!st){ mosquitto__free(s); return MOSQ_ERR_NOMEM; } snprintf(st, len, "%d: %s", (int)now, s); db__messages_easy_queue(&int_db, NULL, topic, 2, strlen(st), st, 0, 20, NULL); mosquitto__free(st); }else{ db__messages_easy_queue(&int_db, NULL, topic, 2, strlen(s), s, 0, 20, NULL); } } #ifdef WITH_DLT if(priority != MOSQ_LOG_INTERNAL){ DLT_LOG_STRING(dltContext, get_dlt_level(priority), s); } #endif mosquitto__free(s); } return MOSQ_ERR_SUCCESS; } int log__printf(struct mosquitto *mosq, int priority, const char *fmt, ...) { va_list va; int rc; UNUSED(mosq); va_start(va, fmt); rc = log__vprintf(priority, fmt, va); va_end(va); return rc; } void log__internal(const char *fmt, ...) { va_list va; char buf[200]; int len; va_start(va, fmt); len = vsnprintf(buf, 200, fmt, va); va_end(va); if(len >= 200){ log__printf(NULL, MOSQ_LOG_INTERNAL, "Internal log buffer too short (%d)", len); return; } log__printf(NULL, MOSQ_LOG_INTERNAL, "%s%s%s", "\e[32m", buf, "\e[0m"); } int mosquitto_log_vprintf(int level, const char *fmt, va_list va) { return log__vprintf(level, fmt, va); } void mosquitto_log_printf(int level, const char *fmt, ...) { va_list va; va_start(va, fmt); log__vprintf(level, fmt, va); va_end(va); } mosquitto-1.6.9/src/handle_publish.c0000664000175000017500000002366513626052637016555 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #include "alias_mosq.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "sys_tree.h" #include "util_mosq.h" int handle__publish(struct mosquitto_db *db, struct mosquitto *context) { char *topic; mosquitto__payload_uhpa payload; uint32_t payloadlen; uint8_t dup, qos, retain; uint16_t mid = 0; int rc = 0; int rc2; uint8_t header = context->in_packet.command; int res = 0; struct mosquitto_msg_store *stored = NULL; int len; int slen; char *topic_mount; mosquitto_property *properties = NULL; mosquitto_property *p, *p_prev; mosquitto_property *msg_properties = NULL, *msg_properties_last; uint32_t message_expiry_interval = 0; int topic_alias = -1; uint8_t reason_code = 0; #ifdef WITH_BRIDGE char *topic_temp; int i; struct mosquitto__bridge_topic *cur_topic; bool match; #endif if(context->state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } payload.ptr = NULL; dup = (header & 0x08)>>3; qos = (header & 0x06)>>1; if(qos == 3){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid QoS in PUBLISH from %s, disconnecting.", context->id); return 1; } if(qos > context->maximum_qos){ log__printf(NULL, MOSQ_LOG_INFO, "Too high QoS in PUBLISH from %s, disconnecting.", context->id); return 1; } retain = (header & 0x01); if(retain && db->config->retain_available == false){ if(context->protocol == mosq_p_mqtt5){ send__disconnect(context, MQTT_RC_RETAIN_NOT_SUPPORTED, NULL); } return 1; } if(packet__read_string(&context->in_packet, &topic, &slen)) return 1; if(!slen && context->protocol != mosq_p_mqtt5){ /* Invalid publish topic, disconnect client. */ mosquitto__free(topic); return 1; } if(qos > 0){ if(packet__read_uint16(&context->in_packet, &mid)){ mosquitto__free(topic); return 1; } if(mid == 0){ mosquitto__free(topic); return MOSQ_ERR_PROTOCOL; } } /* Handle properties */ if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_PUBLISH, &context->in_packet, &properties); if(rc) return rc; p = properties; p_prev = NULL; msg_properties = NULL; msg_properties_last = NULL; while(p){ switch(p->identifier){ case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_CORRELATION_DATA: case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_USER_PROPERTY: if(msg_properties){ msg_properties_last->next = p; msg_properties_last = p; }else{ msg_properties = p; msg_properties_last = p; } if(p_prev){ p_prev->next = p->next; p = p_prev->next; }else{ properties = p->next; p = properties; } msg_properties_last->next = NULL; break; case MQTT_PROP_TOPIC_ALIAS: topic_alias = p->value.i16; p_prev = p; p = p->next; break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: message_expiry_interval = p->value.i32; p_prev = p; p = p->next; break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: p_prev = p; p = p->next; break; default: p = p->next; break; } } } mosquitto_property_free_all(&properties); if(topic_alias == 0 || (context->listener && topic_alias > context->listener->max_topic_alias)){ mosquitto__free(topic); send__disconnect(context, MQTT_RC_TOPIC_ALIAS_INVALID, NULL); return MOSQ_ERR_PROTOCOL; }else if(topic_alias > 0){ if(topic){ rc = alias__add(context, topic, topic_alias); if(rc){ mosquitto__free(topic); return rc; } }else{ rc = alias__find(context, &topic, topic_alias); if(rc){ send__disconnect(context, MQTT_RC_TOPIC_ALIAS_INVALID, NULL); mosquitto__free(topic); return rc; } } } if(mosquitto_validate_utf8(topic, slen) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_INFO, "Client %s sent topic with invalid UTF-8, disconnecting.", context->id); mosquitto__free(topic); return 1; } #ifdef WITH_BRIDGE if(context->bridge && context->bridge->topics && context->bridge->topic_remapping){ for(i=0; ibridge->topic_count; i++){ cur_topic = &context->bridge->topics[i]; if((cur_topic->direction == bd_both || cur_topic->direction == bd_in) && (cur_topic->remote_prefix || cur_topic->local_prefix)){ /* Topic mapping required on this topic if the message matches */ rc = mosquitto_topic_matches_sub(cur_topic->remote_topic, topic, &match); if(rc){ mosquitto__free(topic); return rc; } if(match){ if(cur_topic->remote_prefix){ /* This prefix needs removing. */ if(!strncmp(cur_topic->remote_prefix, topic, strlen(cur_topic->remote_prefix))){ topic_temp = mosquitto__strdup(topic+strlen(cur_topic->remote_prefix)); if(!topic_temp){ mosquitto__free(topic); return MOSQ_ERR_NOMEM; } mosquitto__free(topic); topic = topic_temp; } } if(cur_topic->local_prefix){ /* This prefix needs adding. */ len = strlen(topic) + strlen(cur_topic->local_prefix)+1; topic_temp = mosquitto__malloc(len+1); if(!topic_temp){ mosquitto__free(topic); return MOSQ_ERR_NOMEM; } snprintf(topic_temp, len, "%s%s", cur_topic->local_prefix, topic); topic_temp[len] = '\0'; mosquitto__free(topic); topic = topic_temp; } break; } } } } #endif if(mosquitto_pub_topic_check(topic) != MOSQ_ERR_SUCCESS){ /* Invalid publish topic, just swallow it. */ mosquitto__free(topic); return 1; } payloadlen = context->in_packet.remaining_length - context->in_packet.pos; G_PUB_BYTES_RECEIVED_INC(payloadlen); if(context->listener && context->listener->mount_point){ len = strlen(context->listener->mount_point) + strlen(topic) + 1; topic_mount = mosquitto__malloc(len+1); if(!topic_mount){ mosquitto__free(topic); mosquitto_property_free_all(&msg_properties); return MOSQ_ERR_NOMEM; } snprintf(topic_mount, len, "%s%s", context->listener->mount_point, topic); topic_mount[len] = '\0'; mosquitto__free(topic); topic = topic_mount; } if(payloadlen){ if(db->config->message_size_limit && payloadlen > db->config->message_size_limit){ log__printf(NULL, MOSQ_LOG_DEBUG, "Dropped too large PUBLISH from %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", context->id, dup, qos, retain, mid, topic, (long)payloadlen); reason_code = MQTT_RC_IMPLEMENTATION_SPECIFIC; goto process_bad_message; } if(UHPA_ALLOC(payload, payloadlen) == 0){ mosquitto__free(topic); mosquitto_property_free_all(&msg_properties); return MOSQ_ERR_NOMEM; } if(packet__read_bytes(&context->in_packet, UHPA_ACCESS(payload, payloadlen), payloadlen)){ mosquitto__free(topic); UHPA_FREE(payload, payloadlen); mosquitto_property_free_all(&msg_properties); return 1; } } /* Check for topic access */ rc = mosquitto_acl_check(db, context, topic, payloadlen, UHPA_ACCESS(payload, payloadlen), qos, retain, MOSQ_ACL_WRITE); if(rc == MOSQ_ERR_ACL_DENIED){ log__printf(NULL, MOSQ_LOG_DEBUG, "Denied PUBLISH from %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", context->id, dup, qos, retain, mid, topic, (long)payloadlen); reason_code = MQTT_RC_NOT_AUTHORIZED; goto process_bad_message; }else if(rc != MOSQ_ERR_SUCCESS){ mosquitto__free(topic); UHPA_FREE(payload, payloadlen); mosquitto_property_free_all(&msg_properties); return rc; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received PUBLISH from %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", context->id, dup, qos, retain, mid, topic, (long)payloadlen); if(qos > 0){ db__message_store_find(context, mid, &stored); } if(!stored){ dup = 0; if(db__message_store(db, context, mid, topic, qos, payloadlen, &payload, retain, &stored, message_expiry_interval, msg_properties, 0, mosq_mo_client)){ mosquitto_property_free_all(&msg_properties); return 1; } msg_properties = NULL; /* Now belongs to db__message_store() */ }else{ mosquitto__free(topic); topic = stored->topic; dup = 1; mosquitto_property_free_all(&msg_properties); UHPA_FREE(payload, payloadlen); } switch(qos){ case 0: rc2 = sub__messages_queue(db, context->id, topic, qos, retain, &stored); if(rc2 > 0) rc = 1; break; case 1: util__decrement_receive_quota(context); rc2 = sub__messages_queue(db, context->id, topic, qos, retain, &stored); if(rc2 == MOSQ_ERR_SUCCESS || context->protocol != mosq_p_mqtt5){ if(send__puback(context, mid, 0)) rc = 1; }else if(rc2 == MOSQ_ERR_NO_SUBSCRIBERS){ if(send__puback(context, mid, MQTT_RC_NO_MATCHING_SUBSCRIBERS)) rc = 1; }else{ rc = rc2; } break; case 2: if(dup == 0){ res = db__message_insert(db, context, mid, mosq_md_in, qos, retain, stored, NULL); }else{ res = 0; } /* db__message_insert() returns 2 to indicate dropped message * due to queue. This isn't an error so don't disconnect them. */ if(!res){ if(send__pubrec(context, mid, 0)) rc = 1; }else if(res == 1){ rc = 1; } break; } return rc; process_bad_message: mosquitto__free(topic); UHPA_FREE(payload, payloadlen); switch(qos){ case 0: return MOSQ_ERR_SUCCESS; case 1: return send__puback(context, mid, reason_code); case 2: if(context->protocol == mosq_p_mqtt5){ return send__pubrec(context, mid, reason_code); }else{ return send__pubrec(context, mid, 0); } } return 1; } mosquitto-1.6.9/src/persist.h0000664000175000017500000001077713626052637015272 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef PERSIST_H #define PERSIST_H #define MOSQ_DB_VERSION 5 /* DB read/write */ extern const unsigned char magic[15]; #define DB_CHUNK_CFG 1 #define DB_CHUNK_MSG_STORE 2 #define DB_CHUNK_CLIENT_MSG 3 #define DB_CHUNK_RETAIN 4 #define DB_CHUNK_SUB 5 #define DB_CHUNK_CLIENT 6 /* End DB read/write */ #define read_e(f, b, c) if(fread(b, 1, c, f) != c){ goto error; } #define write_e(f, b, c) if(fwrite(b, 1, c, f) != c){ goto error; } /* COMPATIBILITY NOTES * * The P_* structs (persist structs) contain all of the data for a particular * data chunk. They are loaded in multiple parts, so can be rearranged without * updating the db format version. * * The PF_* structs (persist fixed structs) contain the fixed size data for a * particular data chunk. They are written to disk as is, so they must not be * rearranged without updating the db format version. When adding new members, * always use explicit sized datatypes ("uint32_t", not "long"), and check * whether what is being added can go in an existing hole in the struct. */ struct PF_header{ uint32_t chunk; uint32_t length; }; struct PF_cfg{ uint64_t last_db_id; uint8_t shutdown; uint8_t dbid_size; }; struct PF_client{ int64_t session_expiry_time; uint32_t session_expiry_interval; uint16_t last_mid; uint16_t id_len; }; struct P_client{ struct PF_client F; char *client_id; }; struct PF_client_msg{ dbid_t store_id; uint16_t mid; uint16_t id_len; uint8_t qos; uint8_t state; uint8_t retain_dup; uint8_t direction; }; struct P_client_msg{ struct PF_client_msg F; char *client_id; mosquitto_property *properties; }; struct PF_msg_store{ dbid_t store_id; int64_t expiry_time; uint32_t payloadlen; uint16_t source_mid; uint16_t source_id_len; uint16_t source_username_len; uint16_t topic_len; uint16_t source_port; uint8_t qos; uint8_t retain; }; struct P_msg_store{ struct PF_msg_store F; mosquitto__payload_uhpa payload; struct mosquitto source; char *topic; mosquitto_property *properties; }; struct PF_sub{ uint32_t identifier; uint16_t id_len; uint16_t topic_len; uint8_t qos; uint8_t options; }; struct P_sub{ struct PF_sub F; char *client_id; char *topic; }; struct PF_retain{ dbid_t store_id; }; struct P_retain{ struct PF_retain F; }; int persist__read_string_len(FILE *db_fptr, char **str, uint16_t len); int persist__read_string(FILE *db_fptr, char **str); int persist__chunk_header_read(FILE *db_fptr, int *chunk, int *length); int persist__chunk_header_read_v234(FILE *db_fptr, int *chunk, int *length); int persist__chunk_cfg_read_v234(FILE *db_fptr, struct PF_cfg *chunk); int persist__chunk_client_read_v234(FILE *db_fptr, struct P_client *chunk, int db_version); int persist__chunk_client_msg_read_v234(FILE *db_fptr, struct P_client_msg *chunk); int persist__chunk_msg_store_read_v234(FILE *db_fptr, struct P_msg_store *chunk, int db_version); int persist__chunk_retain_read_v234(FILE *db_fptr, struct P_retain *chunk); int persist__chunk_sub_read_v234(FILE *db_fptr, struct P_sub *chunk); int persist__chunk_header_read_v5(FILE *db_fptr, int *chunk, int *length); int persist__chunk_cfg_read_v5(FILE *db_fptr, struct PF_cfg *chunk); int persist__chunk_client_read_v5(FILE *db_fptr, struct P_client *chunk); int persist__chunk_client_msg_read_v5(FILE *db_fptr, struct P_client_msg *chunk, uint32_t length); int persist__chunk_msg_store_read_v5(FILE *db_fptr, struct P_msg_store *chunk, uint32_t length); int persist__chunk_retain_read_v5(FILE *db_fptr, struct P_retain *chunk); int persist__chunk_sub_read_v5(FILE *db_fptr, struct P_sub *chunk); int persist__chunk_cfg_write_v5(FILE *db_fptr, struct PF_cfg *chunk); int persist__chunk_client_write_v5(FILE *db_fptr, struct P_client *chunk); int persist__chunk_client_msg_write_v5(FILE *db_fptr, struct P_client_msg *chunk); int persist__chunk_message_store_write_v5(FILE *db_fptr, struct P_msg_store *chunk); int persist__chunk_retain_write_v5(FILE *db_fptr, struct P_retain *chunk); int persist__chunk_sub_write_v5(FILE *db_fptr, struct P_sub *chunk); #endif mosquitto-1.6.9/src/net.c0000664000175000017500000005074313626052637014357 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifndef WIN32 #include #include #include #include #include #include #else #include #include #endif #include #include #include #include #include #ifdef WITH_WRAP #include #endif #ifdef HAVE_NETINET_IN_H # include #endif #ifdef __QNX__ #include #endif #include "mosquitto_broker_internal.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "net_mosq.h" #include "util_mosq.h" #ifdef WITH_TLS #include "tls_mosq.h" #include static int tls_ex_index_context = -1; static int tls_ex_index_listener = -1; #endif #include "sys_tree.h" /* For EMFILE handling */ static mosq_sock_t spare_sock = INVALID_SOCKET; void net__broker_init(void) { spare_sock = socket(AF_INET, SOCK_STREAM, 0); net__init(); } void net__broker_cleanup(void) { if(spare_sock != INVALID_SOCKET){ COMPAT_CLOSE(spare_sock); spare_sock = INVALID_SOCKET; } net__cleanup(); } static void net__print_error(int log, const char *format_str) { char *buf; #ifdef WIN32 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), LANG_NEUTRAL, &buf, 0, NULL); log__printf(NULL, log, format_str, buf); LocalFree(buf); #else buf = strerror(errno); log__printf(NULL, log, format_str, buf); #endif } int net__socket_accept(struct mosquitto_db *db, mosq_sock_t listensock) { int i; int j; mosq_sock_t new_sock = INVALID_SOCKET; struct mosquitto *new_context; #ifdef WITH_TLS BIO *bio; int rc; char ebuf[256]; unsigned long e; #endif #ifdef WITH_WRAP struct request_info wrap_req; char address[1024]; #endif new_sock = accept(listensock, NULL, 0); if(new_sock == INVALID_SOCKET){ #ifdef WIN32 errno = WSAGetLastError(); if(errno == WSAEMFILE){ #else if(errno == EMFILE || errno == ENFILE){ #endif /* Close the spare socket, which means we should be able to accept * this connection. Accept it, then close it immediately and create * a new spare_sock. This prevents the situation of ever properly * running out of sockets. * It would be nice to send a "server not available" connack here, * but there are lots of reasons why this would be tricky (TLS * being the big one). */ COMPAT_CLOSE(spare_sock); new_sock = accept(listensock, NULL, 0); if(new_sock != INVALID_SOCKET){ COMPAT_CLOSE(new_sock); } spare_sock = socket(AF_INET, SOCK_STREAM, 0); log__printf(NULL, MOSQ_LOG_WARNING, "Unable to accept new connection, system socket count has been exceeded. Try increasing \"ulimit -n\" or equivalent."); } return -1; } G_SOCKET_CONNECTIONS_INC(); if(net__socket_nonblock(&new_sock)){ return INVALID_SOCKET; } #ifdef WITH_WRAP /* Use tcpd / libwrap to determine whether a connection is allowed. */ request_init(&wrap_req, RQ_FILE, new_sock, RQ_DAEMON, "mosquitto", 0); fromhost(&wrap_req); if(!hosts_access(&wrap_req)){ /* Access is denied */ if(db->config->connection_messages == true){ if(!net__socket_get_address(new_sock, address, 1024)){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client connection from %s denied access by tcpd.", address); } } COMPAT_CLOSE(new_sock); return -1; } #endif if(db->config->set_tcp_nodelay){ int flag = 1; if(setsockopt(new_sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int)) != 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unable to set TCP_NODELAY."); } } new_context = context__init(db, new_sock); if(!new_context){ COMPAT_CLOSE(new_sock); return -1; } for(i=0; iconfig->listener_count; i++){ for(j=0; jconfig->listeners[i].sock_count; j++){ if(db->config->listeners[i].socks[j] == listensock){ new_context->listener = &db->config->listeners[i]; new_context->listener->client_count++; break; } } } if(!new_context->listener){ context__cleanup(db, new_context, true); return -1; } if(new_context->listener->max_connections > 0 && new_context->listener->client_count > new_context->listener->max_connections){ if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client connection from %s denied: max_connections exceeded.", new_context->address); } context__cleanup(db, new_context, true); return -1; } #ifdef WITH_TLS /* TLS init */ for(i=0; iconfig->listener_count; i++){ for(j=0; jconfig->listeners[i].sock_count; j++){ if(db->config->listeners[i].socks[j] == listensock){ if(db->config->listeners[i].ssl_ctx){ new_context->ssl = SSL_new(db->config->listeners[i].ssl_ctx); if(!new_context->ssl){ context__cleanup(db, new_context, true); return -1; } SSL_set_ex_data(new_context->ssl, tls_ex_index_context, new_context); SSL_set_ex_data(new_context->ssl, tls_ex_index_listener, &db->config->listeners[i]); new_context->want_write = true; bio = BIO_new_socket(new_sock, BIO_NOCLOSE); SSL_set_bio(new_context->ssl, bio, bio); ERR_clear_error(); rc = SSL_accept(new_context->ssl); if(rc != 1){ rc = SSL_get_error(new_context->ssl, rc); if(rc == SSL_ERROR_WANT_READ){ /* We always want to read. */ }else if(rc == SSL_ERROR_WANT_WRITE){ new_context->want_write = true; }else{ if(db->config->connection_messages == true){ e = ERR_get_error(); while(e){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client connection from %s failed: %s.", new_context->address, ERR_error_string(e, ebuf)); e = ERR_get_error(); } } context__cleanup(db, new_context, true); return -1; } } } } } } #endif if(db->config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_NOTICE, "New connection from %s on port %d.", new_context->address, new_context->listener->port); } return new_sock; } #ifdef WITH_TLS static int client_certificate_verify(int preverify_ok, X509_STORE_CTX *ctx) { UNUSED(ctx); /* Preverify should check expiry, revocation. */ return preverify_ok; } #endif #ifdef FINAL_WITH_TLS_PSK static unsigned int psk_server_callback(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) { struct mosquitto_db *db; struct mosquitto *context; struct mosquitto__listener *listener; char *psk_key = NULL; int len; const char *psk_hint; if(!identity) return 0; db = mosquitto__get_db(); context = SSL_get_ex_data(ssl, tls_ex_index_context); if(!context) return 0; listener = SSL_get_ex_data(ssl, tls_ex_index_listener); if(!listener) return 0; psk_hint = listener->psk_hint; /* The hex to BN conversion results in the length halving, so we can pass * max_psk_len*2 as the max hex key here. */ psk_key = mosquitto__calloc(1, max_psk_len*2 + 1); if(!psk_key) return 0; if(mosquitto_psk_key_get(db, context, psk_hint, identity, psk_key, max_psk_len*2) != MOSQ_ERR_SUCCESS){ mosquitto__free(psk_key); return 0; } len = mosquitto__hex2bin(psk_key, psk, max_psk_len); if (len < 0){ mosquitto__free(psk_key); return 0; } if(listener->use_identity_as_username){ context->username = mosquitto__strdup(identity); if(!context->username){ mosquitto__free(psk_key); return 0; } } mosquitto__free(psk_key); return len; } #endif #ifdef WITH_TLS int net__tls_server_ctx(struct mosquitto__listener *listener) { char buf[256]; int rc; FILE *dhparamfile; DH *dhparam = NULL; if(listener->ssl_ctx){ SSL_CTX_free(listener->ssl_ctx); } #if OPENSSL_VERSION_NUMBER < 0x10100000L listener->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); #else listener->ssl_ctx = SSL_CTX_new(TLS_server_method()); #endif if(!listener->ssl_ctx){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to create TLS context."); return 1; } if(listener->tls_version == NULL){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1); #ifdef SSL_OP_NO_TLSv1_3 }else if(!strcmp(listener->tls_version, "tlsv1.3")){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2); }else if(!strcmp(listener->tls_version, "tlsv1.2")){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_3); }else if(!strcmp(listener->tls_version, "tlsv1.1")){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3); #else }else if(!strcmp(listener->tls_version, "tlsv1.2")){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); }else if(!strcmp(listener->tls_version, "tlsv1.1")){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_2); #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unsupported tls_version \"%s\".", listener->tls_version); return 1; } #ifdef SSL_OP_NO_COMPRESSION /* Disable compression */ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_COMPRESSION); #endif #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE /* Server chooses cipher */ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif #ifdef SSL_MODE_RELEASE_BUFFERS /* Use even less memory per SSL connection. */ SSL_CTX_set_mode(listener->ssl_ctx, SSL_MODE_RELEASE_BUFFERS); #endif #ifdef WITH_EC #if OPENSSL_VERSION_NUMBER >= 0x10002000L && OPENSSL_VERSION_NUMBER < 0x10100000L SSL_CTX_set_ecdh_auto(listener->ssl_ctx, 1); #endif #endif #ifdef SSL_OP_NO_RENEGOTIATION SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_RENEGOTIATION); #endif snprintf(buf, 256, "mosquitto-%d", listener->port); SSL_CTX_set_session_id_context(listener->ssl_ctx, (unsigned char *)buf, strlen(buf)); if(listener->ciphers){ rc = SSL_CTX_set_cipher_list(listener->ssl_ctx, listener->ciphers); if(rc == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to set TLS ciphers. Check cipher list \"%s\".", listener->ciphers); return 1; } }else{ rc = SSL_CTX_set_cipher_list(listener->ssl_ctx, "DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH"); if(rc == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to set TLS ciphers. Check cipher list \"%s\".", listener->ciphers); return 1; } } if(listener->dhparamfile){ dhparamfile = fopen(listener->dhparamfile, "r"); if(!dhparamfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error loading dhparamfile \"%s\".", listener->dhparamfile); return 1; } dhparam = PEM_read_DHparams(dhparamfile, NULL, NULL, NULL); fclose(dhparamfile); if(dhparam == NULL || SSL_CTX_set_tmp_dh(listener->ssl_ctx, dhparam) != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error loading dhparamfile \"%s\".", listener->dhparamfile); net__print_ssl_error(NULL); return 1; } } return MOSQ_ERR_SUCCESS; } #endif int net__load_crl_file(struct mosquitto__listener *listener) { #ifdef WITH_TLS X509_STORE *store; X509_LOOKUP *lookup; int rc; store = SSL_CTX_get_cert_store(listener->ssl_ctx); if(!store){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to obtain TLS store."); net__print_error(MOSQ_LOG_ERR, "Error: %s"); return 1; } lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); rc = X509_load_crl_file(lookup, listener->crlfile, X509_FILETYPE_PEM); if(rc < 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load certificate revocation file \"%s\". Check crlfile.", listener->crlfile); net__print_error(MOSQ_LOG_ERR, "Error: %s"); net__print_ssl_error(NULL); return 1; } X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK); #endif return MOSQ_ERR_SUCCESS; } int net__tls_load_verify(struct mosquitto__listener *listener) { #ifdef WITH_TLS ENGINE *engine = NULL; int rc; rc = SSL_CTX_load_verify_locations(listener->ssl_ctx, listener->cafile, listener->capath); if(rc == 0){ if(listener->cafile && listener->capath){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load CA certificates. Check cafile \"%s\" and capath \"%s\".", listener->cafile, listener->capath); }else if(listener->cafile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load CA certificates. Check cafile \"%s\".", listener->cafile); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load CA certificates. Check capath \"%s\".", listener->capath); } net__print_ssl_error(NULL); return 1; } if(listener->tls_engine){ #if !defined(OPENSSL_NO_ENGINE) engine = ENGINE_by_id(listener->tls_engine); if(!engine){ log__printf(NULL, MOSQ_LOG_ERR, "Error loading %s engine\n", listener->tls_engine); net__print_ssl_error(NULL); return 1; } if(!ENGINE_init(engine)){ log__printf(NULL, MOSQ_LOG_ERR, "Failed engine initialisation\n"); net__print_ssl_error(NULL); ENGINE_free(engine); return 1; } ENGINE_set_default(engine, ENGINE_METHOD_ALL); ENGINE_free(engine); /* release the structural reference from ENGINE_by_id() */ #endif } /* FIXME user data? */ if(listener->require_certificate){ SSL_CTX_set_verify(listener->ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, client_certificate_verify); }else{ SSL_CTX_set_verify(listener->ssl_ctx, SSL_VERIFY_NONE, client_certificate_verify); } rc = SSL_CTX_use_certificate_chain_file(listener->ssl_ctx, listener->certfile); if(rc != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load server certificate \"%s\". Check certfile.", listener->certfile); net__print_ssl_error(NULL); #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif return 1; } if(listener->tls_engine && listener->tls_keyform == mosq_k_engine){ #if !defined(OPENSSL_NO_ENGINE) UI_METHOD *ui_method = net__get_ui_method(); if(listener->tls_engine_kpass_sha1){ if(!ENGINE_ctrl_cmd(engine, ENGINE_SECRET_MODE, ENGINE_SECRET_MODE_SHA, NULL, NULL, 0)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to set engine secret mode sha"); net__print_ssl_error(NULL); ENGINE_FINISH(engine); return 1; } if(!ENGINE_ctrl_cmd(engine, ENGINE_PIN, 0, listener->tls_engine_kpass_sha1, NULL, 0)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to set engine pin"); net__print_ssl_error(NULL); ENGINE_FINISH(engine); return 1; } ui_method = NULL; } EVP_PKEY *pkey = ENGINE_load_private_key(engine, listener->keyfile, ui_method, NULL); if(!pkey){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load engine private key file \"%s\".", listener->keyfile); net__print_ssl_error(NULL); ENGINE_FINISH(engine); return 1; } if(SSL_CTX_use_PrivateKey(listener->ssl_ctx, pkey) <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to use engine private key file \"%s\".", listener->keyfile); net__print_ssl_error(NULL); ENGINE_FINISH(engine); return 1; } #endif }else{ rc = SSL_CTX_use_PrivateKey_file(listener->ssl_ctx, listener->keyfile, SSL_FILETYPE_PEM); if(rc != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load server key file \"%s\". Check keyfile.", listener->keyfile); #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif return 1; } } rc = SSL_CTX_check_private_key(listener->ssl_ctx); if(rc != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Server certificate/key are inconsistent."); net__print_ssl_error(NULL); #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif return 1; } /* Load CRLs if they exist. */ if(listener->crlfile){ rc = net__load_crl_file(listener); if(rc){ #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif return rc; } } #endif return MOSQ_ERR_SUCCESS; } /* Creates a socket and listens on port 'port'. * Returns 1 on failure * Returns 0 on success. */ int net__socket_listen(struct mosquitto__listener *listener) { mosq_sock_t sock = INVALID_SOCKET; struct addrinfo hints; struct addrinfo *ainfo, *rp; char service[10]; int rc; #ifndef WIN32 int ss_opt = 1; #else char ss_opt = 1; #endif #ifdef SO_BINDTODEVICE struct ifreq ifr; #endif if(!listener) return MOSQ_ERR_INVAL; snprintf(service, 10, "%d", listener->port); memset(&hints, 0, sizeof(struct addrinfo)); if(listener->socket_domain){ hints.ai_family = listener->socket_domain; }else{ hints.ai_family = AF_UNSPEC; } hints.ai_flags = AI_PASSIVE; hints.ai_socktype = SOCK_STREAM; rc = getaddrinfo(listener->host, service, &hints, &ainfo); if (rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error creating listener: %s.", gai_strerror(rc)); return INVALID_SOCKET; } listener->sock_count = 0; listener->socks = NULL; for(rp = ainfo; rp; rp = rp->ai_next){ if(rp->ai_family == AF_INET){ log__printf(NULL, MOSQ_LOG_INFO, "Opening ipv4 listen socket on port %d.", ntohs(((struct sockaddr_in *)rp->ai_addr)->sin_port)); }else if(rp->ai_family == AF_INET6){ log__printf(NULL, MOSQ_LOG_INFO, "Opening ipv6 listen socket on port %d.", ntohs(((struct sockaddr_in6 *)rp->ai_addr)->sin6_port)); }else{ continue; } sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if(sock == INVALID_SOCKET){ net__print_error(MOSQ_LOG_WARNING, "Warning: %s"); continue; } listener->sock_count++; listener->socks = mosquitto__realloc(listener->socks, sizeof(mosq_sock_t)*listener->sock_count); if(!listener->socks){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); freeaddrinfo(ainfo); return MOSQ_ERR_NOMEM; } listener->socks[listener->sock_count-1] = sock; #ifndef WIN32 ss_opt = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &ss_opt, sizeof(ss_opt)); #endif #ifdef IPV6_V6ONLY ss_opt = 1; setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &ss_opt, sizeof(ss_opt)); #endif if(net__socket_nonblock(&sock)){ freeaddrinfo(ainfo); return 1; } #ifdef SO_BINDTODEVICE if(listener->bind_interface){ memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, listener->bind_interface, sizeof(ifr.ifr_name)-1); ifr.ifr_name[sizeof(ifr.ifr_name)-1] = '\0'; log__printf(NULL, MOSQ_LOG_INFO, "Binding listener to interface \"%s\".", ifr.ifr_name); if(setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) { net__print_error(MOSQ_LOG_ERR, "Error: %s"); COMPAT_CLOSE(sock); freeaddrinfo(ainfo); return 1; } } #endif if(bind(sock, rp->ai_addr, rp->ai_addrlen) == -1){ net__print_error(MOSQ_LOG_ERR, "Error: %s"); COMPAT_CLOSE(sock); freeaddrinfo(ainfo); return 1; } if(listen(sock, 100) == -1){ net__print_error(MOSQ_LOG_ERR, "Error: %s"); freeaddrinfo(ainfo); COMPAT_CLOSE(sock); return 1; } } freeaddrinfo(ainfo); /* We need to have at least one working socket. */ if(listener->sock_count > 0){ #ifdef WITH_TLS if((listener->cafile || listener->capath) && listener->certfile && listener->keyfile){ if(net__tls_server_ctx(listener)){ COMPAT_CLOSE(sock); return 1; } if(net__tls_load_verify(listener)){ COMPAT_CLOSE(sock); return 1; } # ifdef FINAL_WITH_TLS_PSK }else if(listener->psk_hint){ if(tls_ex_index_context == -1){ tls_ex_index_context = SSL_get_ex_new_index(0, "client context", NULL, NULL, NULL); } if(tls_ex_index_listener == -1){ tls_ex_index_listener = SSL_get_ex_new_index(0, "listener", NULL, NULL, NULL); } if(net__tls_server_ctx(listener)){ COMPAT_CLOSE(sock); return 1; } SSL_CTX_set_psk_server_callback(listener->ssl_ctx, psk_server_callback); if(listener->psk_hint){ rc = SSL_CTX_use_psk_identity_hint(listener->ssl_ctx, listener->psk_hint); if(rc == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to set TLS PSK hint."); net__print_ssl_error(NULL); COMPAT_CLOSE(sock); return 1; } } # endif /* FINAL_WITH_TLS_PSK */ } #endif /* WITH_TLS */ return 0; }else{ return 1; } } int net__socket_get_address(mosq_sock_t sock, char *buf, int len) { struct sockaddr_storage addr; socklen_t addrlen; memset(&addr, 0, sizeof(struct sockaddr_storage)); addrlen = sizeof(addr); if(!getpeername(sock, (struct sockaddr *)&addr, &addrlen)){ if(addr.ss_family == AF_INET){ if(inet_ntop(AF_INET, &((struct sockaddr_in *)&addr)->sin_addr.s_addr, buf, len)){ return 0; } }else if(addr.ss_family == AF_INET6){ if(inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr.s6_addr, buf, len)){ return 0; } } } return 1; } mosquitto-1.6.9/src/linker-macosx.syms0000664000175000017500000000041113626052637017101 0ustar rogerroger_mosquitto_log_printf _mosquitto_client_address _mosquitto_client_clean_session _mosquitto_client_id _mosquitto_client_keepalive _mosquitto_client_certificate _mosquitto_client_protocol _mosquitto_client_sub_count _mosquitto_client_username _mosquitto_set_username mosquitto-1.6.9/src/uhpa.h0000664000175000017500000001475713626052637014540 0ustar rogerroger/* Copyright (c) 2015-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef UHPA_H #define UHPA_H /* "Union of heap pointer and array" * * This set of macros is intended to provide a simple means of treating a * variable as a heap pointer or a fixed size array, depending on the size of * the data being stored. It was borne out of the situation where the majority * of calls to malloc for a struct member were ending up less than 8 bytes - * i.e. the size of the 64-bit pointer. By using uhpa a great number of calls * to malloc could be avoided. The downsize to this method is that you must * always know the length of data that you are dealing with. * * The data structure you provide must look something like: * * typedef union { * void *ptr; * char array[MAX_ARRAY_SIZE]; * } uhpa_u * * This code really only makes sense if the data types you want to store are * smaller than a pointer - the most obvious choice being bytes. All of these * functions assume that the array is made up of single bytes. * * You can change the type of ptr to match your needs, with the above caveat * about array. So make ptr a char*, uint8_t*, unsigned char*, ... * * It should be possible to modify the code to work with arrays that have * element sizes bigger than a byte. * * Define MAX_ARRAY_SIZE to be as large as you want, depending on the size of * your commonly used data. Define MAX_ARRAY_SIZE to be sizeof(void *) if you * do not want to "waste" any memory per item - with the tradeoff that calls to * malloc will be more frequent because MAX_ARRAY_SIZE will only be 4 or 8 * bytes, depending on your architecture. * * ============================================================================= * Basic Functions * ============================================================================= * * Note that if you are using strings, set size to be strlen(s)+1, so that the * null terminator is included, or use the _STR functions below. * * UHPA_ALLOC(u, size) * Call to allocate memory to a uhpa variable if required. * * u : the uhpa data type that will have memory allocated or not, * depending on "size". * size : the length of the data to be stored, in bytes. * * returns : 1 if memory was allocated successfully * 0 if memory was not able to be allocated * -1 if no memory needed to be allocated * * UHPA_ACCESS(u, size) * Call to access (for read or write) a uhpa variable that has already had * UHPA_ALLOC() called on it. * * u : the uhpa data type that has already had memory allocated. * size : the length of the stored data, in bytes. * * returns : an appropriate pointer/array address * * UHPA_FREE(u, size) * Call to free memory associated with a uhpa variable. This is safe to * call with a data structure that does not have heap allocated memory. * * u : the uhpa data type that has already had memory allocated. * size : the length of the stored data, in bytes. * * UHPA_MOVE(dest, src, src_size) * Call to move memory stored in one uhpa variable to another. If the data * is stored with heap allocated memory, then dest.ptr is set to src.ptr. * If the data is stored as an array, memmove is used to copy data from * src to dest. In both cases the data stored in src is invalidated by * setting src.ptr to NULL and calling memset(src.array, 0, src_size) * respectively. * * ============================================================================= * String Functions * ============================================================================= * * Convenience functions when working with strings. These are identical to the * non-string versions, except that they increase the value of "size" by 1, to * take into account the need for storing the 0 termination character. * * UHPA_ALLOC_STR(u, size) * UHPA_ACCESS_STR(u, size) * UHPA_FREE_STR(u, size) * UHPA_MOVE_STR(dest, src, size) * * ============================================================================= * Forcing use of malloc * ============================================================================= * * If you wish to force the use of malloc without removing the UHPA macros from * your code (i.e. the macros will never use the array part of the union) then * #define UHPA_FORCE_MALLOC before including this file. * * ============================================================================= * Memory Functions * ============================================================================= * * If you wish to use your own memory functions for alloc/free, #define both * uhpa_malloc and uhpa_free to your own functions. */ #ifndef uhpa_malloc # define uhpa_malloc(size) malloc(size) #endif #ifndef uhpa_free # define uhpa_free(ptr) free(ptr) #endif #define UHPA_ALLOC_CHK(u, size) \ ((size) > sizeof((u).array)? \ (((u).ptr = uhpa_malloc((size)))?1:0) \ :-1) #define UHPA_ACCESS_CHK(u, size) ((size) > sizeof((u).array)?(u).ptr:(u).array) #define UHPA_FREE_CHK(u, size) \ if((size) > sizeof((u).array) && (u).ptr){ \ uhpa_free((u).ptr); \ (u).ptr = NULL; \ } #define UHPA_MOVE_CHK(dest, src, src_size) \ if((src_size) > sizeof((src).array) && (src).ptr){ \ (dest).ptr = (src).ptr; \ (src).ptr = NULL; \ }else{ \ memmove((dest).array, (src).array, (src_size)); \ memset((src).array, 0, (src_size)); \ } #ifdef UHPA_FORCE_MALLOC # define UHPA_ALLOC(u, size) ((u).ptr = uhpa_malloc(size)) # define UHPA_ACCESS(u, size) (u).ptr # define UHPA_FREE(u, size) uhpa_free((u).ptr); (u).ptr = NULL; # define UHPA_MOVE(dest, src, src_size) {(dest).ptr = (src).ptr; (src).ptr = NULL;} #else # define UHPA_ALLOC(u, size) UHPA_ALLOC_CHK(u, size) # define UHPA_ACCESS(u, size) UHPA_ACCESS_CHK(u, size) # define UHPA_FREE(u, size) UHPA_FREE_CHK(u, size) # define UHPA_MOVE(dest, src, src_size) UHPA_MOVE_CHK(dest, src, src_size) #endif #define UHPA_ALLOC_STR(u, size) UHPA_ALLOC((u), (size)+1) #define UHPA_ACCESS_STR(u, size) ((char *)UHPA_ACCESS((u), (size)+1)) #define UHPA_FREE_STR(u, size) UHPA_FREE((u), (size)+1) #define UHPA_MOVE_STR(dest, src, src_size) UHPA_MOVE((dest), (src), (src_size)+1) #endif mosquitto-1.6.9/src/mosquitto_passwd.c0000664000175000017500000004033413626052637017211 0ustar rogerroger/* Copyright (c) 2012-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #include #include #include #ifdef WIN32 # include # include # ifndef __cplusplus # if defined(_MSC_VER) && _MSC_VER < 1900 # define bool char # define true 1 # define false 0 # else # include # endif # endif # define snprintf sprintf_s # include # include #else # include # include # include # include #endif #define MAX_BUFFER_LEN 65536 #define SALT_LEN 12 #include "misc_mosq.h" struct cb_helper { const char *line; const char *username; const char *password; bool found; }; #ifdef WIN32 static FILE *mpw_tmpfile(void) { return tmpfile(); } #else static char alphanum[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static unsigned char tmpfile_path[36]; static FILE *mpw_tmpfile(void) { int fd; size_t i; if(RAND_bytes(tmpfile_path, sizeof(tmpfile_path)) != 1){ return NULL; } strcpy((char *)tmpfile_path, "/tmp/"); for(i=strlen((char *)tmpfile_path); ilength+1); if(!(*encoded)){ BIO_free_all(b64); return 1; } memcpy(*encoded, bptr->data, bptr->length); (*encoded)[bptr->length] = '\0'; BIO_free_all(b64); return 0; } void print_usage(void) { printf("mosquitto_passwd is a tool for managing password files for mosquitto.\n\n"); printf("Usage: mosquitto_passwd [-c | -D] passwordfile username\n"); printf(" mosquitto_passwd -b passwordfile username password\n"); printf(" mosquitto_passwd -U passwordfile\n"); printf(" -b : run in batch mode to allow passing passwords on the command line.\n"); printf(" -c : create a new password file. This will overwrite existing files.\n"); printf(" -D : delete the username rather than adding/updating its password.\n"); printf(" -U : update a plain text password file to use hashed passwords.\n"); printf("\nSee https://mosquitto.org/ for more information.\n\n"); } int output_new_password(FILE *fptr, const char *username, const char *password) { int rc; unsigned char salt[SALT_LEN]; char *salt64 = NULL, *hash64 = NULL; unsigned char hash[EVP_MAX_MD_SIZE]; unsigned int hash_len; const EVP_MD *digest; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_MD_CTX context; #else EVP_MD_CTX *context; #endif rc = RAND_bytes(salt, SALT_LEN); if(!rc){ fprintf(stderr, "Error: Insufficient entropy available to perform password generation.\n"); return 1; } rc = base64_encode(salt, SALT_LEN, &salt64); if(rc){ free(salt64); fprintf(stderr, "Error: Unable to encode salt.\n"); return 1; } digest = EVP_get_digestbyname("sha512"); if(!digest){ free(salt64); fprintf(stderr, "Error: Unable to create openssl digest.\n"); return 1; } #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_MD_CTX_init(&context); EVP_DigestInit_ex(&context, digest, NULL); EVP_DigestUpdate(&context, password, strlen(password)); EVP_DigestUpdate(&context, salt, SALT_LEN); EVP_DigestFinal_ex(&context, hash, &hash_len); EVP_MD_CTX_cleanup(&context); #else context = EVP_MD_CTX_new(); EVP_DigestInit_ex(context, digest, NULL); EVP_DigestUpdate(context, password, strlen(password)); EVP_DigestUpdate(context, salt, SALT_LEN); EVP_DigestFinal_ex(context, hash, &hash_len); EVP_MD_CTX_free(context); #endif rc = base64_encode(hash, hash_len, &hash64); if(rc){ free(salt64); free(hash64); fprintf(stderr, "Error: Unable to encode hash.\n"); return 1; } fprintf(fptr, "%s:$6$%s$%s\n", username, salt64, hash64); free(salt64); free(hash64); return 0; } static int pwfile_iterate(FILE *fptr, FILE *ftmp, int (*cb)(FILE *, FILE *, const char *, const char *, const char *, struct cb_helper *), struct cb_helper *helper) { char *buf; int buflen = 1024; char *lbuf; int lbuflen; int rc = 1; int line = 0; char *username, *password; buf = malloc(buflen); if(buf == NULL){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } lbuflen = buflen; lbuf = malloc(lbuflen); if(lbuf == NULL){ fprintf(stderr, "Error: Out of memory.\n"); free(buf); return 1; } while(!feof(fptr) && fgets_extending(&buf, &buflen, fptr)){ if(lbuflen != buflen){ free(lbuf); lbuflen = buflen; lbuf = malloc(lbuflen); if(lbuf == NULL){ fprintf(stderr, "Error: Out of memory.\n"); free(buf); return 1; } } memcpy(lbuf, buf, buflen); line++; username = strtok(buf, ":"); password = strtok(NULL, ":"); if(username == NULL || password == NULL){ fprintf(stderr, "Error: Corrupt password file at line %d.\n", line); free(lbuf); free(buf); return 1; } username = misc__trimblanks(username); password = misc__trimblanks(password); if(strlen(username) == 0 || strlen(password) == 0){ fprintf(stderr, "Error: Corrupt password file at line %d.\n", line); free(lbuf); free(buf); return 1; } rc = cb(fptr, ftmp, username, password, lbuf, helper); if(rc){ break; } } free(lbuf); free(buf); return rc; } /* ====================================================================== * Delete a user from the password file * ====================================================================== */ static int delete_pwuser_cb(FILE *fptr, FILE *ftmp, const char *username, const char *password, const char *line, struct cb_helper *helper) { if(strcmp(username, helper->username)){ /* If this isn't the username to delete, write it to the new file */ fprintf(ftmp, "%s", line); }else{ /* Don't write the matching username to the file. */ helper->found = true; } return 0; } int delete_pwuser(FILE *fptr, FILE *ftmp, const char *username) { struct cb_helper helper; int rc; memset(&helper, 0, sizeof(helper)); helper.username = username; rc = pwfile_iterate(fptr, ftmp, delete_pwuser_cb, &helper); if(helper.found == false){ fprintf(stderr, "Warning: User %s not found in password file.\n", username); return 1; } return rc; } /* ====================================================================== * Update a plain text password file to use hashes * ====================================================================== */ static int update_file_cb(FILE *fptr, FILE *ftmp, const char *username, const char *password, const char *line, struct cb_helper *helper) { return output_new_password(ftmp, username, password); } int update_file(FILE *fptr, FILE *ftmp) { return pwfile_iterate(fptr, ftmp, update_file_cb, NULL); } /* ====================================================================== * Update an existing user password / create a new password * ====================================================================== */ static int update_pwuser_cb(FILE *fptr, FILE *ftmp, const char *username, const char *password, const char *line, struct cb_helper *helper) { int rc = 0; printf("%s\n", username); if(strcmp(username, helper->username)){ /* If this isn't the matching user, then writing out the exiting line */ printf("%s\n", line); fprintf(ftmp, "%s", line); }else{ /* Write out a new line for our matching username */ helper->found = true; rc = output_new_password(ftmp, username, password); } return rc; } int update_pwuser(FILE *fptr, FILE *ftmp, const char *username, const char *password) { struct cb_helper helper; int rc; memset(&helper, 0, sizeof(helper)); helper.username = username; rc = pwfile_iterate(fptr, ftmp, update_pwuser_cb, &helper); if(helper.found){ return rc; }else{ return output_new_password(ftmp, username, password); } } int gets_quiet(char *s, int len) { #ifdef WIN32 HANDLE h; DWORD con_orig, con_quiet = 0; DWORD read_len = 0; memset(s, 0, len); h = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(h, &con_orig); con_quiet = con_orig; con_quiet &= ~ENABLE_ECHO_INPUT; con_quiet |= ENABLE_LINE_INPUT; SetConsoleMode(h, con_quiet); if(!ReadConsole(h, s, len, &read_len, NULL)){ SetConsoleMode(h, con_orig); return 1; } while(s[strlen(s)-1] == 10 || s[strlen(s)-1] == 13){ s[strlen(s)-1] = 0; } if(strlen(s) == 0){ return 1; } SetConsoleMode(h, con_orig); return 0; #else struct termios ts_quiet, ts_orig; char *rs; memset(s, 0, len); tcgetattr(0, &ts_orig); ts_quiet = ts_orig; ts_quiet.c_lflag &= ~(ECHO | ICANON); tcsetattr(0, TCSANOW, &ts_quiet); rs = fgets(s, len, stdin); tcsetattr(0, TCSANOW, &ts_orig); if(!rs){ return 1; }else{ while(s[strlen(s)-1] == 10 || s[strlen(s)-1] == 13){ s[strlen(s)-1] = 0; } if(strlen(s) == 0){ return 1; } } return 0; #endif } int get_password(char *password, size_t len) { char pw1[MAX_BUFFER_LEN], pw2[MAX_BUFFER_LEN]; size_t minLen; minLen = len < MAX_BUFFER_LEN ? len : MAX_BUFFER_LEN; printf("Password: "); fflush(stdout); if(gets_quiet(pw1, minLen)){ fprintf(stderr, "Error: Empty password.\n"); return 1; } printf("\n"); printf("Reenter password: "); fflush(stdout); if(gets_quiet(pw2, minLen)){ fprintf(stderr, "Error: Empty password.\n"); return 1; } printf("\n"); if(strcmp(pw1, pw2)){ fprintf(stderr, "Error: Passwords do not match.\n"); return 1; } strncpy(password, pw1, minLen); return 0; } int copy_contents(FILE *src, FILE *dest) { char buf[MAX_BUFFER_LEN]; size_t len; rewind(src); rewind(dest); #ifdef WIN32 _chsize(fileno(dest), 0); #else if(ftruncate(fileno(dest), 0)) return 1; #endif while(!feof(src)){ len = fread(buf, 1, MAX_BUFFER_LEN, src); if(len > 0){ if(fwrite(buf, 1, len, dest) != len){ return 1; } }else{ return !feof(src); } } return 0; } int create_backup(const char *backup_file, FILE *fptr) { FILE *fbackup; fbackup = fopen(backup_file, "wt"); if(!fbackup){ fprintf(stderr, "Error creating backup password file \"%s\", not continuing.\n", backup_file); return 1; } if(copy_contents(fptr, fbackup)){ fprintf(stderr, "Error copying data to backup password file \"%s\", not continuing.\n", backup_file); fclose(fbackup); return 1; } fclose(fbackup); rewind(fptr); return 0; } void handle_sigint(int signal) { #ifndef WIN32 struct termios ts; tcgetattr(0, &ts); ts.c_lflag |= ECHO | ICANON; tcsetattr(0, TCSANOW, &ts); #endif UNUSED(signal); exit(0); } int main(int argc, char *argv[]) { char *password_file_tmp = NULL; char *password_file = NULL; char *username = NULL; char *password_cmd = NULL; bool batch_mode = false; bool create_new = false; bool delete_user = false; FILE *fptr, *ftmp; char password[MAX_BUFFER_LEN]; int rc; bool do_update_file = false; char *backup_file; signal(SIGINT, handle_sigint); signal(SIGTERM, handle_sigint); #if OPENSSL_VERSION_NUMBER < 0x10100000L || OPENSSL_API_COMPAT < 0x10100000L OpenSSL_add_all_digests(); #else OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ | OPENSSL_INIT_ADD_ALL_DIGESTS \ | OPENSSL_INIT_LOAD_CONFIG, NULL); #endif if(argc == 1){ print_usage(); return 1; } if(!strcmp(argv[1], "-c")){ create_new = true; if(argc != 4){ fprintf(stderr, "Error: -c argument given but password file or username missing.\n"); return 1; }else{ password_file_tmp = argv[2]; username = argv[3]; } }else if(!strcmp(argv[1], "-D")){ delete_user = true; if(argc != 4){ fprintf(stderr, "Error: -D argument given but password file or username missing.\n"); return 1; }else{ password_file_tmp = argv[2]; username = argv[3]; } }else if(!strcmp(argv[1], "-b")){ batch_mode = true; if(argc != 5){ fprintf(stderr, "Error: -b argument given but password file, username or password missing.\n"); return 1; }else{ password_file_tmp = argv[2]; username = argv[3]; password_cmd = argv[4]; } }else if(!strcmp(argv[1], "-U")){ if(argc != 3){ fprintf(stderr, "Error: -U argument given but password file missing.\n"); return 1; }else{ do_update_file = true; password_file_tmp = argv[2]; } }else if(argc == 3){ password_file_tmp = argv[1]; username = argv[2]; }else{ print_usage(); return 1; } if(username && strlen(username) > 65535){ fprintf(stderr, "Error: Username must be less than 65536 characters long.\n"); return 1; } if(password_cmd && strlen(password_cmd) > 65535){ fprintf(stderr, "Error: Password must be less than 65536 characters long.\n"); return 1; } #ifdef WIN32 password_file = _fullpath(NULL, password_file_tmp, 0); if(!password_file){ fprintf(stderr, "Error getting full path for password file.\n"); return 1; } #else password_file = realpath(password_file_tmp, NULL); if(!password_file){ if(errno == ENOENT){ password_file = strdup(password_file_tmp); if(!password_file){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } }else{ fprintf(stderr, "Error reading password file: %s\n", strerror(errno)); return 1; } } #endif if(create_new){ rc = get_password(password, MAX_BUFFER_LEN); if(rc){ free(password_file); return rc; } fptr = fopen(password_file, "wt"); if(!fptr){ fprintf(stderr, "Error: Unable to open file %s for writing. %s.\n", password_file, strerror(errno)); free(password_file); return 1; } free(password_file); rc = output_new_password(fptr, username, password); fclose(fptr); return rc; }else{ fptr = fopen(password_file, "r+t"); if(!fptr){ fprintf(stderr, "Error: Unable to open password file %s. %s.\n", password_file, strerror(errno)); free(password_file); return 1; } backup_file = malloc(strlen(password_file)+5); if(!backup_file){ fprintf(stderr, "Error: Out of memory.\n"); free(password_file); return 1; } snprintf(backup_file, strlen(password_file)+5, "%s.tmp", password_file); free(password_file); password_file = NULL; if(create_backup(backup_file, fptr)){ fclose(fptr); free(backup_file); return 1; } ftmp = mpw_tmpfile(); if(!ftmp){ fprintf(stderr, "Error: Unable to open temporary file. %s.\n", strerror(errno)); fclose(fptr); free(backup_file); return 1; } if(delete_user){ rc = delete_pwuser(fptr, ftmp, username); }else if(do_update_file){ rc = update_file(fptr, ftmp); }else{ if(batch_mode){ /* Update password for individual user */ rc = update_pwuser(fptr, ftmp, username, password_cmd); }else{ rc = get_password(password, MAX_BUFFER_LEN); if(rc){ fclose(fptr); fclose(ftmp); unlink(backup_file); free(backup_file); return rc; } /* Update password for individual user */ rc = update_pwuser(fptr, ftmp, username, password); } } if(rc){ fclose(fptr); fclose(ftmp); unlink(backup_file); free(backup_file); return rc; } if(copy_contents(ftmp, fptr)){ fclose(fptr); fclose(ftmp); fprintf(stderr, "Error occurred updating password file.\n"); fprintf(stderr, "Password file may be corrupt, check the backup file: %s.\n", backup_file); free(backup_file); return 1; } fclose(fptr); fclose(ftmp); /* Everything was ok so backup no longer needed. May contain old * passwords so shouldn't be kept around. */ unlink(backup_file); free(backup_file); } return 0; } mosquitto-1.6.9/src/Makefile0000664000175000017500000002532613626052637015064 0ustar rogerrogerinclude ../config.mk .PHONY: all install uninstall clean reallyclean ifeq ($(WITH_TLS),yes) all : mosquitto mosquitto_passwd else all : mosquitto endif OBJS= mosquitto.o \ alias_mosq.o \ bridge.o \ conf.o \ conf_includedir.o \ context.o \ database.o \ handle_auth.o \ handle_connack.o \ handle_connect.o \ handle_disconnect.o \ handle_ping.o \ handle_pubackcomp.o \ handle_publish.o \ handle_pubrec.o \ handle_pubrel.o \ handle_suback.o \ handle_subscribe.o \ handle_unsuback.o \ handle_unsubscribe.o \ logging.o \ loop.o \ memory_mosq.o \ misc_mosq.o \ net.o \ net_mosq.o \ net_mosq_ocsp.o \ packet_datatypes.o \ packet_mosq.o \ property_broker.o \ property_mosq.o \ persist_read.o \ persist_read_v234.o \ persist_read_v5.o \ persist_write.o \ persist_write_v5.o \ plugin.o \ read_handle.o \ security.o \ security_default.o \ send_auth.o \ send_connack.o \ send_connect.o \ send_disconnect.o \ send_mosq.o \ send_publish.o \ send_suback.o \ send_subscribe.o \ send_unsuback.o \ send_unsubscribe.o \ service.o \ session_expiry.o \ signals.o \ subs.o \ sys_tree.o \ time_mosq.o \ tls_mosq.o \ utf8_mosq.o \ util_mosq.o \ util_topic.o \ websockets.o \ will_delay.o \ will_mosq.o mosquitto : ${OBJS} ${CROSS_COMPILE}${CC} ${BROKER_LDFLAGS} $^ -o $@ $(BROKER_LDADD) mosquitto.o : mosquitto.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ alias_mosq.o : ../lib/alias_mosq.c ../lib/alias_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ bridge.o : bridge.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ conf.o : conf.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ conf_includedir.o : conf_includedir.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ context.o : context.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ database.o : database.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_auth.o : handle_auth.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_connack.o : handle_connack.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_connect.o : handle_connect.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_disconnect.o : handle_disconnect.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_ping.o : ../lib/handle_ping.c ../lib/read_handle.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_pubackcomp.o : ../lib/handle_pubackcomp.c ../lib/read_handle.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_publish.o : handle_publish.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_pubrec.o : ../lib/handle_pubrec.c ../lib/read_handle.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_pubrel.o : ../lib/handle_pubrel.c ../lib/read_handle.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_suback.o : ../lib/handle_suback.c ../lib/read_handle.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_subscribe.o : handle_subscribe.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_unsuback.o : ../lib/handle_unsuback.c ../lib/read_handle.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ handle_unsubscribe.o : handle_unsubscribe.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ logging.o : logging.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ loop.o : loop.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ memory_mosq.o : ../lib/memory_mosq.c ../lib/memory_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ misc_mosq.o : ../lib/misc_mosq.c ../lib/misc_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ net.o : net.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ net_mosq_ocsp.o : ../lib/net_mosq_ocsp.c ../lib/net_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ net_mosq.o : ../lib/net_mosq.c ../lib/net_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ persist_read.o : persist_read.c persist.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ persist_read_v234.o : persist_read_v234.c persist.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ persist_read_v5.o : persist_read_v5.c persist.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ persist_write.o : persist_write.c persist.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ persist_write_v5.o : persist_write_v5.c persist.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ packet_datatypes.o : ../lib/packet_datatypes.c ../lib/packet_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ packet_mosq.o : ../lib/packet_mosq.c ../lib/packet_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ property_broker.o : property_broker.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ property_mosq.o : ../lib/property_mosq.c ../lib/property_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ plugin.o : plugin.c mosquitto_plugin.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ read_handle.o : read_handle.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ security.o : security.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ security_default.o : security_default.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_auth.o : send_auth.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_connect.o : ../lib/send_connect.c ../lib/send_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_disconnect.o : ../lib/send_disconnect.c ../lib/send_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_connack.o : send_connack.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_mosq.o : ../lib/send_mosq.c ../lib/send_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_publish.o : ../lib/send_publish.c ../lib/send_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_suback.o : send_suback.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_subscribe.o : ../lib/send_subscribe.c ../lib/send_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_unsuback.o : send_unsuback.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ send_unsubscribe.o : ../lib/send_unsubscribe.c ../lib/send_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ service.o : service.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ session_expiry.o : session_expiry.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ signals.o : signals.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ subs.o : subs.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ sys_tree.o : sys_tree.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ time_mosq.o : ../lib/time_mosq.c ../lib/time_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ tls_mosq.o : ../lib/tls_mosq.c ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ util_mosq.o : ../lib/util_mosq.c ../lib/util_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ util_topic.o : ../lib/util_topic.c ../lib/util_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ utf8_mosq.o : ../lib/utf8_mosq.c ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ websockets.o : websockets.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ will_delay.o : will_delay.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ will_mosq.o : ../lib/will_mosq.c ../lib/will_mosq.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ mosquitto_passwd : mosquitto_passwd.o misc_mosq.o ${CROSS_COMPILE}${CC} ${LDFLAGS} $^ -o $@ $(PASSWD_LDADD) mosquitto_passwd.o : mosquitto_passwd.c ${CROSS_COMPILE}${CC} -I.. -I../lib $(CPPFLAGS) $(CFLAGS) -c $< -o $@ plugin_defer.so : plugin_defer.c mosquitto_plugin.h mosquitto_broker.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} -I. -I../lib -fPIC -shared $< -o $@ plugin_debug.so : plugin_debug.c mosquitto_plugin.h mosquitto_broker.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} -I. -I../lib -fPIC -shared $< -o $@ install : all $(INSTALL) -d "${DESTDIR}$(prefix)/sbin" $(INSTALL) ${STRIP_OPTS} mosquitto "${DESTDIR}${prefix}/sbin/mosquitto" $(INSTALL) -d "${DESTDIR}$(prefix)/include" $(INSTALL) mosquitto_broker.h "${DESTDIR}${prefix}/include/mosquitto_broker.h" $(INSTALL) mosquitto_plugin.h "${DESTDIR}${prefix}/include/mosquitto_plugin.h" ifeq ($(WITH_TLS),yes) $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_passwd "${DESTDIR}${prefix}/bin/mosquitto_passwd" endif uninstall : -rm -f "${DESTDIR}${prefix}/sbin/mosquitto" -rm -f "${DESTDIR}${prefix}/include/mosquitto_broker.h" -rm -f "${DESTDIR}${prefix}/include/mosquitto_plugin.h" -rm -f "${DESTDIR}${prefix}/bin/mosquitto_passwd" clean : -rm -f *.o mosquitto mosquitto_passwd *.gcda *.gcno reallyclean : clean -rm -rf *.orig *.db mosquitto-1.6.9/lib/0000775000175000017500000000000013626052637013373 5ustar rogerrogermosquitto-1.6.9/lib/socks_mosq.h0000664000175000017500000000124213626052637015724 0ustar rogerroger/* Copyright (c) 2014-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef SOCKS_MOSQ_H #define SOCKS_MOSQ_H int socks5__send(struct mosquitto *mosq); int socks5__read(struct mosquitto *mosq); #endif mosquitto-1.6.9/lib/actions.c0000664000175000017500000002041113626052637015175 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include "mosquitto.h" #include "mosquitto_internal.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "send_mosq.h" #include "util_mosq.h" int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain) { return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, NULL); } int mosquitto_publish_v5(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, const mosquitto_property *properties) { struct mosquitto_message_all *message; uint16_t local_mid; const mosquitto_property *p; const mosquitto_property *outgoing_properties = NULL; mosquitto_property *properties_copy = NULL; mosquitto_property local_property; bool have_topic_alias; int rc; int tlen = 0; uint32_t remaining_length; if(!mosq || qos<0 || qos>2) return MOSQ_ERR_INVAL; if(mosq->protocol != mosq_p_mqtt5 && properties) return MOSQ_ERR_NOT_SUPPORTED; if(qos > mosq->maximum_qos) return MOSQ_ERR_QOS_NOT_SUPPORTED; if(properties){ if(properties->client_generated){ outgoing_properties = properties; }else{ memcpy(&local_property, properties, sizeof(mosquitto_property)); local_property.client_generated = true; local_property.next = NULL; outgoing_properties = &local_property; } rc = mosquitto_property_check_all(CMD_PUBLISH, outgoing_properties); if(rc) return rc; } if(!topic || STREMPTY(topic)){ if(topic) topic = NULL; if(mosq->protocol == mosq_p_mqtt5){ p = outgoing_properties; have_topic_alias = false; while(p){ if(p->identifier == MQTT_PROP_TOPIC_ALIAS){ have_topic_alias = true; break; } p = p->next; } if(have_topic_alias == false){ return MOSQ_ERR_INVAL; } }else{ return MOSQ_ERR_INVAL; } }else{ tlen = strlen(topic); if(mosquitto_validate_utf8(topic, tlen)) return MOSQ_ERR_MALFORMED_UTF8; if(payloadlen < 0 || payloadlen > MQTT_MAX_PAYLOAD) return MOSQ_ERR_PAYLOAD_SIZE; if(mosquitto_pub_topic_check(topic) != MOSQ_ERR_SUCCESS){ return MOSQ_ERR_INVAL; } } if(mosq->maximum_packet_size > 0){ remaining_length = 1 + 2+tlen + payloadlen + property__get_length_all(outgoing_properties); if(qos > 0){ remaining_length++; } if(packet__check_oversize(mosq, remaining_length)){ return MOSQ_ERR_OVERSIZE_PACKET; } } local_mid = mosquitto__mid_generate(mosq); if(mid){ *mid = local_mid; } if(qos == 0){ return send__publish(mosq, local_mid, topic, payloadlen, payload, qos, retain, false, outgoing_properties, NULL, 0); }else{ if(outgoing_properties){ rc = mosquitto_property_copy_all(&properties_copy, outgoing_properties); if(rc) return rc; } message = mosquitto__calloc(1, sizeof(struct mosquitto_message_all)); if(!message){ mosquitto_property_free_all(&properties_copy); return MOSQ_ERR_NOMEM; } message->next = NULL; message->timestamp = mosquitto_time(); message->msg.mid = local_mid; if(topic){ message->msg.topic = mosquitto__strdup(topic); if(!message->msg.topic){ message__cleanup(&message); mosquitto_property_free_all(&properties_copy); return MOSQ_ERR_NOMEM; } } if(payloadlen){ message->msg.payloadlen = payloadlen; message->msg.payload = mosquitto__malloc(payloadlen*sizeof(uint8_t)); if(!message->msg.payload){ message__cleanup(&message); mosquitto_property_free_all(&properties_copy); return MOSQ_ERR_NOMEM; } memcpy(message->msg.payload, payload, payloadlen*sizeof(uint8_t)); }else{ message->msg.payloadlen = 0; message->msg.payload = NULL; } message->msg.qos = qos; message->msg.retain = retain; message->dup = false; message->properties = properties_copy; pthread_mutex_lock(&mosq->msgs_out.mutex); message->state = mosq_ms_invalid; message__queue(mosq, message, mosq_md_out); pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_SUCCESS; } } int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos) { return mosquitto_subscribe_multiple(mosq, mid, 1, (char *const *const)&sub, qos, 0, NULL); } int mosquitto_subscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, int qos, int options, const mosquitto_property *properties) { return mosquitto_subscribe_multiple(mosq, mid, 1, (char *const *const)&sub, qos, options, properties); } int mosquitto_subscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, int qos, int options, const mosquitto_property *properties) { const mosquitto_property *outgoing_properties = NULL; mosquitto_property local_property; int i; int rc; uint32_t remaining_length = 0; int slen; if(!mosq || !sub_count || !sub) return MOSQ_ERR_INVAL; if(mosq->protocol != mosq_p_mqtt5 && properties) return MOSQ_ERR_NOT_SUPPORTED; if(qos < 0 || qos > 2) return MOSQ_ERR_INVAL; if((options & 0x30) == 0x30 || (options & 0xC0) != 0) return MOSQ_ERR_INVAL; if(mosq->sock == INVALID_SOCKET) return MOSQ_ERR_NO_CONN; if(properties){ if(properties->client_generated){ outgoing_properties = properties; }else{ memcpy(&local_property, properties, sizeof(mosquitto_property)); local_property.client_generated = true; local_property.next = NULL; outgoing_properties = &local_property; } rc = mosquitto_property_check_all(CMD_SUBSCRIBE, outgoing_properties); if(rc) return rc; } for(i=0; imaximum_packet_size > 0){ remaining_length += 2 + property__get_length_all(outgoing_properties); if(packet__check_oversize(mosq, remaining_length)){ return MOSQ_ERR_OVERSIZE_PACKET; } } if(mosq->protocol == mosq_p_mqtt311 || mosq->protocol == mosq_p_mqtt31){ options = 0; } return send__subscribe(mosq, mid, sub_count, sub, qos|options, outgoing_properties); } int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub) { return mosquitto_unsubscribe_multiple(mosq, mid, 1, (char *const *const)&sub, NULL); } int mosquitto_unsubscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, const mosquitto_property *properties) { return mosquitto_unsubscribe_multiple(mosq, mid, 1, (char *const *const)&sub, properties); } int mosquitto_unsubscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, const mosquitto_property *properties) { const mosquitto_property *outgoing_properties = NULL; mosquitto_property local_property; int rc; int i; uint32_t remaining_length = 0; int slen; if(!mosq) return MOSQ_ERR_INVAL; if(mosq->protocol != mosq_p_mqtt5 && properties) return MOSQ_ERR_NOT_SUPPORTED; if(mosq->sock == INVALID_SOCKET) return MOSQ_ERR_NO_CONN; if(properties){ if(properties->client_generated){ outgoing_properties = properties; }else{ memcpy(&local_property, properties, sizeof(mosquitto_property)); local_property.client_generated = true; local_property.next = NULL; outgoing_properties = &local_property; } rc = mosquitto_property_check_all(CMD_UNSUBSCRIBE, outgoing_properties); if(rc) return rc; } for(i=0; imaximum_packet_size > 0){ remaining_length += 2 + property__get_length_all(outgoing_properties); if(packet__check_oversize(mosq, remaining_length)){ return MOSQ_ERR_OVERSIZE_PACKET; } } return send__unsubscribe(mosq, mid, sub_count, sub, outgoing_properties); } mosquitto-1.6.9/lib/handle_connack.c0000664000175000017500000000744113626052637016474 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" static void connack_callback(struct mosquitto *mosq, uint8_t reason_code, uint8_t connect_flags, const mosquitto_property *properties) { log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received CONNACK (%d)", mosq->id, reason_code); if(reason_code == MQTT_RC_SUCCESS){ mosq->reconnects = 0; } pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_connect){ mosq->in_callback = true; mosq->on_connect(mosq, mosq->userdata, reason_code); mosq->in_callback = false; } if(mosq->on_connect_with_flags){ mosq->in_callback = true; mosq->on_connect_with_flags(mosq, mosq->userdata, reason_code, connect_flags); mosq->in_callback = false; } if(mosq->on_connect_v5){ mosq->in_callback = true; mosq->on_connect_v5(mosq, mosq->userdata, reason_code, connect_flags, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); } int handle__connack(struct mosquitto *mosq) { uint8_t connect_flags; uint8_t reason_code; int rc; mosquitto_property *properties = NULL; char *clientid = NULL; assert(mosq); rc = packet__read_byte(&mosq->in_packet, &connect_flags); if(rc) return rc; rc = packet__read_byte(&mosq->in_packet, &reason_code); if(rc) return rc; if(mosq->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_CONNACK, &mosq->in_packet, &properties); if(rc == MOSQ_ERR_PROTOCOL && reason_code == CONNACK_REFUSED_PROTOCOL_VERSION){ /* This could occur because we are connecting to a v3.x broker and * it has replied with "unacceptable protocol version", but with a * v3 CONNACK. */ connack_callback(mosq, MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION, connect_flags, NULL); return rc; }else if(rc){ return rc; } } mosquitto_property_read_string(properties, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, &clientid, false); if(clientid){ if(mosq->id){ /* We've been sent a client identifier but already have one. This * shouldn't happen. */ free(clientid); mosquitto_property_free_all(&properties); return MOSQ_ERR_PROTOCOL; }else{ mosq->id = clientid; clientid = NULL; } } mosquitto_property_read_byte(properties, MQTT_PROP_MAXIMUM_QOS, &mosq->maximum_qos, false); mosquitto_property_read_int16(properties, MQTT_PROP_RECEIVE_MAXIMUM, &mosq->msgs_out.inflight_maximum, false); mosquitto_property_read_int16(properties, MQTT_PROP_SERVER_KEEP_ALIVE, &mosq->keepalive, false); mosquitto_property_read_int32(properties, MQTT_PROP_MAXIMUM_PACKET_SIZE, &mosq->maximum_packet_size, false); mosq->msgs_out.inflight_quota = mosq->msgs_out.inflight_maximum; connack_callback(mosq, reason_code, connect_flags, properties); mosquitto_property_free_all(&properties); switch(reason_code){ case 0: pthread_mutex_lock(&mosq->state_mutex); if(mosq->state != mosq_cs_disconnecting){ mosq->state = mosq_cs_active; } pthread_mutex_unlock(&mosq->state_mutex); message__retry_check(mosq); return MOSQ_ERR_SUCCESS; case 1: case 2: case 3: case 4: case 5: return MOSQ_ERR_CONN_REFUSED; default: return MOSQ_ERR_PROTOCOL; } } mosquitto-1.6.9/lib/linker.version0000664000175000017500000000636113626052637016274 0ustar rogerroger/* Linker version script - currently used here primarily to control which * symbols are exported. */ MOSQ_1.0 { global: mosquitto_lib_version; mosquitto_lib_init; mosquitto_lib_cleanup; mosquitto_new; mosquitto_destroy; mosquitto_reinitialise; mosquitto_will_set; mosquitto_will_clear; mosquitto_username_pw_set; mosquitto_connect; mosquitto_connect_async; mosquitto_reconnect; mosquitto_disconnect; mosquitto_publish; mosquitto_subscribe; mosquitto_unsubscribe; mosquitto_message_copy; mosquitto_message_free; mosquitto_loop; mosquitto_socket; mosquitto_loop_start; mosquitto_loop_stop; mosquitto_loop_read; mosquitto_loop_write; mosquitto_loop_misc; mosquitto_connect_callback_set; mosquitto_disconnect_callback_set; mosquitto_publish_callback_set; mosquitto_message_callback_set; mosquitto_subscribe_callback_set; mosquitto_unsubscribe_callback_set; mosquitto_log_callback_set; mosquitto_message_retry_set; mosquitto_want_write; mosquitto_user_data_set; mosquitto_strerror; mosquitto_connack_string; mosquitto_tls_set; mosquitto_tls_opts_set; mosquitto_tls_psk_set; mosquitto_sub_topic_tokenise; mosquitto_sub_topic_tokens_free; mosquitto_topic_matches_sub; local: *; }; MOSQ_1.1 { global: mosquitto_loop_forever; } MOSQ_1.0; MOSQ_1.2 { global: mosquitto_connect_bind; mosquitto_connect_bind_async; mosquitto_max_inflight_messages_set; mosquitto_reconnect_delay_set; mosquitto_reconnect_async; mosquitto_tls_insecure_set; } MOSQ_1.1; MOSQ_1.3 { global: mosquitto_connect_srv; } MOSQ_1.2; MOSQ_1.4 { global: mosquitto_threaded_set; mosquitto_opts_set; mosquitto_pub_topic_check; mosquitto_sub_topic_check; mosquitto_socks5_set; } MOSQ_1.3; MOSQ_1.5 { global: mosquitto_subscribe_simple; mosquitto_subscribe_callback; mosquitto_message_free_contents; mosquitto_validate_utf8; mosquitto_userdata; mosquitto_pub_topic_check2; mosquitto_sub_topic_check2; mosquitto_topic_matches_sub2; mosquitto_connect_with_flags_callback_set; } MOSQ_1.4; MOSQ_1.6 { global: mosquitto_connect_bind_v5; mosquitto_connect_v5_callback_set; mosquitto_disconnect_v5; mosquitto_disconnect_v5_callback_set; mosquitto_int_option; mosquitto_message_v5_callback_set; mosquitto_property_add_binary; mosquitto_property_add_byte; mosquitto_property_add_int16; mosquitto_property_add_int32; mosquitto_property_add_string; mosquitto_property_add_string_pair; mosquitto_property_add_varint; mosquitto_property_check_all; mosquitto_property_check_command; mosquitto_property_free_all; mosquitto_property_read_binary; mosquitto_property_read_byte; mosquitto_property_read_int16; mosquitto_property_read_int32; mosquitto_property_read_string; mosquitto_property_read_string_pair; mosquitto_property_read_varint; mosquitto_publish_v5; mosquitto_publish_v5_callback_set; mosquitto_reason_string; mosquitto_string_option; mosquitto_string_to_command; mosquitto_string_to_property_info; mosquitto_subscribe_multiple; mosquitto_subscribe_v5; mosquitto_subscribe_v5_callback_set; mosquitto_unsubscribe_multiple; mosquitto_unsubscribe_v5; mosquitto_unsubscribe_v5_callback_set; mosquitto_void_option; mosquitto_will_set_v5; } MOSQ_1.5; mosquitto-1.6.9/lib/handle_disconnect.c0000664000175000017500000000273213626052637017207 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "logging_mosq.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "util_mosq.h" int handle__disconnect(struct mosquitto *mosq) { int rc; uint8_t reason_code; mosquitto_property *properties = NULL; if(!mosq){ return MOSQ_ERR_INVAL; } if(mosq->protocol != mosq_p_mqtt5){ return MOSQ_ERR_PROTOCOL; } rc = packet__read_byte(&mosq->in_packet, &reason_code); if(rc) return rc; if(mosq->in_packet.remaining_length > 2){ rc = property__read_all(CMD_DISCONNECT, &mosq->in_packet, &properties); if(rc) return rc; mosquitto_property_free_all(&properties); } log__printf(mosq, MOSQ_LOG_DEBUG, "Received DISCONNECT (%d)", reason_code); do_client_disconnect(mosq, reason_code, properties); mosquitto_property_free_all(&properties); return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/CMakeLists.txt0000664000175000017500000000532413626052637016137 0ustar rogerrogeradd_subdirectory(cpp) include_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/lib ${STDBOOL_H_PATH} ${STDINT_H_PATH} ${OPENSSL_INCLUDE_DIR} ${PTHREAD_INCLUDE_DIR}) link_directories(${mosquitto_SOURCE_DIR}/lib) if (WITH_BUNDLED_DEPS) include_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/src/deps) endif (WITH_BUNDLED_DEPS) set(C_SRC actions.c callbacks.c connect.c handle_auth.c handle_connack.c handle_disconnect.c handle_ping.c handle_pubackcomp.c handle_publish.c handle_pubrec.c handle_pubrel.c handle_suback.c handle_unsuback.c helpers.c logging_mosq.c logging_mosq.h loop.c memory_mosq.c memory_mosq.h messages_mosq.c messages_mosq.h misc_mosq.c misc_mosq.h mosquitto.c mosquitto.h mosquitto_internal.h mqtt_protocol.h net_mosq_ocsp.c net_mosq.c net_mosq.h options.c packet_datatypes.c packet_mosq.c packet_mosq.h property_mosq.c property_mosq.h read_handle.c read_handle.h send_connect.c send_disconnect.c send_mosq.c send_publish.c send_subscribe.c send_unsubscribe.c send_mosq.c send_mosq.h socks_mosq.c srv_mosq.c thread_mosq.c time_mosq.c tls_mosq.c utf8_mosq.c util_mosq.c util_topic.c util_mosq.h will_mosq.c will_mosq.h) set (LIBRARIES ${OPENSSL_LIBRARIES} ${PTHREAD_LIBRARIES}) if (UNIX AND NOT APPLE) find_library(LIBRT rt) if (LIBRT) set (LIBRARIES ${LIBRARIES} rt) endif (LIBRT) endif (UNIX AND NOT APPLE) if (WIN32) set (LIBRARIES ${LIBRARIES} ws2_32) endif (WIN32) if (WITH_SRV) # Simple detect c-ares find_path(ARES_HEADER ares.h) if (ARES_HEADER) add_definitions("-DWITH_SRV") set (LIBRARIES ${LIBRARIES} cares) else (ARES_HEADER) message(WARNING "c-ares library not found.") endif (ARES_HEADER) endif (WITH_SRV) add_library(libmosquitto SHARED ${C_SRC}) set_target_properties(libmosquitto PROPERTIES POSITION_INDEPENDENT_CODE 1 ) target_link_libraries(libmosquitto ${LIBRARIES}) set_target_properties(libmosquitto PROPERTIES OUTPUT_NAME mosquitto VERSION ${VERSION} SOVERSION 1 ) install(TARGETS libmosquitto RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") if (WITH_STATIC_LIBRARIES) add_library(libmosquitto_static STATIC ${C_SRC}) if (WITH_PIC) set_target_properties(libmosquitto_static PROPERTIES POSITION_INDEPENDENT_CODE 1 ) endif (WITH_PIC) target_link_libraries(libmosquitto_static ${LIBRARIES}) set_target_properties(libmosquitto_static PROPERTIES OUTPUT_NAME mosquitto_static VERSION ${VERSION} ) target_compile_definitions(libmosquitto_static PUBLIC "LIBMOSQUITTO_STATIC") install(TARGETS libmosquitto_static ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}") endif (WITH_STATIC_LIBRARIES) install(FILES mosquitto.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") mosquitto-1.6.9/lib/handle_pubackcomp.c0000664000175000017500000000647013626052637017205 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" #ifdef WITH_BROKER int handle__pubackcomp(struct mosquitto_db *db, struct mosquitto *mosq, const char *type) #else int handle__pubackcomp(struct mosquitto *mosq, const char *type) #endif { uint8_t reason_code = 0; uint16_t mid; int rc; mosquitto_property *properties = NULL; int qos; int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } pthread_mutex_lock(&mosq->msgs_out.mutex); util__increment_send_quota(mosq); pthread_mutex_unlock(&mosq->msgs_out.mutex); rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc) return rc; qos = type[3] == 'A'?1:2; /* pubAck or pubComp */ if(mid == 0) return MOSQ_ERR_PROTOCOL; if(mosq->protocol == mosq_p_mqtt5 && mosq->in_packet.remaining_length > 2){ rc = packet__read_byte(&mosq->in_packet, &reason_code); if(rc) return rc; if(mosq->in_packet.remaining_length > 3){ rc = property__read_all(CMD_PUBACK, &mosq->in_packet, &properties); if(rc) return rc; } } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received %s from %s (Mid: %d, RC:%d)", type, mosq->id, mid, reason_code); /* Immediately free, we don't do anything with Reason String or User Property at the moment */ mosquitto_property_free_all(&properties); rc = db__message_delete_outgoing(db, mosq, mid, mosq_ms_wait_for_pubcomp, qos); if(rc == MOSQ_ERR_NOT_FOUND){ log__printf(mosq, MOSQ_LOG_WARNING, "Warning: Received %s from %s for an unknown packet identifier %d.", type, mosq->id, mid); return MOSQ_ERR_SUCCESS; }else{ return rc; } #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received %s (Mid: %d, RC:%d)", mosq->id, type, mid, reason_code); rc = message__delete(mosq, mid, mosq_md_out, qos); if(rc){ return rc; }else{ /* Only inform the client the message has been sent once. */ pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_publish){ mosq->in_callback = true; mosq->on_publish(mosq, mosq->userdata, mid); mosq->in_callback = false; } if(mosq->on_publish_v5){ mosq->in_callback = true; mosq->on_publish_v5(mosq, mosq->userdata, mid, reason_code, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); mosquitto_property_free_all(&properties); } pthread_mutex_lock(&mosq->msgs_out.mutex); message__release_to_inflight(mosq, mosq_md_out); pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_SUCCESS; #endif } mosquitto-1.6.9/lib/socks_mosq.c0000664000175000017500000003134613626052637015727 0ustar rogerroger/* Copyright (c) 2014-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WIN32 # include #elif __QNX__ # include # include #else # include #endif #ifdef __FreeBSD__ # include # include #endif #include "mosquitto_internal.h" #include "memory_mosq.h" #include "net_mosq.h" #include "packet_mosq.h" #include "send_mosq.h" #include "util_mosq.h" #define SOCKS_AUTH_NONE 0x00U #define SOCKS_AUTH_GSS 0x01U #define SOCKS_AUTH_USERPASS 0x02U #define SOCKS_AUTH_NO_ACCEPTABLE 0xFFU #define SOCKS_ATYPE_IP_V4 1U /* four bytes */ #define SOCKS_ATYPE_DOMAINNAME 3U /* one byte length, followed by fqdn no null, 256 max chars */ #define SOCKS_ATYPE_IP_V6 4U /* 16 bytes */ #define SOCKS_REPLY_SUCCEEDED 0x00U #define SOCKS_REPLY_GENERAL_FAILURE 0x01U #define SOCKS_REPLY_CONNECTION_NOT_ALLOWED 0x02U #define SOCKS_REPLY_NETWORK_UNREACHABLE 0x03U #define SOCKS_REPLY_HOST_UNREACHABLE 0x04U #define SOCKS_REPLY_CONNECTION_REFUSED 0x05U #define SOCKS_REPLY_TTL_EXPIRED 0x06U #define SOCKS_REPLY_COMMAND_NOT_SUPPORTED 0x07U #define SOCKS_REPLY_ADDRESS_TYPE_NOT_SUPPORTED 0x08U int mosquitto_socks5_set(struct mosquitto *mosq, const char *host, int port, const char *username, const char *password) { #ifdef WITH_SOCKS if(!mosq) return MOSQ_ERR_INVAL; if(!host || strlen(host) > 256) return MOSQ_ERR_INVAL; if(port < 1 || port > 65535) return MOSQ_ERR_INVAL; mosquitto__free(mosq->socks5_host); mosq->socks5_host = NULL; mosq->socks5_host = mosquitto__strdup(host); if(!mosq->socks5_host){ return MOSQ_ERR_NOMEM; } mosq->socks5_port = port; mosquitto__free(mosq->socks5_username); mosq->socks5_username = NULL; mosquitto__free(mosq->socks5_password); mosq->socks5_password = NULL; if(username){ mosq->socks5_username = mosquitto__strdup(username); if(!mosq->socks5_username){ return MOSQ_ERR_NOMEM; } if(password){ mosq->socks5_password = mosquitto__strdup(password); if(!mosq->socks5_password){ mosquitto__free(mosq->socks5_username); return MOSQ_ERR_NOMEM; } } } return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } #ifdef WITH_SOCKS int socks5__send(struct mosquitto *mosq) { struct mosquitto__packet *packet; int slen; int ulen, plen; struct in_addr addr_ipv4; struct in6_addr addr_ipv6; int ipv4_pton_result; int ipv6_pton_result; int state; state = mosquitto__get_state(mosq); if(state == mosq_cs_socks5_new){ packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; if(mosq->socks5_username){ packet->packet_length = 4; }else{ packet->packet_length = 3; } packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length); packet->payload[0] = 0x05; if(mosq->socks5_username){ packet->payload[1] = 2; packet->payload[2] = SOCKS_AUTH_NONE; packet->payload[3] = SOCKS_AUTH_USERPASS; }else{ packet->payload[1] = 1; packet->payload[2] = SOCKS_AUTH_NONE; } mosquitto__set_state(mosq, mosq_cs_socks5_start); mosq->in_packet.pos = 0; mosq->in_packet.packet_length = 2; mosq->in_packet.to_process = 2; mosq->in_packet.payload = mosquitto__malloc(sizeof(uint8_t)*2); if(!mosq->in_packet.payload){ mosquitto__free(packet->payload); mosquitto__free(packet); return MOSQ_ERR_NOMEM; } return packet__queue(mosq, packet); }else if(state == mosq_cs_socks5_auth_ok){ packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; ipv4_pton_result = inet_pton(AF_INET, mosq->host, &addr_ipv4); ipv6_pton_result = inet_pton(AF_INET6, mosq->host, &addr_ipv6); if(ipv4_pton_result == 1){ packet->packet_length = 10; packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length); if(!packet->payload){ mosquitto__free(packet); return MOSQ_ERR_NOMEM; } packet->payload[3] = SOCKS_ATYPE_IP_V4; memcpy(&(packet->payload[4]), (const void*)&addr_ipv4, 4); packet->payload[4+4] = MOSQ_MSB(mosq->port); packet->payload[4+4+1] = MOSQ_LSB(mosq->port); }else if(ipv6_pton_result == 1){ packet->packet_length = 22; packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length); if(!packet->payload){ mosquitto__free(packet); return MOSQ_ERR_NOMEM; } packet->payload[3] = SOCKS_ATYPE_IP_V6; memcpy(&(packet->payload[4]), (const void*)&addr_ipv6, 16); packet->payload[4+16] = MOSQ_MSB(mosq->port); packet->payload[4+16+1] = MOSQ_LSB(mosq->port); }else{ slen = strlen(mosq->host); if(slen > UCHAR_MAX){ mosquitto__free(packet); return MOSQ_ERR_NOMEM; } packet->packet_length = 7 + slen; packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length); if(!packet->payload){ mosquitto__free(packet); return MOSQ_ERR_NOMEM; } packet->payload[3] = SOCKS_ATYPE_DOMAINNAME; packet->payload[4] = (uint8_t)slen; memcpy(&(packet->payload[5]), mosq->host, slen); packet->payload[5+slen] = MOSQ_MSB(mosq->port); packet->payload[6+slen] = MOSQ_LSB(mosq->port); } packet->payload[0] = 0x05; packet->payload[1] = 0x01; packet->payload[2] = 0x00; mosquitto__set_state(mosq, mosq_cs_socks5_request); mosq->in_packet.pos = 0; mosq->in_packet.packet_length = 5; mosq->in_packet.to_process = 5; mosq->in_packet.payload = mosquitto__malloc(sizeof(uint8_t)*5); if(!mosq->in_packet.payload){ mosquitto__free(packet->payload); mosquitto__free(packet); return MOSQ_ERR_NOMEM; } return packet__queue(mosq, packet); }else if(state == mosq_cs_socks5_send_userpass){ packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; ulen = strlen(mosq->socks5_username); plen = strlen(mosq->socks5_password); packet->packet_length = 3 + ulen + plen; packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length); packet->payload[0] = 0x01; packet->payload[1] = ulen; memcpy(&(packet->payload[2]), mosq->socks5_username, ulen); packet->payload[2+ulen] = plen; memcpy(&(packet->payload[3+ulen]), mosq->socks5_password, plen); mosquitto__set_state(mosq, mosq_cs_socks5_userpass_reply); mosq->in_packet.pos = 0; mosq->in_packet.packet_length = 2; mosq->in_packet.to_process = 2; mosq->in_packet.payload = mosquitto__malloc(sizeof(uint8_t)*2); if(!mosq->in_packet.payload){ mosquitto__free(packet->payload); mosquitto__free(packet); return MOSQ_ERR_NOMEM; } return packet__queue(mosq, packet); } return MOSQ_ERR_SUCCESS; } int socks5__read(struct mosquitto *mosq) { ssize_t len; uint8_t *payload; uint8_t i; int state; state = mosquitto__get_state(mosq); if(state == mosq_cs_socks5_start){ while(mosq->in_packet.to_process > 0){ len = net__read(mosq, &(mosq->in_packet.payload[mosq->in_packet.pos]), mosq->in_packet.to_process); if(len > 0){ mosq->in_packet.pos += len; mosq->in_packet.to_process -= len; }else{ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ return MOSQ_ERR_SUCCESS; }else{ packet__cleanup(&mosq->in_packet); switch(errno){ case 0: return MOSQ_ERR_PROXY; case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } } if(mosq->in_packet.payload[0] != 5){ packet__cleanup(&mosq->in_packet); return MOSQ_ERR_PROXY; } switch(mosq->in_packet.payload[1]){ case SOCKS_AUTH_NONE: packet__cleanup(&mosq->in_packet); mosquitto__set_state(mosq, mosq_cs_socks5_auth_ok); return socks5__send(mosq); case SOCKS_AUTH_USERPASS: packet__cleanup(&mosq->in_packet); mosquitto__set_state(mosq, mosq_cs_socks5_send_userpass); return socks5__send(mosq); default: packet__cleanup(&mosq->in_packet); return MOSQ_ERR_AUTH; } }else if(state == mosq_cs_socks5_userpass_reply){ while(mosq->in_packet.to_process > 0){ len = net__read(mosq, &(mosq->in_packet.payload[mosq->in_packet.pos]), mosq->in_packet.to_process); if(len > 0){ mosq->in_packet.pos += len; mosq->in_packet.to_process -= len; }else{ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ return MOSQ_ERR_SUCCESS; }else{ packet__cleanup(&mosq->in_packet); switch(errno){ case 0: return MOSQ_ERR_PROXY; case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } } if(mosq->in_packet.payload[0] != 1){ packet__cleanup(&mosq->in_packet); return MOSQ_ERR_PROXY; } if(mosq->in_packet.payload[1] == 0){ packet__cleanup(&mosq->in_packet); mosquitto__set_state(mosq, mosq_cs_socks5_auth_ok); return socks5__send(mosq); }else{ i = mosq->in_packet.payload[1]; packet__cleanup(&mosq->in_packet); switch(i){ case SOCKS_REPLY_CONNECTION_NOT_ALLOWED: return MOSQ_ERR_AUTH; case SOCKS_REPLY_NETWORK_UNREACHABLE: case SOCKS_REPLY_HOST_UNREACHABLE: case SOCKS_REPLY_CONNECTION_REFUSED: return MOSQ_ERR_NO_CONN; case SOCKS_REPLY_GENERAL_FAILURE: case SOCKS_REPLY_TTL_EXPIRED: case SOCKS_REPLY_COMMAND_NOT_SUPPORTED: case SOCKS_REPLY_ADDRESS_TYPE_NOT_SUPPORTED: return MOSQ_ERR_PROXY; default: return MOSQ_ERR_INVAL; } return MOSQ_ERR_PROXY; } }else if(state == mosq_cs_socks5_request){ while(mosq->in_packet.to_process > 0){ len = net__read(mosq, &(mosq->in_packet.payload[mosq->in_packet.pos]), mosq->in_packet.to_process); if(len > 0){ mosq->in_packet.pos += len; mosq->in_packet.to_process -= len; }else{ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ return MOSQ_ERR_SUCCESS; }else{ packet__cleanup(&mosq->in_packet); switch(errno){ case 0: return MOSQ_ERR_PROXY; case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } } if(mosq->in_packet.packet_length == 5){ /* First part of the packet has been received, we now know what else to expect. */ if(mosq->in_packet.payload[3] == SOCKS_ATYPE_IP_V4){ mosq->in_packet.to_process += 4+2-1; /* 4 bytes IPv4, 2 bytes port, -1 byte because we've already read the first byte */ mosq->in_packet.packet_length += 4+2-1; }else if(mosq->in_packet.payload[3] == SOCKS_ATYPE_IP_V6){ mosq->in_packet.to_process += 16+2-1; /* 16 bytes IPv6, 2 bytes port, -1 byte because we've already read the first byte */ mosq->in_packet.packet_length += 16+2-1; }else if(mosq->in_packet.payload[3] == SOCKS_ATYPE_DOMAINNAME){ if(mosq->in_packet.payload[4] > 0){ mosq->in_packet.to_process += mosq->in_packet.payload[4]; mosq->in_packet.packet_length += mosq->in_packet.payload[4]; } }else{ packet__cleanup(&mosq->in_packet); return MOSQ_ERR_PROTOCOL; } payload = mosquitto__realloc(mosq->in_packet.payload, mosq->in_packet.packet_length); if(payload){ mosq->in_packet.payload = payload; }else{ packet__cleanup(&mosq->in_packet); return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } /* Entire packet is now read. */ if(mosq->in_packet.payload[0] != 5){ packet__cleanup(&mosq->in_packet); return MOSQ_ERR_PROXY; } if(mosq->in_packet.payload[1] == 0){ /* Auth passed */ packet__cleanup(&mosq->in_packet); mosquitto__set_state(mosq, mosq_cs_new); if(mosq->socks5_host){ int rc = net__socket_connect_step3(mosq, mosq->host); if(rc) return rc; } return send__connect(mosq, mosq->keepalive, mosq->clean_start, NULL); }else{ i = mosq->in_packet.payload[1]; packet__cleanup(&mosq->in_packet); mosquitto__set_state(mosq, mosq_cs_socks5_new); switch(i){ case SOCKS_REPLY_CONNECTION_NOT_ALLOWED: return MOSQ_ERR_AUTH; case SOCKS_REPLY_NETWORK_UNREACHABLE: case SOCKS_REPLY_HOST_UNREACHABLE: case SOCKS_REPLY_CONNECTION_REFUSED: return MOSQ_ERR_NO_CONN; case SOCKS_REPLY_GENERAL_FAILURE: case SOCKS_REPLY_TTL_EXPIRED: case SOCKS_REPLY_COMMAND_NOT_SUPPORTED: case SOCKS_REPLY_ADDRESS_TYPE_NOT_SUPPORTED: return MOSQ_ERR_PROXY; default: return MOSQ_ERR_INVAL; } } }else{ return packet__read(mosq); } return MOSQ_ERR_SUCCESS; } #endif mosquitto-1.6.9/lib/tls_mosq.c0000664000175000017500000001126313626052637015403 0ustar rogerroger/* Copyright (c) 2013-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifdef WITH_TLS #include "config.h" #ifdef WIN32 # include # include #else # include # include # include #endif #include #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto_internal.h" #include "logging_mosq.h" #include "tls_mosq.h" extern int tls_ex_index_mosq; int mosquitto__server_certificate_verify(int preverify_ok, X509_STORE_CTX *ctx) { /* Preverify should have already checked expiry, revocation. * We need to verify the hostname. */ struct mosquitto *mosq; SSL *ssl; X509 *cert; /* Always reject if preverify_ok has failed. */ if(!preverify_ok) return 0; ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); mosq = SSL_get_ex_data(ssl, tls_ex_index_mosq); if(!mosq) return 0; if(mosq->tls_insecure == false){ if(X509_STORE_CTX_get_error_depth(ctx) == 0){ /* FIXME - use X509_check_host() etc. for sufficiently new openssl (>=1.1.x) */ cert = X509_STORE_CTX_get_current_cert(ctx); /* This is the peer certificate, all others are upwards in the chain. */ #if defined(WITH_BROKER) preverify_ok = mosquitto__verify_certificate_hostname(cert, mosq->bridge->addresses[mosq->bridge->cur_address].address); #else preverify_ok = mosquitto__verify_certificate_hostname(cert, mosq->host); #endif if (preverify_ok != 1) { log__printf(mosq, MOSQ_LOG_ERR, "Error: host name verification failed."); } return preverify_ok; }else{ return preverify_ok; } }else{ return preverify_ok; } } int mosquitto__cmp_hostname_wildcard(char *certname, const char *hostname) { int i; int len; if(!certname || !hostname){ return 1; } if(certname[0] == '*'){ if(certname[1] != '.'){ return 1; } certname += 2; len = strlen(hostname); for(i=0; itype == GEN_DNS){ #if OPENSSL_VERSION_NUMBER < 0x10100000L data = ASN1_STRING_data(nval->d.dNSName); #else data = ASN1_STRING_get0_data(nval->d.dNSName); #endif if(data && !mosquitto__cmp_hostname_wildcard((char *)data, hostname)){ sk_GENERAL_NAME_pop_free(san, GENERAL_NAME_free); return 1; } have_san_dns = true; }else if(nval->type == GEN_IPADD){ #if OPENSSL_VERSION_NUMBER < 0x10100000L data = ASN1_STRING_data(nval->d.iPAddress); #else data = ASN1_STRING_get0_data(nval->d.iPAddress); #endif if(nval->d.iPAddress->length == 4 && ipv4_ok){ if(!memcmp(ipv4_addr, data, 4)){ sk_GENERAL_NAME_pop_free(san, GENERAL_NAME_free); return 1; } }else if(nval->d.iPAddress->length == 16 && ipv6_ok){ if(!memcmp(ipv6_addr, data, 16)){ sk_GENERAL_NAME_pop_free(san, GENERAL_NAME_free); return 1; } } } } sk_GENERAL_NAME_pop_free(san, GENERAL_NAME_free); if(have_san_dns){ /* Only check CN if subjectAltName DNS entry does not exist. */ return 0; } } subj = X509_get_subject_name(cert); if(X509_NAME_get_text_by_NID(subj, NID_commonName, name, sizeof(name)) > 0){ name[sizeof(name) - 1] = '\0'; if (!mosquitto__cmp_hostname_wildcard(name, hostname)) return 1; } return 0; } #endif mosquitto-1.6.9/lib/will_mosq.h0000664000175000017500000000150413626052637015552 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef WILL_MOSQ_H #define WILL_MOSQ_H #include "mosquitto.h" #include "mosquitto_internal.h" int will__set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties); int will__clear(struct mosquitto *mosq); #endif mosquitto-1.6.9/lib/handle_suback.c0000664000175000017500000000514313626052637016325 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "util_mosq.h" int handle__suback(struct mosquitto *mosq) { uint16_t mid; uint8_t qos; int *granted_qos; int qos_count; int i = 0; int rc; mosquitto_property *properties = NULL; int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received SUBACK from %s", mosq->id); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received SUBACK", mosq->id); #endif rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc) return rc; if(mid == 0) return MOSQ_ERR_PROTOCOL; if(mosq->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_SUBACK, &mosq->in_packet, &properties); if(rc) return rc; } qos_count = mosq->in_packet.remaining_length - mosq->in_packet.pos; granted_qos = mosquitto__malloc(qos_count*sizeof(int)); if(!granted_qos) return MOSQ_ERR_NOMEM; while(mosq->in_packet.pos < mosq->in_packet.remaining_length){ rc = packet__read_byte(&mosq->in_packet, &qos); if(rc){ mosquitto__free(granted_qos); return rc; } granted_qos[i] = (int)qos; i++; } #ifdef WITH_BROKER /* Immediately free, we don't do anything with Reason String or User Property at the moment */ mosquitto_property_free_all(&properties); #else pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_subscribe){ mosq->in_callback = true; mosq->on_subscribe(mosq, mosq->userdata, mid, qos_count, granted_qos); mosq->in_callback = false; } if(mosq->on_subscribe_v5){ mosq->in_callback = true; mosq->on_subscribe_v5(mosq, mosq->userdata, mid, qos_count, granted_qos, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); mosquitto_property_free_all(&properties); #endif mosquitto__free(granted_qos); return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/util_mosq.h0000664000175000017500000000307313626052637015563 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef UTIL_MOSQ_H #define UTIL_MOSQ_H #include #include "tls_mosq.h" #include "mosquitto.h" #include "mosquitto_internal.h" #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #ifdef WITH_BROKER int mosquitto__check_keepalive(struct mosquitto_db *db, struct mosquitto *mosq); #else int mosquitto__check_keepalive(struct mosquitto *mosq); #endif uint16_t mosquitto__mid_generate(struct mosquitto *mosq); int mosquitto__set_state(struct mosquitto *mosq, enum mosquitto_client_state state); enum mosquitto_client_state mosquitto__get_state(struct mosquitto *mosq); #ifdef WITH_TLS int mosquitto__hex2bin_sha1(const char *hex, unsigned char **bin); int mosquitto__hex2bin(const char *hex, unsigned char *bin, int bin_max_len); #endif int util__random_bytes(void *bytes, int count); void util__increment_receive_quota(struct mosquitto *mosq); void util__increment_send_quota(struct mosquitto *mosq); void util__decrement_receive_quota(struct mosquitto *mosq); void util__decrement_send_quota(struct mosquitto *mosq); #endif mosquitto-1.6.9/lib/misc_mosq.h0000664000175000017500000000142413626052637015537 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MISC_MOSQ_H #define MISC_MOSQ_H #include FILE *mosquitto__fopen(const char *path, const char *mode, bool restrict_read); char *misc__trimblanks(char *str); char *fgets_extending(char **buf, int *buflen, FILE *stream); #endif mosquitto-1.6.9/lib/misc_mosq.c0000664000175000017500000000676313626052637015545 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ /* This contains general purpose utility functions that are not specific to * Mosquitto/MQTT features. */ #include "config.h" #include #include #include #include #include #ifdef WIN32 # include # include # include # include #else # include #endif FILE *mosquitto__fopen(const char *path, const char *mode, bool restrict_read) { #ifdef WIN32 char buf[4096]; int rc; rc = ExpandEnvironmentStrings(path, buf, 4096); if(rc == 0 || rc > 4096){ return NULL; }else{ if (restrict_read) { HANDLE hfile; SECURITY_ATTRIBUTES sec; EXPLICIT_ACCESS ea; PACL pacl = NULL; char username[UNLEN + 1]; int ulen = UNLEN; SECURITY_DESCRIPTOR sd; DWORD dwCreationDisposition; switch(mode[0]){ case 'a': dwCreationDisposition = OPEN_ALWAYS; break; case 'r': dwCreationDisposition = OPEN_EXISTING; break; case 'w': dwCreationDisposition = CREATE_ALWAYS; break; default: return NULL; } GetUserName(username, &ulen); if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { return NULL; } BuildExplicitAccessWithName(&ea, username, GENERIC_ALL, SET_ACCESS, NO_INHERITANCE); if (SetEntriesInAcl(1, &ea, NULL, &pacl) != ERROR_SUCCESS) { return NULL; } if (!SetSecurityDescriptorDacl(&sd, TRUE, pacl, FALSE)) { LocalFree(pacl); return NULL; } sec.nLength = sizeof(SECURITY_ATTRIBUTES); sec.bInheritHandle = FALSE; sec.lpSecurityDescriptor = &sd; hfile = CreateFile(buf, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sec, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); LocalFree(pacl); int fd = _open_osfhandle((intptr_t)hfile, 0); if (fd < 0) { return NULL; } FILE *fptr = _fdopen(fd, mode); if (!fptr) { _close(fd); return NULL; } return fptr; }else { return fopen(buf, mode); } } #else if (restrict_read) { FILE *fptr; mode_t old_mask; old_mask = umask(0077); fptr = fopen(path, mode); umask(old_mask); return fptr; }else{ return fopen(path, mode); } #endif } char *misc__trimblanks(char *str) { char *endptr; if(str == NULL) return NULL; while(isspace(str[0])){ str++; } endptr = &str[strlen(str)-1]; while(endptr > str && isspace(endptr[0])){ endptr[0] = '\0'; endptr--; } return str; } char *fgets_extending(char **buf, int *buflen, FILE *stream) { char *rc; char endchar; int offset = 0; char *newbuf; if(stream == NULL || buf == NULL || buflen == NULL || *buflen < 1){ return NULL; } do{ rc = fgets(&((*buf)[offset]), (*buflen)-offset, stream); if(feof(stream)){ return rc; } endchar = (*buf)[strlen(*buf)-1]; if(endchar == '\n'){ return rc; } /* No EOL char found, so extend buffer */ offset = (*buflen)-1; *buflen += 1000; newbuf = realloc(*buf, *buflen); if(!newbuf){ return NULL; } *buf = newbuf; }while(1); } mosquitto-1.6.9/lib/will_mosq.c0000664000175000017500000000617013626052637015551 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" #include "will_mosq.h" int will__set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { int rc = MOSQ_ERR_SUCCESS; mosquitto_property *p; if(!mosq || !topic) return MOSQ_ERR_INVAL; if(payloadlen < 0 || payloadlen > MQTT_MAX_PAYLOAD) return MOSQ_ERR_PAYLOAD_SIZE; if(payloadlen > 0 && !payload) return MOSQ_ERR_INVAL; if(mosquitto_pub_topic_check(topic)) return MOSQ_ERR_INVAL; if(mosquitto_validate_utf8(topic, strlen(topic))) return MOSQ_ERR_MALFORMED_UTF8; if(properties){ if(mosq->protocol != mosq_p_mqtt5){ return MOSQ_ERR_NOT_SUPPORTED; } p = properties; while(p){ rc = mosquitto_property_check_command(CMD_WILL, p->identifier); if(rc) return rc; p = p->next; } } if(mosq->will){ mosquitto__free(mosq->will->msg.topic); mosquitto__free(mosq->will->msg.payload); mosquitto_property_free_all(&mosq->will->properties); mosquitto__free(mosq->will); } mosq->will = mosquitto__calloc(1, sizeof(struct mosquitto_message_all)); if(!mosq->will) return MOSQ_ERR_NOMEM; mosq->will->msg.topic = mosquitto__strdup(topic); if(!mosq->will->msg.topic){ rc = MOSQ_ERR_NOMEM; goto cleanup; } mosq->will->msg.payloadlen = payloadlen; if(mosq->will->msg.payloadlen > 0){ if(!payload){ rc = MOSQ_ERR_INVAL; goto cleanup; } mosq->will->msg.payload = mosquitto__malloc(sizeof(char)*mosq->will->msg.payloadlen); if(!mosq->will->msg.payload){ rc = MOSQ_ERR_NOMEM; goto cleanup; } memcpy(mosq->will->msg.payload, payload, payloadlen); } mosq->will->msg.qos = qos; mosq->will->msg.retain = retain; mosq->will->properties = properties; return MOSQ_ERR_SUCCESS; cleanup: if(mosq->will){ mosquitto__free(mosq->will->msg.topic); mosquitto__free(mosq->will->msg.payload); mosquitto__free(mosq->will); mosq->will = NULL; } return rc; } int will__clear(struct mosquitto *mosq) { if(!mosq->will) return MOSQ_ERR_SUCCESS; mosquitto__free(mosq->will->msg.topic); mosq->will->msg.topic = NULL; mosquitto__free(mosq->will->msg.payload); mosq->will->msg.payload = NULL; mosquitto_property_free_all(&mosq->will->properties); mosquitto__free(mosq->will); mosq->will = NULL; return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/logging_mosq.c0000664000175000017500000000254113626052637016226 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "mosquitto_internal.h" #include "mosquitto.h" #include "memory_mosq.h" int log__printf(struct mosquitto *mosq, int priority, const char *fmt, ...) { va_list va; char *s; int len; assert(mosq); assert(fmt); pthread_mutex_lock(&mosq->log_callback_mutex); if(mosq->on_log){ len = strlen(fmt) + 500; s = mosquitto__malloc(len*sizeof(char)); if(!s){ pthread_mutex_unlock(&mosq->log_callback_mutex); return MOSQ_ERR_NOMEM; } va_start(va, fmt); vsnprintf(s, len, fmt, va); va_end(va); s[len-1] = '\0'; /* Ensure string is null terminated. */ mosq->on_log(mosq, mosq->userdata, priority, s); mosquitto__free(s); } pthread_mutex_unlock(&mosq->log_callback_mutex); return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/dummypthread.h0000664000175000017500000000042213626052637016245 0ustar rogerroger#ifndef DUMMYPTHREAD_H #define DUMMYPTHREAD_H #define pthread_create(A, B, C, D) #define pthread_join(A, B) #define pthread_cancel(A) #define pthread_mutex_init(A, B) #define pthread_mutex_destroy(A) #define pthread_mutex_lock(A) #define pthread_mutex_unlock(A) #endif mosquitto-1.6.9/lib/handle_ping.c0000664000175000017500000000335313626052637016013 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" int handle__pingreq(struct mosquitto *mosq) { int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PINGREQ from %s", mosq->id); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PINGREQ", mosq->id); #endif return send__pingresp(mosq); } int handle__pingresp(struct mosquitto *mosq) { int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } mosq->ping_t = 0; /* No longer waiting for a PINGRESP. */ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PINGRESP from %s", mosq->id); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PINGRESP", mosq->id); #endif return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/util_mosq.c0000664000175000017500000001522013626052637015553 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WIN32 # include # include # include # include #else # include #endif #if !defined(WITH_TLS) && defined(__linux__) && defined(__GLIBC__) # if __GLIBC_PREREQ(2, 25) # include # define HAVE_GETRANDOM 1 # endif #endif #ifdef WITH_TLS # include # include #endif #ifdef WITH_BROKER #include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "memory_mosq.h" #include "net_mosq.h" #include "send_mosq.h" #include "time_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #ifdef WITH_WEBSOCKETS #include #endif #ifdef WITH_BROKER int mosquitto__check_keepalive(struct mosquitto_db *db, struct mosquitto *mosq) #else int mosquitto__check_keepalive(struct mosquitto *mosq) #endif { time_t next_msg_out; time_t last_msg_in; time_t now = mosquitto_time(); #ifndef WITH_BROKER int rc; #endif int state; assert(mosq); #if defined(WITH_BROKER) && defined(WITH_BRIDGE) /* Check if a lazy bridge should be timed out due to idle. */ if(mosq->bridge && mosq->bridge->start_type == bst_lazy && mosq->sock != INVALID_SOCKET && now - mosq->next_msg_out - mosq->keepalive >= mosq->bridge->idle_timeout){ log__printf(NULL, MOSQ_LOG_NOTICE, "Bridge connection %s has exceeded idle timeout, disconnecting.", mosq->id); net__socket_close(db, mosq); return MOSQ_ERR_SUCCESS; } #endif pthread_mutex_lock(&mosq->msgtime_mutex); next_msg_out = mosq->next_msg_out; last_msg_in = mosq->last_msg_in; pthread_mutex_unlock(&mosq->msgtime_mutex); if(mosq->keepalive && mosq->sock != INVALID_SOCKET && (now >= next_msg_out || now - last_msg_in >= mosq->keepalive)){ state = mosquitto__get_state(mosq); if(state == mosq_cs_active && mosq->ping_t == 0){ send__pingreq(mosq); /* Reset last msg times to give the server time to send a pingresp */ pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = now; mosq->next_msg_out = now + mosq->keepalive; pthread_mutex_unlock(&mosq->msgtime_mutex); }else{ #ifdef WITH_BROKER net__socket_close(db, mosq); #else net__socket_close(mosq); state = mosquitto__get_state(mosq); if(state == mosq_cs_disconnecting){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_KEEPALIVE; } pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_disconnect){ mosq->in_callback = true; mosq->on_disconnect(mosq, mosq->userdata, rc); mosq->in_callback = false; } if(mosq->on_disconnect_v5){ mosq->in_callback = true; mosq->on_disconnect_v5(mosq, mosq->userdata, rc, NULL); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); return rc; #endif } } return MOSQ_ERR_SUCCESS; } uint16_t mosquitto__mid_generate(struct mosquitto *mosq) { /* FIXME - this would be better with atomic increment, but this is safer * for now for a bug fix release. * * If this is changed to use atomic increment, callers of this function * will have to be aware that they may receive a 0 result, which may not be * used as a mid. */ uint16_t mid; assert(mosq); pthread_mutex_lock(&mosq->mid_mutex); mosq->last_mid++; if(mosq->last_mid == 0) mosq->last_mid++; mid = mosq->last_mid; pthread_mutex_unlock(&mosq->mid_mutex); return mid; } #ifdef WITH_TLS int mosquitto__hex2bin_sha1(const char *hex, unsigned char **bin) { unsigned char *sha, tmp[SHA_DIGEST_LENGTH]; if(mosquitto__hex2bin(hex, tmp, SHA_DIGEST_LENGTH) != SHA_DIGEST_LENGTH){ return MOSQ_ERR_INVAL; } sha = mosquitto__malloc(SHA_DIGEST_LENGTH); if(!sha){ return MOSQ_ERR_NOMEM; } memcpy(sha, tmp, SHA_DIGEST_LENGTH); *bin = sha; return MOSQ_ERR_SUCCESS; } int mosquitto__hex2bin(const char *hex, unsigned char *bin, int bin_max_len) { BIGNUM *bn = NULL; int len; int leading_zero = 0; int start = 0; size_t i = 0; /* Count the number of leading zero */ for(i=0; i bin_max_len){ BN_free(bn); return 0; } len = BN_bn2bin(bn, bin + leading_zero); BN_free(bn); return len + leading_zero; } #endif void util__increment_receive_quota(struct mosquitto *mosq) { if(mosq->msgs_in.inflight_quota < mosq->msgs_in.inflight_maximum){ mosq->msgs_in.inflight_quota++; } } void util__increment_send_quota(struct mosquitto *mosq) { if(mosq->msgs_out.inflight_quota < mosq->msgs_out.inflight_maximum){ mosq->msgs_out.inflight_quota++; } } void util__decrement_receive_quota(struct mosquitto *mosq) { if(mosq->msgs_in.inflight_quota > 0){ mosq->msgs_in.inflight_quota--; } } void util__decrement_send_quota(struct mosquitto *mosq) { if(mosq->msgs_out.inflight_quota > 0){ mosq->msgs_out.inflight_quota--; } } int util__random_bytes(void *bytes, int count) { int rc = MOSQ_ERR_UNKNOWN; #ifdef WITH_TLS if(RAND_bytes(bytes, count) == 1){ rc = MOSQ_ERR_SUCCESS; } #elif defined(HAVE_GETRANDOM) if(getrandom(bytes, count, 0) == count){ rc = MOSQ_ERR_SUCCESS; } #elif defined(WIN32) HCRYPTPROV provider; if(!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)){ return MOSQ_ERR_UNKNOWN; } if(CryptGenRandom(provider, count, bytes)){ rc = MOSQ_ERR_SUCCESS; } CryptReleaseContext(provider, 0); #else int i; for(i=0; istate_mutex); #ifdef WITH_BROKER if(mosq->state != mosq_cs_disused) #endif { mosq->state = state; } pthread_mutex_unlock(&mosq->state_mutex); return MOSQ_ERR_SUCCESS; } enum mosquitto_client_state mosquitto__get_state(struct mosquitto *mosq) { enum mosquitto_client_state state; pthread_mutex_lock(&mosq->state_mutex); state = mosq->state; pthread_mutex_unlock(&mosq->state_mutex); return state; } mosquitto-1.6.9/lib/send_connect.c0000664000175000017500000001306613626052637016207 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "logging_mosq.h" #include "memory_mosq.h" #include "mosquitto.h" #include "mosquitto_internal.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" int send__connect(struct mosquitto *mosq, uint16_t keepalive, bool clean_session, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; int payloadlen; uint8_t will = 0; uint8_t byte; int rc; uint8_t version; char *clientid, *username, *password; int headerlen; int proplen = 0, will_proplen, varbytes; mosquitto_property *local_props = NULL; uint16_t receive_maximum; assert(mosq); if(mosq->protocol == mosq_p_mqtt31 && !mosq->id) return MOSQ_ERR_PROTOCOL; #if defined(WITH_BROKER) && defined(WITH_BRIDGE) if(mosq->bridge){ clientid = mosq->bridge->remote_clientid; username = mosq->bridge->remote_username; password = mosq->bridge->remote_password; }else{ clientid = mosq->id; username = mosq->username; password = mosq->password; } #else clientid = mosq->id; username = mosq->username; password = mosq->password; #endif if(mosq->protocol == mosq_p_mqtt5){ /* Generate properties from options */ if(!mosquitto_property_read_int16(properties, MQTT_PROP_RECEIVE_MAXIMUM, &receive_maximum, false)){ rc = mosquitto_property_add_int16(&local_props, MQTT_PROP_RECEIVE_MAXIMUM, mosq->msgs_in.inflight_maximum); if(rc) return rc; }else{ mosq->msgs_in.inflight_maximum = receive_maximum; mosq->msgs_in.inflight_quota = receive_maximum; } version = MQTT_PROTOCOL_V5; headerlen = 10; proplen = 0; proplen += property__get_length_all(properties); proplen += property__get_length_all(local_props); varbytes = packet__varint_bytes(proplen); headerlen += proplen + varbytes; }else if(mosq->protocol == mosq_p_mqtt311){ version = MQTT_PROTOCOL_V311; headerlen = 10; }else if(mosq->protocol == mosq_p_mqtt31){ version = MQTT_PROTOCOL_V31; headerlen = 12; }else{ return MOSQ_ERR_INVAL; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; if(clientid){ payloadlen = 2+strlen(clientid); }else{ payloadlen = 2; } if(mosq->will){ will = 1; assert(mosq->will->msg.topic); payloadlen += 2+strlen(mosq->will->msg.topic) + 2+mosq->will->msg.payloadlen; if(mosq->protocol == mosq_p_mqtt5){ will_proplen = property__get_length_all(mosq->will->properties); varbytes = packet__varint_bytes(will_proplen); payloadlen += will_proplen + varbytes; } } /* After this check we can be sure that the username and password are * always valid for the current protocol, so there is no need to check * username before checking password. */ if(mosq->protocol == mosq_p_mqtt31 || mosq->protocol == mosq_p_mqtt311){ if(password != NULL && username == NULL){ return MOSQ_ERR_INVAL; } } if(username){ payloadlen += 2+strlen(username); } if(password){ payloadlen += 2+strlen(password); } packet->command = CMD_CONNECT; packet->remaining_length = headerlen + payloadlen; rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } /* Variable header */ if(version == MQTT_PROTOCOL_V31){ packet__write_string(packet, PROTOCOL_NAME_v31, strlen(PROTOCOL_NAME_v31)); }else{ packet__write_string(packet, PROTOCOL_NAME, strlen(PROTOCOL_NAME)); } #if defined(WITH_BROKER) && defined(WITH_BRIDGE) if(mosq->bridge && mosq->bridge->try_private && mosq->bridge->try_private_accepted){ version |= 0x80; }else{ } #endif packet__write_byte(packet, version); byte = (clean_session&0x1)<<1; if(will){ byte = byte | ((mosq->will->msg.retain&0x1)<<5) | ((mosq->will->msg.qos&0x3)<<3) | ((will&0x1)<<2); } if(username){ byte = byte | 0x1<<7; } if(mosq->password){ byte = byte | 0x1<<6; } packet__write_byte(packet, byte); packet__write_uint16(packet, keepalive); if(mosq->protocol == mosq_p_mqtt5){ /* Write properties */ packet__write_varint(packet, proplen); property__write_all(packet, properties, false); property__write_all(packet, local_props, false); } mosquitto_property_free_all(&local_props); /* Payload */ if(clientid){ packet__write_string(packet, clientid, strlen(clientid)); }else{ packet__write_uint16(packet, 0); } if(will){ if(mosq->protocol == mosq_p_mqtt5){ /* Write will properties */ property__write_all(packet, mosq->will->properties, true); } packet__write_string(packet, mosq->will->msg.topic, strlen(mosq->will->msg.topic)); packet__write_string(packet, (const char *)mosq->will->msg.payload, mosq->will->msg.payloadlen); } if(username){ packet__write_string(packet, username, strlen(username)); } if(password){ packet__write_string(packet, password, strlen(password)); } mosq->keepalive = keepalive; #ifdef WITH_BROKER # ifdef WITH_BRIDGE log__printf(mosq, MOSQ_LOG_DEBUG, "Bridge %s sending CONNECT", clientid); # endif #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending CONNECT", clientid); #endif return packet__queue(mosq, packet); } mosquitto-1.6.9/lib/handle_pubrel.c0000664000175000017500000000644513626052637016354 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" int handle__pubrel(struct mosquitto_db *db, struct mosquitto *mosq) { uint8_t reason_code; uint16_t mid; #ifndef WITH_BROKER struct mosquitto_message_all *message = NULL; #endif int rc; mosquitto_property *properties = NULL; int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } if(mosq->protocol != mosq_p_mqtt31){ if((mosq->in_packet.command&0x0F) != 0x02){ return MOSQ_ERR_PROTOCOL; } } rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc) return rc; if(mid == 0) return MOSQ_ERR_PROTOCOL; if(mosq->protocol == mosq_p_mqtt5 && mosq->in_packet.remaining_length > 2){ rc = packet__read_byte(&mosq->in_packet, &reason_code); if(rc) return rc; if(mosq->in_packet.remaining_length > 3){ rc = property__read_all(CMD_PUBREL, &mosq->in_packet, &properties); if(rc) return rc; } } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PUBREL from %s (Mid: %d)", mosq->id, mid); /* Immediately free, we don't do anything with Reason String or User Property at the moment */ mosquitto_property_free_all(&properties); rc = db__message_release_incoming(db, mosq, mid); if(rc == MOSQ_ERR_NOT_FOUND){ /* Message not found. Still send a PUBCOMP anyway because this could be * due to a repeated PUBREL after a client has reconnected. */ }else if(rc != MOSQ_ERR_SUCCESS){ return rc; } rc = send__pubcomp(mosq, mid); if(rc) return rc; #else UNUSED(db); log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PUBREL (Mid: %d)", mosq->id, mid); rc = send__pubcomp(mosq, mid); if(rc){ message__remove(mosq, mid, mosq_md_in, &message, 2); return rc; } rc = message__remove(mosq, mid, mosq_md_in, &message, 2); if(rc){ return rc; }else{ /* Only pass the message on if we have removed it from the queue - this * prevents multiple callbacks for the same message. */ pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_message){ mosq->in_callback = true; mosq->on_message(mosq, mosq->userdata, &message->msg); mosq->in_callback = false; } if(mosq->on_message_v5){ mosq->in_callback = true; mosq->on_message_v5(mosq, mosq->userdata, &message->msg, message->properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); mosquitto_property_free_all(&properties); message__cleanup(&message); } #endif return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/time_mosq.h0000664000175000017500000000115313626052637015541 0ustar rogerroger/* Copyright (c) 2013-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef TIME_MOSQ_H #define TIME_MOSQ_H time_t mosquitto_time(void); #endif mosquitto-1.6.9/lib/send_mosq.c0000664000175000017500000001203113626052637015524 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # include "sys_tree.h" #else # define G_PUB_BYTES_SENT_INC(A) #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "time_mosq.h" #include "util_mosq.h" int send__pingreq(struct mosquitto *mosq) { int rc; assert(mosq); #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PINGREQ to %s", mosq->id); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PINGREQ", mosq->id); #endif rc = send__simple_command(mosq, CMD_PINGREQ); if(rc == MOSQ_ERR_SUCCESS){ mosq->ping_t = mosquitto_time(); } return rc; } int send__pingresp(struct mosquitto *mosq) { #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PINGRESP to %s", mosq->id); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PINGRESP", mosq->id); #endif return send__simple_command(mosq, CMD_PINGRESP); } int send__puback(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code) { #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PUBACK to %s (m%d, rc%d)", mosq->id, mid, reason_code); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBACK (m%d, rc%d)", mosq->id, mid, reason_code); #endif util__increment_receive_quota(mosq); /* We don't use Reason String or User Property yet. */ return send__command_with_mid(mosq, CMD_PUBACK, mid, false, reason_code, NULL); } int send__pubcomp(struct mosquitto *mosq, uint16_t mid) { #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PUBCOMP to %s (m%d)", mosq->id, mid); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBCOMP (m%d)", mosq->id, mid); #endif util__increment_receive_quota(mosq); /* We don't use Reason String or User Property yet. */ return send__command_with_mid(mosq, CMD_PUBCOMP, mid, false, 0, NULL); } int send__pubrec(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code) { #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PUBREC to %s (m%d, rc%d)", mosq->id, mid, reason_code); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBREC (m%d, rc%d)", mosq->id, mid, reason_code); #endif if(reason_code >= 0x80 && mosq->protocol == mosq_p_mqtt5){ util__increment_receive_quota(mosq); } /* We don't use Reason String or User Property yet. */ return send__command_with_mid(mosq, CMD_PUBREC, mid, false, reason_code, NULL); } int send__pubrel(struct mosquitto *mosq, uint16_t mid) { #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PUBREL to %s (m%d)", mosq->id, mid); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBREL (m%d)", mosq->id, mid); #endif /* We don't use Reason String or User Property yet. */ return send__command_with_mid(mosq, CMD_PUBREL|2, mid, false, 0, NULL); } /* For PUBACK, PUBCOMP, PUBREC, and PUBREL */ int send__command_with_mid(struct mosquitto *mosq, uint8_t command, uint16_t mid, bool dup, uint8_t reason_code, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; int rc; int proplen, varbytes; assert(mosq); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = command; if(dup){ packet->command |= 8; } packet->remaining_length = 2; if(mosq->protocol == mosq_p_mqtt5){ if(reason_code != 0 || properties){ packet->remaining_length += 1; } if(properties){ proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); packet->remaining_length += varbytes + proplen; } } rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } packet__write_uint16(packet, mid); if(mosq->protocol == mosq_p_mqtt5){ if(reason_code != 0 || properties){ packet__write_byte(packet, reason_code); } if(properties){ property__write_all(packet, properties, true); } } return packet__queue(mosq, packet); } /* For DISCONNECT, PINGREQ and PINGRESP */ int send__simple_command(struct mosquitto *mosq, uint8_t command) { struct mosquitto__packet *packet = NULL; int rc; assert(mosq); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = command; packet->remaining_length = 0; rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } return packet__queue(mosq, packet); } mosquitto-1.6.9/lib/memory_mosq.c0000664000175000017500000000557613626052637016123 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "memory_mosq.h" #ifdef REAL_WITH_MEMORY_TRACKING # if defined(__APPLE__) # include # define malloc_usable_size malloc_size # elif defined(__FreeBSD__) # include # else # include # endif #endif #ifdef REAL_WITH_MEMORY_TRACKING static unsigned long memcount = 0; static unsigned long max_memcount = 0; #endif #ifdef WITH_BROKER static size_t mem_limit = 0; void memory__set_limit(size_t lim) { mem_limit = lim; } #endif void *mosquitto__calloc(size_t nmemb, size_t size) { #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + size > mem_limit){ return NULL; } #endif void *mem = calloc(nmemb, size); #ifdef REAL_WITH_MEMORY_TRACKING if(mem){ memcount += malloc_usable_size(mem); if(memcount > max_memcount){ max_memcount = memcount; } } #endif return mem; } void mosquitto__free(void *mem) { #ifdef REAL_WITH_MEMORY_TRACKING if(!mem){ return; } memcount -= malloc_usable_size(mem); #endif free(mem); } void *mosquitto__malloc(size_t size) { #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + size > mem_limit){ return NULL; } #endif void *mem = malloc(size); #ifdef REAL_WITH_MEMORY_TRACKING if(mem){ memcount += malloc_usable_size(mem); if(memcount > max_memcount){ max_memcount = memcount; } } #endif return mem; } #ifdef REAL_WITH_MEMORY_TRACKING unsigned long mosquitto__memory_used(void) { return memcount; } unsigned long mosquitto__max_memory_used(void) { return max_memcount; } #endif void *mosquitto__realloc(void *ptr, size_t size) { #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + size > mem_limit){ return NULL; } #endif void *mem; #ifdef REAL_WITH_MEMORY_TRACKING if(ptr){ memcount -= malloc_usable_size(ptr); } #endif mem = realloc(ptr, size); #ifdef REAL_WITH_MEMORY_TRACKING if(mem){ memcount += malloc_usable_size(mem); if(memcount > max_memcount){ max_memcount = memcount; } } #endif return mem; } char *mosquitto__strdup(const char *s) { #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + strlen(s) > mem_limit){ return NULL; } #endif char *str = strdup(s); #ifdef REAL_WITH_MEMORY_TRACKING if(str){ memcount += malloc_usable_size(str); if(memcount > max_memcount){ max_memcount = memcount; } } #endif return str; } mosquitto-1.6.9/lib/send_publish.c0000664000175000017500000001526313626052637016225 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # include "sys_tree.h" #else # define G_PUB_BYTES_SENT_INC(A) #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" int send__publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { #ifdef WITH_BROKER size_t len; #ifdef WITH_BRIDGE int i; struct mosquitto__bridge_topic *cur_topic; bool match; int rc; char *mapped_topic = NULL; char *topic_temp = NULL; #endif #endif assert(mosq); #if defined(WITH_BROKER) && defined(WITH_WEBSOCKETS) if(mosq->sock == INVALID_SOCKET && !mosq->wsi) return MOSQ_ERR_NO_CONN; #else if(mosq->sock == INVALID_SOCKET) return MOSQ_ERR_NO_CONN; #endif #ifdef WITH_BROKER if(mosq->listener && mosq->listener->mount_point){ len = strlen(mosq->listener->mount_point); if(len < strlen(topic)){ topic += len; }else{ /* Invalid topic string. Should never happen, but silently swallow the message anyway. */ return MOSQ_ERR_SUCCESS; } } #ifdef WITH_BRIDGE if(mosq->bridge && mosq->bridge->topics && mosq->bridge->topic_remapping){ for(i=0; ibridge->topic_count; i++){ cur_topic = &mosq->bridge->topics[i]; if((cur_topic->direction == bd_both || cur_topic->direction == bd_out) && (cur_topic->remote_prefix || cur_topic->local_prefix)){ /* Topic mapping required on this topic if the message matches */ rc = mosquitto_topic_matches_sub(cur_topic->local_topic, topic, &match); if(rc){ return rc; } if(match){ mapped_topic = mosquitto__strdup(topic); if(!mapped_topic) return MOSQ_ERR_NOMEM; if(cur_topic->local_prefix){ /* This prefix needs removing. */ if(!strncmp(cur_topic->local_prefix, mapped_topic, strlen(cur_topic->local_prefix))){ topic_temp = mosquitto__strdup(mapped_topic+strlen(cur_topic->local_prefix)); mosquitto__free(mapped_topic); if(!topic_temp){ return MOSQ_ERR_NOMEM; } mapped_topic = topic_temp; } } if(cur_topic->remote_prefix){ /* This prefix needs adding. */ len = strlen(mapped_topic) + strlen(cur_topic->remote_prefix)+1; topic_temp = mosquitto__malloc(len+1); if(!topic_temp){ mosquitto__free(mapped_topic); return MOSQ_ERR_NOMEM; } snprintf(topic_temp, len, "%s%s", cur_topic->remote_prefix, mapped_topic); topic_temp[len] = '\0'; mosquitto__free(mapped_topic); mapped_topic = topic_temp; } log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PUBLISH to %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", mosq->id, dup, qos, retain, mid, mapped_topic, (long)payloadlen); G_PUB_BYTES_SENT_INC(payloadlen); rc = send__real_publish(mosq, mid, mapped_topic, payloadlen, payload, qos, retain, dup, cmsg_props, store_props, expiry_interval); mosquitto__free(mapped_topic); return rc; } } } } #endif log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PUBLISH to %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", mosq->id, dup, qos, retain, mid, topic, (long)payloadlen); G_PUB_BYTES_SENT_INC(payloadlen); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBLISH (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", mosq->id, dup, qos, retain, mid, topic, (long)payloadlen); #endif return send__real_publish(mosq, mid, topic, payloadlen, payload, qos, retain, dup, cmsg_props, store_props, expiry_interval); } int send__real_publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { struct mosquitto__packet *packet = NULL; int packetlen; int proplen = 0, varbytes; int rc; mosquitto_property expiry_prop; assert(mosq); if(topic){ packetlen = 2+strlen(topic) + payloadlen; }else{ packetlen = 2 + payloadlen; } if(qos > 0) packetlen += 2; /* For message id */ if(mosq->protocol == mosq_p_mqtt5){ proplen = 0; proplen += property__get_length_all(cmsg_props); proplen += property__get_length_all(store_props); if(expiry_interval > 0){ expiry_prop.next = NULL; expiry_prop.value.i32 = expiry_interval; expiry_prop.identifier = MQTT_PROP_MESSAGE_EXPIRY_INTERVAL; expiry_prop.client_generated = false; proplen += property__get_length_all(&expiry_prop); } varbytes = packet__varint_bytes(proplen); if(varbytes > 4){ /* FIXME - Properties too big, don't publish any - should remove some first really */ cmsg_props = NULL; store_props = NULL; expiry_interval = 0; }else{ packetlen += proplen + varbytes; } } if(packet__check_oversize(mosq, packetlen)){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_NOTICE, "Dropping too large outgoing PUBLISH for %s (%d bytes)", mosq->id, packetlen); #else log__printf(NULL, MOSQ_LOG_NOTICE, "Dropping too large outgoing PUBLISH (%d bytes)", packetlen); #endif return MOSQ_ERR_OVERSIZE_PACKET; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->mid = mid; packet->command = CMD_PUBLISH | ((dup&0x1)<<3) | (qos<<1) | retain; packet->remaining_length = packetlen; rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } /* Variable header (topic string) */ if(topic){ packet__write_string(packet, topic, strlen(topic)); }else{ packet__write_uint16(packet, 0); } if(qos > 0){ packet__write_uint16(packet, mid); } if(mosq->protocol == mosq_p_mqtt5){ packet__write_varint(packet, proplen); property__write_all(packet, cmsg_props, false); property__write_all(packet, store_props, false); if(expiry_interval > 0){ property__write_all(packet, &expiry_prop, false); } } /* Payload */ if(payloadlen){ packet__write_bytes(packet, payload, payloadlen); } return packet__queue(mosq, packet); } mosquitto-1.6.9/lib/logging_mosq.h0000664000175000017500000000127013626052637016231 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef LOGGING_MOSQ_H #define LOGGING_MOSQ_H #include "mosquitto.h" int log__printf(struct mosquitto *mosq, int priority, const char *fmt, ...); #endif mosquitto-1.6.9/lib/handle_auth.c0000664000175000017500000000243613626052637016020 0ustar rogerroger/* Copyright (c) 2018-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "logging_mosq.h" #include "mosquitto_internal.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" int handle__auth(struct mosquitto *mosq) { int rc = 0; uint8_t reason_code; mosquitto_property *properties = NULL; if(!mosq) return MOSQ_ERR_INVAL; log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received AUTH", mosq->id); if(mosq->protocol != mosq_p_mqtt5){ return MOSQ_ERR_PROTOCOL; } if(packet__read_byte(&mosq->in_packet, &reason_code)) return 1; rc = property__read_all(CMD_AUTH, &mosq->in_packet, &properties); if(rc) return rc; mosquitto_property_free_all(&properties); /* FIXME - TEMPORARY UNTIL PROPERTIES PROCESSED */ return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/packet_mosq.h0000664000175000017500000000437413626052637016062 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef PACKET_MOSQ_H #define PACKET_MOSQ_H #include "mosquitto_internal.h" #include "mosquitto.h" #ifdef WITH_BROKER struct mosquitto_db; #endif int packet__alloc(struct mosquitto__packet *packet); void packet__cleanup(struct mosquitto__packet *packet); void packet__cleanup_all(struct mosquitto *mosq); int packet__queue(struct mosquitto *mosq, struct mosquitto__packet *packet); int packet__check_oversize(struct mosquitto *mosq, uint32_t remaining_length); int packet__read_byte(struct mosquitto__packet *packet, uint8_t *byte); int packet__read_bytes(struct mosquitto__packet *packet, void *bytes, uint32_t count); int packet__read_binary(struct mosquitto__packet *packet, uint8_t **data, int *length); int packet__read_string(struct mosquitto__packet *packet, char **str, int *length); int packet__read_uint16(struct mosquitto__packet *packet, uint16_t *word); int packet__read_uint32(struct mosquitto__packet *packet, uint32_t *word); int packet__read_varint(struct mosquitto__packet *packet, int32_t *word, int8_t *bytes); void packet__write_byte(struct mosquitto__packet *packet, uint8_t byte); void packet__write_bytes(struct mosquitto__packet *packet, const void *bytes, uint32_t count); void packet__write_string(struct mosquitto__packet *packet, const char *str, uint16_t length); void packet__write_uint16(struct mosquitto__packet *packet, uint16_t word); void packet__write_uint32(struct mosquitto__packet *packet, uint32_t word); int packet__write_varint(struct mosquitto__packet *packet, int32_t word); int packet__varint_bytes(int32_t word); int packet__write(struct mosquitto *mosq); #ifdef WITH_BROKER int packet__read(struct mosquitto_db *db, struct mosquitto *mosq); #else int packet__read(struct mosquitto *mosq); #endif #endif mosquitto-1.6.9/lib/net_mosq_ocsp.c0000664000175000017500000001170413626052637016413 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light Copyright (c) 2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG), Dr. Lars Voelker All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Dr. Lars Voelker, BMW AG */ /* COPYRIGHT AND PERMISSION NOTICE of curl on which the ocsp code is based: Copyright (c) 1996 - 2016, Daniel Stenberg, , and many contributors, see the THANKS file. All rights reserved. Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. */ #ifdef WITH_TLS #include #include #include #include #include #include #include int mosquitto__verify_ocsp_status_cb(SSL * ssl, void *arg) { struct mosquitto *mosq = (struct mosquitto *)arg; int ocsp_status, result2, i; unsigned char *p; const unsigned char *cp; OCSP_RESPONSE *rsp = NULL; OCSP_BASICRESP *br = NULL; X509_STORE *st = NULL; STACK_OF(X509) *ch = NULL; long len = SSL_get_tlsext_status_ocsp_resp(mosq->ssl, &p); log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: SSL_get_tlsext_status_ocsp_resp returned %ld bytes", len); // the following functions expect a const pointer cp = (const unsigned char *)p; if (!cp || len <= 0) { log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: no response"); goto end; } rsp = d2i_OCSP_RESPONSE(NULL, &cp, len); if (rsp==NULL) { log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: invalid response"); goto end; } ocsp_status = OCSP_response_status(rsp); if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: invalid status: %s (%d)", OCSP_response_status_str(ocsp_status), ocsp_status); goto end; } br = OCSP_response_get1_basic(rsp); if (!br) { log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: invalid response"); goto end; } ch = SSL_get_peer_cert_chain(mosq->ssl); if (sk_X509_num(ch) <= 0) { log__printf(mosq, MOSQ_LOG_ERR, "OCSP: we did not receive certificates of the server (num: %d)", sk_X509_num(ch)); goto end; } st = SSL_CTX_get_cert_store(mosq->ssl_ctx); // Note: // Other checkers often fix problems in OpenSSL before 1.0.2a (e.g. libcurl). // For all currently supported versions of the OpenSSL project, this is not needed anymore. if ((result2=OCSP_basic_verify(br, ch, st, 0)) <= 0) { log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: response verification failed (error: %d)", result2); goto end; } for(i = 0; i < OCSP_resp_count(br); i++) { int cert_status, crl_reason; OCSP_SINGLERESP *single = NULL; ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; single = OCSP_resp_get0(br, i); if(!single) continue; cert_status = OCSP_single_get0_status(single, &crl_reason, &rev, &thisupd, &nextupd); log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: SSL certificate status: %s (%d)", OCSP_cert_status_str(cert_status), cert_status); switch(cert_status) { case V_OCSP_CERTSTATUS_GOOD: // Note: A OCSP stapling result will be accepted up to 5 minutes after it expired! if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) { log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: OCSP response has expired"); goto end; } break; case V_OCSP_CERTSTATUS_REVOKED: log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: SSL certificate revocation reason: %s (%d)", OCSP_crl_reason_str(crl_reason), crl_reason); goto end; case V_OCSP_CERTSTATUS_UNKNOWN: goto end; default: log__printf(mosq, MOSQ_LOG_DEBUG, "OCSP: SSL certificate revocation status unknown"); goto end; } } if (br!=NULL) OCSP_BASICRESP_free(br); if (rsp!=NULL) OCSP_RESPONSE_free(rsp); return 1; // OK end: if (br!=NULL) OCSP_BASICRESP_free(br); if (rsp!=NULL) OCSP_RESPONSE_free(rsp); return 0; // Not OK } #endif mosquitto-1.6.9/lib/mosquitto.h0000664000175000017500000035073413626052637015624 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_H #define MOSQUITTO_H #ifdef __cplusplus extern "C" { #endif #if defined(WIN32) && !defined(WITH_BROKER) && !defined(LIBMOSQUITTO_STATIC) # ifdef libmosquitto_EXPORTS # define libmosq_EXPORT __declspec(dllexport) # else # define libmosq_EXPORT __declspec(dllimport) # endif #else # define libmosq_EXPORT #endif #if defined(_MSC_VER) && _MSC_VER < 1900 # ifndef __cplusplus # define bool char # define true 1 # define false 0 # endif #else # ifndef __cplusplus # include # endif #endif #include #include #define LIBMOSQUITTO_MAJOR 1 #define LIBMOSQUITTO_MINOR 6 #define LIBMOSQUITTO_REVISION 9 /* LIBMOSQUITTO_VERSION_NUMBER looks like 1002001 for e.g. version 1.2.1. */ #define LIBMOSQUITTO_VERSION_NUMBER (LIBMOSQUITTO_MAJOR*1000000+LIBMOSQUITTO_MINOR*1000+LIBMOSQUITTO_REVISION) /* Log types */ #define MOSQ_LOG_NONE 0 #define MOSQ_LOG_INFO (1<<0) #define MOSQ_LOG_NOTICE (1<<1) #define MOSQ_LOG_WARNING (1<<2) #define MOSQ_LOG_ERR (1<<3) #define MOSQ_LOG_DEBUG (1<<4) #define MOSQ_LOG_SUBSCRIBE (1<<5) #define MOSQ_LOG_UNSUBSCRIBE (1<<6) #define MOSQ_LOG_WEBSOCKETS (1<<7) #define MOSQ_LOG_INTERNAL 0x80000000U #define MOSQ_LOG_ALL 0xFFFFFFFFU /* Error values */ enum mosq_err_t { MOSQ_ERR_AUTH_CONTINUE = -4, MOSQ_ERR_NO_SUBSCRIBERS = -3, MOSQ_ERR_SUB_EXISTS = -2, MOSQ_ERR_CONN_PENDING = -1, MOSQ_ERR_SUCCESS = 0, MOSQ_ERR_NOMEM = 1, MOSQ_ERR_PROTOCOL = 2, MOSQ_ERR_INVAL = 3, MOSQ_ERR_NO_CONN = 4, MOSQ_ERR_CONN_REFUSED = 5, MOSQ_ERR_NOT_FOUND = 6, MOSQ_ERR_CONN_LOST = 7, MOSQ_ERR_TLS = 8, MOSQ_ERR_PAYLOAD_SIZE = 9, MOSQ_ERR_NOT_SUPPORTED = 10, MOSQ_ERR_AUTH = 11, MOSQ_ERR_ACL_DENIED = 12, MOSQ_ERR_UNKNOWN = 13, MOSQ_ERR_ERRNO = 14, MOSQ_ERR_EAI = 15, MOSQ_ERR_PROXY = 16, MOSQ_ERR_PLUGIN_DEFER = 17, MOSQ_ERR_MALFORMED_UTF8 = 18, MOSQ_ERR_KEEPALIVE = 19, MOSQ_ERR_LOOKUP = 20, MOSQ_ERR_MALFORMED_PACKET = 21, MOSQ_ERR_DUPLICATE_PROPERTY = 22, MOSQ_ERR_TLS_HANDSHAKE = 23, MOSQ_ERR_QOS_NOT_SUPPORTED = 24, MOSQ_ERR_OVERSIZE_PACKET = 25, MOSQ_ERR_OCSP = 26, }; /* Option values */ enum mosq_opt_t { MOSQ_OPT_PROTOCOL_VERSION = 1, MOSQ_OPT_SSL_CTX = 2, MOSQ_OPT_SSL_CTX_WITH_DEFAULTS = 3, MOSQ_OPT_RECEIVE_MAXIMUM = 4, MOSQ_OPT_SEND_MAXIMUM = 5, MOSQ_OPT_TLS_KEYFORM = 6, MOSQ_OPT_TLS_ENGINE = 7, MOSQ_OPT_TLS_ENGINE_KPASS_SHA1 = 8, MOSQ_OPT_TLS_OCSP_REQUIRED = 9, MOSQ_OPT_TLS_ALPN = 10, }; /* MQTT specification restricts client ids to a maximum of 23 characters */ #define MOSQ_MQTT_ID_MAX_LENGTH 23 #define MQTT_PROTOCOL_V31 3 #define MQTT_PROTOCOL_V311 4 #define MQTT_PROTOCOL_V5 5 struct mosquitto_message{ int mid; char *topic; void *payload; int payloadlen; int qos; bool retain; }; struct mosquitto; typedef struct mqtt5__property mosquitto_property; /* * Topic: Threads * libmosquitto provides thread safe operation, with the exception of * which is not thread safe. * * If your application uses threads you must use to * tell the library this is the case, otherwise it makes some optimisations * for the single threaded case that may result in unexpected behaviour for * the multi threaded case. */ /*************************************************** * Important note * * The following functions that deal with network operations will return * MOSQ_ERR_SUCCESS on success, but this does not mean that the operation has * taken place. An attempt will be made to write the network data, but if the * socket is not available for writing at that time then the packet will not be * sent. To ensure the packet is sent, call mosquitto_loop() (which must also * be called to process incoming network data). * This is especially important when disconnecting a client that has a will. If * the broker does not receive the DISCONNECT command, it will assume that the * client has disconnected unexpectedly and send the will. * * mosquitto_connect() * mosquitto_disconnect() * mosquitto_subscribe() * mosquitto_unsubscribe() * mosquitto_publish() ***************************************************/ /* ====================================================================== * * Section: Library version, init, and cleanup * * ====================================================================== */ /* * Function: mosquitto_lib_version * * Can be used to obtain version information for the mosquitto library. * This allows the application to compare the library version against the * version it was compiled against by using the LIBMOSQUITTO_MAJOR, * LIBMOSQUITTO_MINOR and LIBMOSQUITTO_REVISION defines. * * Parameters: * major - an integer pointer. If not NULL, the major version of the * library will be returned in this variable. * minor - an integer pointer. If not NULL, the minor version of the * library will be returned in this variable. * revision - an integer pointer. If not NULL, the revision of the library will * be returned in this variable. * * Returns: * LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major, * minor and revision values. * See Also: * , */ libmosq_EXPORT int mosquitto_lib_version(int *major, int *minor, int *revision); /* * Function: mosquitto_lib_init * * Must be called before any other mosquitto functions. * * This function is *not* thread safe. * * Returns: * MOSQ_ERR_SUCCESS - always * * See Also: * , */ libmosq_EXPORT int mosquitto_lib_init(void); /* * Function: mosquitto_lib_cleanup * * Call to free resources associated with the library. * * Returns: * MOSQ_ERR_SUCCESS - always * * See Also: * , */ libmosq_EXPORT int mosquitto_lib_cleanup(void); /* ====================================================================== * * Section: Client creation, destruction, and reinitialisation * * ====================================================================== */ /* * Function: mosquitto_new * * Create a new mosquitto client instance. * * Parameters: * id - String to use as the client id. If NULL, a random client id * will be generated. If id is NULL, clean_session must be true. * clean_session - set to true to instruct the broker to clean all messages * and subscriptions on disconnect, false to instruct it to * keep them. See the man page mqtt(7) for more details. * Note that a client will never discard its own outgoing * messages on disconnect. Calling or * will cause the messages to be resent. * Use to reset a client to its * original state. * Must be set to true if the id parameter is NULL. * obj - A user pointer that will be passed as an argument to any * callbacks that are specified. * * Returns: * Pointer to a struct mosquitto on success. * NULL on failure. Interrogate errno to determine the cause for the failure: * - ENOMEM on out of memory. * - EINVAL on invalid input parameters. * * See Also: * , , */ libmosq_EXPORT struct mosquitto *mosquitto_new(const char *id, bool clean_session, void *obj); /* * Function: mosquitto_destroy * * Use to free memory associated with a mosquitto client instance. * * Parameters: * mosq - a struct mosquitto pointer to free. * * See Also: * , */ libmosq_EXPORT void mosquitto_destroy(struct mosquitto *mosq); /* * Function: mosquitto_reinitialise * * This function allows an existing mosquitto client to be reused. Call on a * mosquitto instance to close any open network connections, free memory * and reinitialise the client with the new parameters. The end result is the * same as the output of . * * Parameters: * mosq - a valid mosquitto instance. * id - string to use as the client id. If NULL, a random client id * will be generated. If id is NULL, clean_session must be true. * clean_session - set to true to instruct the broker to clean all messages * and subscriptions on disconnect, false to instruct it to * keep them. See the man page mqtt(7) for more details. * Must be set to true if the id parameter is NULL. * obj - A user pointer that will be passed as an argument to any * callbacks that are specified. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * * See Also: * , */ libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_session, void *obj); /* ====================================================================== * * Section: Will * * ====================================================================== */ /* * Function: mosquitto_will_set * * Configure will information for a mosquitto instance. By default, clients do * not have a will. This must be called before calling . * * Parameters: * mosq - a valid mosquitto instance. * topic - the topic on which to publish the will. * payloadlen - the size of the payload (bytes). Valid values are between 0 and * 268,435,455. * payload - pointer to the data to send. If payloadlen > 0 this must be a * valid memory location. * qos - integer value 0, 1 or 2 indicating the Quality of Service to be * used for the will. * retain - set to true to make the will a retained message. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8. */ libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain); /* * Function: mosquitto_will_set_v5 * * Configure will information for a mosquitto instance, with attached * properties. By default, clients do not have a will. This must be called * before calling . * * Parameters: * mosq - a valid mosquitto instance. * topic - the topic on which to publish the will. * payloadlen - the size of the payload (bytes). Valid values are between 0 and * 268,435,455. * payload - pointer to the data to send. If payloadlen > 0 this must be a * valid memory location. * qos - integer value 0, 1 or 2 indicating the Quality of Service to be * used for the will. * retain - set to true to make the will a retained message. * properties - list of MQTT 5 properties. Can be NULL. On success only, the * property list becomes the property of libmosquitto once this * function is called and will be freed by the library. The * property list must be freed by the application on error. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8. * MOSQ_ERR_NOT_SUPPORTED - if properties is not NULL and the client is not * using MQTT v5 * MOSQ_ERR_PROTOCOL - if a property is invalid for use with wills. * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. */ libmosq_EXPORT int mosquitto_will_set_v5(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties); /* * Function: mosquitto_will_clear * * Remove a previously configured will. This must be called before calling * . * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. */ libmosq_EXPORT int mosquitto_will_clear(struct mosquitto *mosq); /* ====================================================================== * * Section: Username and password * * ====================================================================== */ /* * Function: mosquitto_username_pw_set * * Configure username and password for a mosquitto instance. By default, no * username or password will be sent. For v3.1 and v3.1.1 clients, if username * is NULL, the password argument is ignored. * * This is must be called before calling . * * Parameters: * mosq - a valid mosquitto instance. * username - the username to send as a string, or NULL to disable * authentication. * password - the password to send as a string. Set to NULL when username is * valid in order to send just a username. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. */ libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username, const char *password); /* ====================================================================== * * Section: Connecting, reconnecting, disconnecting * * ====================================================================== */ /* * Function: mosquitto_connect * * Connect to an MQTT broker. * * Parameters: * mosq - a valid mosquitto instance. * host - the hostname or ip address of the broker to connect to. * port - the network port to connect to. Usually 1883. * keepalive - the number of seconds after which the broker should send a PING * message to the client if no other messages have been exchanged * in that time. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , , , */ libmosq_EXPORT int mosquitto_connect(struct mosquitto *mosq, const char *host, int port, int keepalive); /* * Function: mosquitto_connect_bind * * Connect to an MQTT broker. This extends the functionality of * by adding the bind_address parameter. Use this function * if you need to restrict network communication over a particular interface. * * Parameters: * mosq - a valid mosquitto instance. * host - the hostname or ip address of the broker to connect to. * port - the network port to connect to. Usually 1883. * keepalive - the number of seconds after which the broker should send a PING * message to the client if no other messages have been exchanged * in that time. * bind_address - the hostname or ip address of the local network interface to * bind to. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , */ libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address); /* * Function: mosquitto_connect_bind_v5 * * Connect to an MQTT broker. This extends the functionality of * by adding the bind_address parameter and MQTT v5 * properties. Use this function if you need to restrict network communication * over a particular interface. * * Use e.g. and similar to create a list of * properties, then attach them to this publish. Properties need freeing with * . * * Parameters: * mosq - a valid mosquitto instance. * host - the hostname or ip address of the broker to connect to. * port - the network port to connect to. Usually 1883. * keepalive - the number of seconds after which the broker should send a PING * message to the client if no other messages have been exchanged * in that time. * bind_address - the hostname or ip address of the local network interface to * bind to. * properties - the MQTT 5 properties for the connect (not for the Will). * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. * MOSQ_ERR_PROTOCOL - if any property is invalid for use with CONNECT. * * See Also: * , , */ libmosq_EXPORT int mosquitto_connect_bind_v5(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties); /* * Function: mosquitto_connect_async * * Connect to an MQTT broker. This is a non-blocking call. If you use * your client must use the threaded interface * . If you need to use , you must use * to connect the client. * * May be called before or after . * * Parameters: * mosq - a valid mosquitto instance. * host - the hostname or ip address of the broker to connect to. * port - the network port to connect to. Usually 1883. * keepalive - the number of seconds after which the broker should send a PING * message to the client if no other messages have been exchanged * in that time. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , , , */ libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port, int keepalive); /* * Function: mosquitto_connect_bind_async * * Connect to an MQTT broker. This is a non-blocking call. If you use * your client must use the threaded interface * . If you need to use , you must use * to connect the client. * * This extends the functionality of by adding the * bind_address parameter. Use this function if you need to restrict network * communication over a particular interface. * * May be called before or after . * * Parameters: * mosq - a valid mosquitto instance. * host - the hostname or ip address of the broker to connect to. * port - the network port to connect to. Usually 1883. * keepalive - the number of seconds after which the broker should send a PING * message to the client if no other messages have been exchanged * in that time. * bind_address - the hostname or ip address of the local network interface to * bind to. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , */ libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address); /* * Function: mosquitto_connect_srv * * Connect to an MQTT broker. * * If you set `host` to `example.com`, then this call will attempt to retrieve * the DNS SRV record for `_secure-mqtt._tcp.example.com` or * `_mqtt._tcp.example.com` to discover which actual host to connect to. * * DNS SRV support is not usually compiled in to libmosquitto, use of this call * is not recommended. * * Parameters: * mosq - a valid mosquitto instance. * host - the hostname to search for an SRV record. * keepalive - the number of seconds after which the broker should send a PING * message to the client if no other messages have been exchanged * in that time. * bind_address - the hostname or ip address of the local network interface to * bind to. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , */ libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address); /* * Function: mosquitto_reconnect * * Reconnect to a broker. * * This function provides an easy way of reconnecting to a broker after a * connection has been lost. It uses the values that were provided in the * call. It must not be called before * . * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , */ libmosq_EXPORT int mosquitto_reconnect(struct mosquitto *mosq); /* * Function: mosquitto_reconnect_async * * Reconnect to a broker. Non blocking version of . * * This function provides an easy way of reconnecting to a broker after a * connection has been lost. It uses the values that were provided in the * or calls. It must not be * called before . * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , */ libmosq_EXPORT int mosquitto_reconnect_async(struct mosquitto *mosq); /* * Function: mosquitto_disconnect * * Disconnect from the broker. * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. */ libmosq_EXPORT int mosquitto_disconnect(struct mosquitto *mosq); /* * Function: mosquitto_disconnect_v5 * * Disconnect from the broker, with attached MQTT properties. * * Use e.g. and similar to create a list of * properties, then attach them to this publish. Properties need freeing with * . * * Parameters: * mosq - a valid mosquitto instance. * reason_code - the disconnect reason code. * properties - a valid mosquitto_property list, or NULL. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. * MOSQ_ERR_PROTOCOL - if any property is invalid for use with DISCONNECT. */ libmosq_EXPORT int mosquitto_disconnect_v5(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties); /* ====================================================================== * * Section: Publishing, subscribing, unsubscribing * * ====================================================================== */ /* * Function: mosquitto_publish * * Publish a message on a given topic. * * Parameters: * mosq - a valid mosquitto instance. * mid - pointer to an int. If not NULL, the function will set this * to the message id of this particular message. This can be then * used with the publish callback to determine when the message * has been sent. * Note that although the MQTT protocol doesn't use message ids * for messages with QoS=0, libmosquitto assigns them message ids * so they can be tracked with this parameter. * topic - null terminated string of the topic to publish to. * payloadlen - the size of the payload (bytes). Valid values are between 0 and * 268,435,455. * payload - pointer to the data to send. If payloadlen > 0 this must be a * valid memory location. * qos - integer value 0, 1 or 2 indicating the Quality of Service to be * used for the message. * retain - set to true to make the message retained. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the * broker. * MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * MOSQ_ERR_QOS_NOT_SUPPORTED - if the QoS is greater than that supported by * the broker. * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. * * See Also: * */ libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain); /* * Function: mosquitto_publish_v5 * * Publish a message on a given topic, with attached MQTT properties. * * Use e.g. and similar to create a list of * properties, then attach them to this publish. Properties need freeing with * . * * Requires the mosquitto instance to be connected with MQTT 5. * * Parameters: * mosq - a valid mosquitto instance. * mid - pointer to an int. If not NULL, the function will set this * to the message id of this particular message. This can be then * used with the publish callback to determine when the message * has been sent. * Note that although the MQTT protocol doesn't use message ids * for messages with QoS=0, libmosquitto assigns them message ids * so they can be tracked with this parameter. * topic - null terminated string of the topic to publish to. * payloadlen - the size of the payload (bytes). Valid values are between 0 and * 268,435,455. * payload - pointer to the data to send. If payloadlen > 0 this must be a * valid memory location. * qos - integer value 0, 1 or 2 indicating the Quality of Service to be * used for the message. * retain - set to true to make the message retained. * properties - a valid mosquitto_property list, or NULL. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the * broker. * MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. * MOSQ_ERR_PROTOCOL - if any property is invalid for use with PUBLISH. * MOSQ_ERR_QOS_NOT_SUPPORTED - if the QoS is greater than that supported by * the broker. * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_publish_v5( struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, const mosquitto_property *properties); /* * Function: mosquitto_subscribe * * Subscribe to a topic. * * Parameters: * mosq - a valid mosquitto instance. * mid - a pointer to an int. If not NULL, the function will set this to * the message id of this particular message. This can be then used * with the subscribe callback to determine when the message has been * sent. * sub - the subscription pattern. * qos - the requested Quality of Service for this subscription. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos); /* * Function: mosquitto_subscribe_v5 * * Subscribe to a topic, with attached MQTT properties. * * Use e.g. and similar to create a list of * properties, then attach them to this publish. Properties need freeing with * . * * Requires the mosquitto instance to be connected with MQTT 5. * * * Parameters: * mosq - a valid mosquitto instance. * mid - a pointer to an int. If not NULL, the function will set this to * the message id of this particular message. This can be then used * with the subscribe callback to determine when the message has been * sent. * sub - the subscription pattern. * qos - the requested Quality of Service for this subscription. * options - options to apply to this subscription, OR'd together. Set to 0 to * use the default options, otherwise choose from the list: * MQTT_SUB_OPT_NO_LOCAL: with this option set, if this client * publishes to a topic to which it is subscribed, the * broker will not publish the message back to the * client. * MQTT_SUB_OPT_RETAIN_AS_PUBLISHED: with this option set, messages * published for this subscription will keep the * retain flag as was set by the publishing client. * The default behaviour without this option set has * the retain flag indicating whether a message is * fresh/stale. * MQTT_SUB_OPT_SEND_RETAIN_ALWAYS: with this option set, * pre-existing retained messages are sent as soon as * the subscription is made, even if the subscription * already exists. This is the default behaviour, so * it is not necessary to set this option. * MQTT_SUB_OPT_SEND_RETAIN_NEW: with this option set, pre-existing * retained messages for this subscription will be * sent when the subscription is made, but only if the * subscription does not already exist. * MQTT_SUB_OPT_SEND_RETAIN_NEVER: with this option set, * pre-existing retained messages will never be sent * for this subscription. * properties - a valid mosquitto_property list, or NULL. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. * MOSQ_ERR_PROTOCOL - if any property is invalid for use with SUBSCRIBE. * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_subscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, int qos, int options, const mosquitto_property *properties); /* * Function: mosquitto_subscribe_multiple * * Subscribe to multiple topics. * * Parameters: * mosq - a valid mosquitto instance. * mid - a pointer to an int. If not NULL, the function will set this to * the message id of this particular message. This can be then used * with the subscribe callback to determine when the message has been * sent. * sub_count - the count of subscriptions to be made * sub - array of sub_count pointers, each pointing to a subscription string. * The "char *const *const" datatype ensures that neither the array of * pointers nor the strings that they point to are mutable. If you aren't * familiar with this, just think of it as a safer "char **", * equivalent to "const char *" for a simple string pointer. * qos - the requested Quality of Service for each subscription. * options - options to apply to this subscription, OR'd together. This * argument is not used for MQTT v3 susbcriptions. Set to 0 to use * the default options, otherwise choose from the list: * MQTT_SUB_OPT_NO_LOCAL: with this option set, if this client * publishes to a topic to which it is subscribed, the * broker will not publish the message back to the * client. * MQTT_SUB_OPT_RETAIN_AS_PUBLISHED: with this option set, messages * published for this subscription will keep the * retain flag as was set by the publishing client. * The default behaviour without this option set has * the retain flag indicating whether a message is * fresh/stale. * MQTT_SUB_OPT_SEND_RETAIN_ALWAYS: with this option set, * pre-existing retained messages are sent as soon as * the subscription is made, even if the subscription * already exists. This is the default behaviour, so * it is not necessary to set this option. * MQTT_SUB_OPT_SEND_RETAIN_NEW: with this option set, pre-existing * retained messages for this subscription will be * sent when the subscription is made, but only if the * subscription does not already exist. * MQTT_SUB_OPT_SEND_RETAIN_NEVER: with this option set, * pre-existing retained messages will never be sent * for this subscription. * properties - a valid mosquitto_property list, or NULL. Only used with MQTT * v5 clients. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_MALFORMED_UTF8 - if a topic is not valid UTF-8 * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_subscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, int qos, int options, const mosquitto_property *properties); /* * Function: mosquitto_unsubscribe * * Unsubscribe from a topic. * * Parameters: * mosq - a valid mosquitto instance. * mid - a pointer to an int. If not NULL, the function will set this to * the message id of this particular message. This can be then used * with the unsubscribe callback to determine when the message has been * sent. * sub - the unsubscription pattern. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub); /* * Function: mosquitto_unsubscribe_v5 * * Unsubscribe from a topic, with attached MQTT properties. * * Use e.g. and similar to create a list of * properties, then attach them to this publish. Properties need freeing with * . * * Parameters: * mosq - a valid mosquitto instance. * mid - a pointer to an int. If not NULL, the function will set this to * the message id of this particular message. This can be then used * with the unsubscribe callback to determine when the message has been * sent. * sub - the unsubscription pattern. * properties - a valid mosquitto_property list, or NULL. Only used with MQTT * v5 clients. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. * MOSQ_ERR_PROTOCOL - if any property is invalid for use with UNSUBSCRIBE. * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_unsubscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, const mosquitto_property *properties); /* * Function: mosquitto_unsubscribe_multiple * * Unsubscribe from multiple topics. * * Parameters: * mosq - a valid mosquitto instance. * mid - a pointer to an int. If not NULL, the function will set this to * the message id of this particular message. This can be then used * with the subscribe callback to determine when the message has been * sent. * sub_count - the count of unsubscriptions to be made * sub - array of sub_count pointers, each pointing to an unsubscription string. * The "char *const *const" datatype ensures that neither the array of * pointers nor the strings that they point to are mutable. If you aren't * familiar with this, just think of it as a safer "char **", * equivalent to "const char *" for a simple string pointer. * properties - a valid mosquitto_property list, or NULL. Only used with MQTT * v5 clients. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_MALFORMED_UTF8 - if a topic is not valid UTF-8 * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than * supported by the broker. */ libmosq_EXPORT int mosquitto_unsubscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, const mosquitto_property *properties); /* ====================================================================== * * Section: Struct mosquitto_message helper functions * * ====================================================================== */ /* * Function: mosquitto_message_copy * * Copy the contents of a mosquitto message to another message. * Useful for preserving a message received in the on_message() callback. * * Parameters: * dst - a pointer to a valid mosquitto_message struct to copy to. * src - a pointer to a valid mosquitto_message struct to copy from. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * * See Also: * */ libmosq_EXPORT int mosquitto_message_copy(struct mosquitto_message *dst, const struct mosquitto_message *src); /* * Function: mosquitto_message_free * * Completely free a mosquitto_message struct. * * Parameters: * message - pointer to a mosquitto_message pointer to free. * * See Also: * , */ libmosq_EXPORT void mosquitto_message_free(struct mosquitto_message **message); /* * Function: mosquitto_message_free_contents * * Free a mosquitto_message struct contents, leaving the struct unaffected. * * Parameters: * message - pointer to a mosquitto_message struct to free its contents. * * See Also: * , */ libmosq_EXPORT void mosquitto_message_free_contents(struct mosquitto_message *message); /* ====================================================================== * * Section: Network loop (managed by libmosquitto) * * The internal network loop must be called at a regular interval. The two * recommended approaches are to use either or * . is a blocking call and is * suitable for the situation where you only want to handle incoming messages * in callbacks. is a non-blocking call, it creates a * separate thread to run the loop for you. Use this function when you have * other tasks you need to run at the same time as the MQTT client, e.g. * reading data from a sensor. * * ====================================================================== */ /* * Function: mosquitto_loop_forever * * This function call loop() for you in an infinite blocking loop. It is useful * for the case where you only want to run the MQTT client loop in your * program. * * It handles reconnecting in case server connection is lost. If you call * mosquitto_disconnect() in a callback it will return. * * Parameters: * mosq - a valid mosquitto instance. * timeout - Maximum number of milliseconds to wait for network activity * in the select() call before timing out. Set to 0 for instant * return. Set negative to use the default of 1000ms. * max_packets - this parameter is currently unused and should be set to 1 for * future compatibility. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the * broker. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , */ libmosq_EXPORT int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets); /* * Function: mosquitto_loop_start * * This is part of the threaded client interface. Call this once to start a new * thread to process network traffic. This provides an alternative to * repeatedly calling yourself. * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOT_SUPPORTED - if thread support is not available. * * See Also: * , , , */ libmosq_EXPORT int mosquitto_loop_start(struct mosquitto *mosq); /* * Function: mosquitto_loop_stop * * This is part of the threaded client interface. Call this once to stop the * network thread previously created with . This call * will block until the network thread finishes. For the network thread to end, * you must have previously called or have set the force * parameter to true. * * Parameters: * mosq - a valid mosquitto instance. * force - set to true to force thread cancellation. If false, * must have already been called. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOT_SUPPORTED - if thread support is not available. * * See Also: * , */ libmosq_EXPORT int mosquitto_loop_stop(struct mosquitto *mosq, bool force); /* * Function: mosquitto_loop * * The main network loop for the client. This must be called frequently * to keep communications between the client and broker working. This is * carried out by and , which * are the recommended ways of handling the network loop. You may also use this * function if you wish. It must not be called inside a callback. * * If incoming data is present it will then be processed. Outgoing commands, * from e.g. , are normally sent immediately that their * function is called, but this is not always possible. will * also attempt to send any remaining outgoing messages, which also includes * commands that are part of the flow for messages with QoS>0. * * This calls select() to monitor the client network socket. If you want to * integrate mosquitto client operation with your own select() call, use * , , and * . * * Threads: * * Parameters: * mosq - a valid mosquitto instance. * timeout - Maximum number of milliseconds to wait for network activity * in the select() call before timing out. Set to 0 for instant * return. Set negative to use the default of 1000ms. * max_packets - this parameter is currently unused and should be set to 1 for * future compatibility. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the * broker. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * See Also: * , , */ libmosq_EXPORT int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_packets); /* ====================================================================== * * Section: Network loop (for use in other event loops) * * ====================================================================== */ /* * Function: mosquitto_loop_read * * Carry out network read operations. * This should only be used if you are not using mosquitto_loop() and are * monitoring the client network socket for activity yourself. * * Parameters: * mosq - a valid mosquitto instance. * max_packets - this parameter is currently unused and should be set to 1 for * future compatibility. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the * broker. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , */ libmosq_EXPORT int mosquitto_loop_read(struct mosquitto *mosq, int max_packets); /* * Function: mosquitto_loop_write * * Carry out network write operations. * This should only be used if you are not using mosquitto_loop() and are * monitoring the client network socket for activity yourself. * * Parameters: * mosq - a valid mosquitto instance. * max_packets - this parameter is currently unused and should be set to 1 for * future compatibility. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the * broker. * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno * contains the error code, even on Windows. * Use strerror_r() where available or FormatMessage() on * Windows. * * See Also: * , , , */ libmosq_EXPORT int mosquitto_loop_write(struct mosquitto *mosq, int max_packets); /* * Function: mosquitto_loop_misc * * Carry out miscellaneous operations required as part of the network loop. * This should only be used if you are not using mosquitto_loop() and are * monitoring the client network socket for activity yourself. * * This function deals with handling PINGs and checking whether messages need * to be retried, so should be called fairly frequently, around once per second * is sufficient. * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. * * See Also: * , , */ libmosq_EXPORT int mosquitto_loop_misc(struct mosquitto *mosq); /* ====================================================================== * * Section: Network loop (helper functions) * * ====================================================================== */ /* * Function: mosquitto_socket * * Return the socket handle for a mosquitto instance. Useful if you want to * include a mosquitto client in your own select() calls. * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * The socket for the mosquitto client or -1 on failure. */ libmosq_EXPORT int mosquitto_socket(struct mosquitto *mosq); /* * Function: mosquitto_want_write * * Returns true if there is data ready to be written on the socket. * * Parameters: * mosq - a valid mosquitto instance. * * See Also: * , , */ libmosq_EXPORT bool mosquitto_want_write(struct mosquitto *mosq); /* * Function: mosquitto_threaded_set * * Used to tell the library that your application is using threads, but not * using . The library operates slightly differently when * not in threaded mode in order to simplify its operation. If you are managing * your own threads and do not use this function you will experience crashes * due to race conditions. * * When using , this is set automatically. * * Parameters: * mosq - a valid mosquitto instance. * threaded - true if your application is using threads, false otherwise. */ libmosq_EXPORT int mosquitto_threaded_set(struct mosquitto *mosq, bool threaded); /* ====================================================================== * * Section: Client options * * ====================================================================== */ /* * Function: mosquitto_opts_set * * Used to set options for the client. * * This function is deprecated, the replacement and * functions should be used instead. * * Parameters: * mosq - a valid mosquitto instance. * option - the option to set. * value - the option specific value. * * Options: * MOSQ_OPT_PROTOCOL_VERSION * Value must be an int, set to either MQTT_PROTOCOL_V31 or * MQTT_PROTOCOL_V311. Must be set before the client connects. * Defaults to MQTT_PROTOCOL_V31. * * MOSQ_OPT_SSL_CTX * Pass an openssl SSL_CTX to be used when creating TLS connections * rather than libmosquitto creating its own. This must be called * before connecting to have any effect. If you use this option, the * onus is on you to ensure that you are using secure settings. * Setting to NULL means that libmosquitto will use its own SSL_CTX * if TLS is to be used. * This option is only available for openssl 1.1.0 and higher. * * MOSQ_OPT_SSL_CTX_WITH_DEFAULTS * Value must be an int set to 1 or 0. If set to 1, then the user * specified SSL_CTX passed in using MOSQ_OPT_SSL_CTX will have the * default options applied to it. This means that you only need to * change the values that are relevant to you. If you use this * option then you must configure the TLS options as normal, i.e. * you should use to configure the cafile/capath * as a minimum. * This option is only available for openssl 1.1.0 and higher. */ libmosq_EXPORT int mosquitto_opts_set(struct mosquitto *mosq, enum mosq_opt_t option, void *value); /* * Function: mosquitto_int_option * * Used to set integer options for the client. * * Parameters: * mosq - a valid mosquitto instance. * option - the option to set. * value - the option specific value. * * Options: * MOSQ_OPT_PROTOCOL_VERSION - * Value must be set to either MQTT_PROTOCOL_V31, * MQTT_PROTOCOL_V311, or MQTT_PROTOCOL_V5. Must be set before the * client connects. Defaults to MQTT_PROTOCOL_V311. * * MOSQ_OPT_RECEIVE_MAXIMUM - * Value can be set between 1 and 65535 inclusive, and represents * the maximum number of incoming QoS 1 and QoS 2 messages that this * client wants to process at once. Defaults to 20. This option is * not valid for MQTT v3.1 or v3.1.1 clients. * Note that if the MQTT_PROP_RECEIVE_MAXIMUM property is in the * proplist passed to mosquitto_connect_v5(), then that property * will override this option. Using this option is the recommended * method however. * * MOSQ_OPT_SEND_MAXIMUM - * Value can be set between 1 and 65535 inclusive, and represents * the maximum number of outgoing QoS 1 and QoS 2 messages that this * client will attempt to have "in flight" at once. Defaults to 20. * This option is not valid for MQTT v3.1 or v3.1.1 clients. * Note that if the broker being connected to sends a * MQTT_PROP_RECEIVE_MAXIMUM property that has a lower value than * this option, then the broker provided value will be used. * * MOSQ_OPT_SSL_CTX_WITH_DEFAULTS - * If value is set to a non zero value, then the user specified * SSL_CTX passed in using MOSQ_OPT_SSL_CTX will have the default * options applied to it. This means that you only need to change * the values that are relevant to you. If you use this option then * you must configure the TLS options as normal, i.e. you should * use to configure the cafile/capath as a * minimum. * This option is only available for openssl 1.1.0 and higher. * * MOSQ_OPT_TLS_OCSP_REQUIRED - * Set whether OCSP checking on TLS connections is required. Set to * 1 to enable checking, or 0 (the default) for no checking. */ libmosq_EXPORT int mosquitto_int_option(struct mosquitto *mosq, enum mosq_opt_t option, int value); /* * Function: mosquitto_void_option * * Used to set void* options for the client. * * Parameters: * mosq - a valid mosquitto instance. * option - the option to set. * value - the option specific value. * * Options: * MOSQ_OPT_SSL_CTX - * Pass an openssl SSL_CTX to be used when creating TLS connections * rather than libmosquitto creating its own. This must be called * before connecting to have any effect. If you use this option, the * onus is on you to ensure that you are using secure settings. * Setting to NULL means that libmosquitto will use its own SSL_CTX * if TLS is to be used. * This option is only available for openssl 1.1.0 and higher. */ libmosq_EXPORT int mosquitto_void_option(struct mosquitto *mosq, enum mosq_opt_t option, void *value); /* * Function: mosquitto_reconnect_delay_set * * Control the behaviour of the client when it has unexpectedly disconnected in * or after . The default * behaviour if this function is not used is to repeatedly attempt to reconnect * with a delay of 1 second until the connection succeeds. * * Use reconnect_delay parameter to change the delay between successive * reconnection attempts. You may also enable exponential backoff of the time * between reconnections by setting reconnect_exponential_backoff to true and * set an upper bound on the delay with reconnect_delay_max. * * Example 1: * delay=2, delay_max=10, exponential_backoff=False * Delays would be: 2, 4, 6, 8, 10, 10, ... * * Example 2: * delay=3, delay_max=30, exponential_backoff=True * Delays would be: 3, 6, 12, 24, 30, 30, ... * * Parameters: * mosq - a valid mosquitto instance. * reconnect_delay - the number of seconds to wait between * reconnects. * reconnect_delay_max - the maximum number of seconds to wait * between reconnects. * reconnect_exponential_backoff - use exponential backoff between * reconnect attempts. Set to true to enable * exponential backoff. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. */ libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff); /* * Function: mosquitto_max_inflight_messages_set * * This function is deprected. Use the function with the * MOSQ_OPT_SEND_MAXIMUM option instead. * * Set the number of QoS 1 and 2 messages that can be "in flight" at one time. * An in flight message is part way through its delivery flow. Attempts to send * further messages with will result in the messages being * queued until the number of in flight messages reduces. * * A higher number here results in greater message throughput, but if set * higher than the maximum in flight messages on the broker may lead to * delays in the messages being acknowledged. * * Set to 0 for no maximum. * * Parameters: * mosq - a valid mosquitto instance. * max_inflight_messages - the maximum number of inflight messages. Defaults * to 20. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. */ libmosq_EXPORT int mosquitto_max_inflight_messages_set(struct mosquitto *mosq, unsigned int max_inflight_messages); /* * Function: mosquitto_message_retry_set * * This function now has no effect. */ libmosq_EXPORT void mosquitto_message_retry_set(struct mosquitto *mosq, unsigned int message_retry); /* * Function: mosquitto_user_data_set * * When is called, the pointer given as the "obj" parameter * will be passed to the callbacks as user data. The * function allows this obj parameter to be updated at any time. This function * will not modify the memory pointed to by the current user data pointer. If * it is dynamically allocated memory you must free it yourself. * * Parameters: * mosq - a valid mosquitto instance. * obj - A user pointer that will be passed as an argument to any callbacks * that are specified. */ libmosq_EXPORT void mosquitto_user_data_set(struct mosquitto *mosq, void *obj); /* Function: mosquitto_userdata * * Retrieve the "userdata" variable for a mosquitto client. * * Parameters: * mosq - a valid mosquitto instance. * * Returns: * A pointer to the userdata member variable. */ libmosq_EXPORT void *mosquitto_userdata(struct mosquitto *mosq); /* ====================================================================== * * Section: TLS support * * ====================================================================== */ /* * Function: mosquitto_tls_set * * Configure the client for certificate based SSL/TLS support. Must be called * before . * * Cannot be used in conjunction with . * * Define the Certificate Authority certificates to be trusted (ie. the server * certificate must be signed with one of these certificates) using cafile. * * If the server you are connecting to requires clients to provide a * certificate, define certfile and keyfile with your client certificate and * private key. If your private key is encrypted, provide a password callback * function or you will have to enter the password at the command line. * * Parameters: * mosq - a valid mosquitto instance. * cafile - path to a file containing the PEM encoded trusted CA * certificate files. Either cafile or capath must not be NULL. * capath - path to a directory containing the PEM encoded trusted CA * certificate files. See mosquitto.conf for more details on * configuring this directory. Either cafile or capath must not * be NULL. * certfile - path to a file containing the PEM encoded certificate file * for this client. If NULL, keyfile must also be NULL and no * client certificate will be used. * keyfile - path to a file containing the PEM encoded private key for * this client. If NULL, certfile must also be NULL and no * client certificate will be used. * pw_callback - if keyfile is encrypted, set pw_callback to allow your client * to pass the correct password for decryption. If set to NULL, * the password must be entered on the command line. * Your callback must write the password into "buf", which is * "size" bytes long. The return value must be the length of the * password. "userdata" will be set to the calling mosquitto * instance. The mosquitto userdata member variable can be * retrieved using . * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * * See Also: * , , * , */ libmosq_EXPORT int mosquitto_tls_set(struct mosquitto *mosq, const char *cafile, const char *capath, const char *certfile, const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)); /* * Function: mosquitto_tls_insecure_set * * Configure verification of the server hostname in the server certificate. If * value is set to true, it is impossible to guarantee that the host you are * connecting to is not impersonating your server. This can be useful in * initial server testing, but makes it possible for a malicious third party to * impersonate your server through DNS spoofing, for example. * Do not use this function in a real system. Setting value to true makes the * connection encryption pointless. * Must be called before . * * Parameters: * mosq - a valid mosquitto instance. * value - if set to false, the default, certificate hostname checking is * performed. If set to true, no hostname checking is performed and * the connection is insecure. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * * See Also: * */ libmosq_EXPORT int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value); /* * Function: mosquitto_tls_opts_set * * Set advanced SSL/TLS options. Must be called before . * * Parameters: * mosq - a valid mosquitto instance. * cert_reqs - an integer defining the verification requirements the client * will impose on the server. This can be one of: * * SSL_VERIFY_NONE (0): the server will not be verified in any way. * * SSL_VERIFY_PEER (1): the server certificate will be verified * and the connection aborted if the verification fails. * The default and recommended value is SSL_VERIFY_PEER. Using * SSL_VERIFY_NONE provides no security. * tls_version - the version of the SSL/TLS protocol to use as a string. If NULL, * the default value is used. The default value and the * available values depend on the version of openssl that the * library was compiled against. For openssl >= 1.0.1, the * available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2 * as the default. For openssl < 1.0.1, only tlsv1 is available. * ciphers - a string describing the ciphers available for use. See the * "openssl ciphers" tool for more information. If NULL, the * default ciphers will be used. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * * See Also: * */ libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers); /* * Function: mosquitto_tls_psk_set * * Configure the client for pre-shared-key based TLS support. Must be called * before . * * Cannot be used in conjunction with . * * Parameters: * mosq - a valid mosquitto instance. * psk - the pre-shared-key in hex format with no leading "0x". * identity - the identity of this client. May be used as the username * depending on the server settings. * ciphers - a string describing the PSK ciphers available for use. See the * "openssl ciphers" tool for more information. If NULL, the * default ciphers will be used. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * * See Also: * */ libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers); /* ====================================================================== * * Section: Callbacks * * ====================================================================== */ /* * Function: mosquitto_connect_callback_set * * Set the connect callback. This is called when the broker sends a CONNACK * message in response to a connection. * * Parameters: * mosq - a valid mosquitto instance. * on_connect - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int rc) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * rc - the return code of the connection response, one of: * * * 0 - success * * 1 - connection refused (unacceptable protocol version) * * 2 - connection refused (identifier rejected) * * 3 - connection refused (broker unavailable) * * 4-255 - reserved for future use */ libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int)); /* * Function: mosquitto_connect_with_flags_callback_set * * Set the connect callback. This is called when the broker sends a CONNACK * message in response to a connection. * * Parameters: * mosq - a valid mosquitto instance. * on_connect - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int rc) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * rc - the return code of the connection response, one of: * flags - the connect flags. * * * 0 - success * * 1 - connection refused (unacceptable protocol version) * * 2 - connection refused (identifier rejected) * * 3 - connection refused (broker unavailable) * * 4-255 - reserved for future use */ libmosq_EXPORT void mosquitto_connect_with_flags_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int, int)); /* * Function: mosquitto_connect_v5_callback_set * * Set the connect callback. This is called when the broker sends a CONNACK * message in response to a connection. * * Parameters: * mosq - a valid mosquitto instance. * on_connect - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int rc) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * rc - the return code of the connection response, one of: * * 0 - success * * 1 - connection refused (unacceptable protocol version) * * 2 - connection refused (identifier rejected) * * 3 - connection refused (broker unavailable) * * 4-255 - reserved for future use * flags - the connect flags. * props - list of MQTT 5 properties, or NULL * */ libmosq_EXPORT void mosquitto_connect_v5_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int, int, const mosquitto_property *props)); /* * Function: mosquitto_disconnect_callback_set * * Set the disconnect callback. This is called when the broker has received the * DISCONNECT command and has disconnected the client. * * Parameters: * mosq - a valid mosquitto instance. * on_disconnect - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * rc - integer value indicating the reason for the disconnect. A value of 0 * means the client has called . Any other value * indicates that the disconnect is unexpected. */ libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int)); /* * Function: mosquitto_disconnect_v5_callback_set * * Set the disconnect callback. This is called when the broker has received the * DISCONNECT command and has disconnected the client. * * Parameters: * mosq - a valid mosquitto instance. * on_disconnect - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * rc - integer value indicating the reason for the disconnect. A value of 0 * means the client has called . Any other value * indicates that the disconnect is unexpected. * props - list of MQTT 5 properties, or NULL */ libmosq_EXPORT void mosquitto_disconnect_v5_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int, const mosquitto_property *)); /* * Function: mosquitto_publish_callback_set * * Set the publish callback. This is called when a message initiated with * has been sent to the broker successfully. * * Parameters: * mosq - a valid mosquitto instance. * on_publish - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int mid) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the sent message. */ libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int)); /* * Function: mosquitto_publish_v5_callback_set * * Set the publish callback. This is called when a message initiated with * has been sent to the broker. This callback will be * called both if the message is sent successfully, or if the broker responded * with an error, which will be reflected in the reason_code parameter. * * Parameters: * mosq - a valid mosquitto instance. * on_publish - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int mid) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the sent message. * reason_code - the MQTT 5 reason code * props - list of MQTT 5 properties, or NULL */ libmosq_EXPORT void mosquitto_publish_v5_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int, int, const mosquitto_property *)); /* * Function: mosquitto_message_callback_set * * Set the message callback. This is called when a message is received from the * broker. * * Parameters: * mosq - a valid mosquitto instance. * on_message - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * message - the message data. This variable and associated memory will be * freed by the library after the callback completes. The client * should make copies of any of the data it requires. * * See Also: * */ libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *)); /* * Function: mosquitto_message_v5_callback_set * * Set the message callback. This is called when a message is received from the * broker. * * Parameters: * mosq - a valid mosquitto instance. * on_message - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * message - the message data. This variable and associated memory will be * freed by the library after the callback completes. The client * should make copies of any of the data it requires. * props - list of MQTT 5 properties, or NULL * * See Also: * */ libmosq_EXPORT void mosquitto_message_v5_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *, const mosquitto_property *)); /* * Function: mosquitto_subscribe_callback_set * * Set the subscribe callback. This is called when the broker responds to a * subscription request. * * Parameters: * mosq - a valid mosquitto instance. * on_subscribe - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the subscribe message. * qos_count - the number of granted subscriptions (size of granted_qos). * granted_qos - an array of integers indicating the granted QoS for each of * the subscriptions. */ libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *)); /* * Function: mosquitto_subscribe_v5_callback_set * * Set the subscribe callback. This is called when the broker responds to a * subscription request. * * Parameters: * mosq - a valid mosquitto instance. * on_subscribe - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the subscribe message. * qos_count - the number of granted subscriptions (size of granted_qos). * granted_qos - an array of integers indicating the granted QoS for each of * the subscriptions. * props - list of MQTT 5 properties, or NULL */ libmosq_EXPORT void mosquitto_subscribe_v5_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *, const mosquitto_property *)); /* * Function: mosquitto_unsubscribe_callback_set * * Set the unsubscribe callback. This is called when the broker responds to a * unsubscription request. * * Parameters: * mosq - a valid mosquitto instance. * on_unsubscribe - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int mid) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the unsubscribe message. */ libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int)); /* * Function: mosquitto_unsubscribe_v5_callback_set * * Set the unsubscribe callback. This is called when the broker responds to a * unsubscription request. * * Parameters: * mosq - a valid mosquitto instance. * on_unsubscribe - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int mid) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the unsubscribe message. * props - list of MQTT 5 properties, or NULL */ libmosq_EXPORT void mosquitto_unsubscribe_v5_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int, const mosquitto_property *)); /* * Function: mosquitto_log_callback_set * * Set the logging callback. This should be used if you want event logging * information from the client library. * * mosq - a valid mosquitto instance. * on_log - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, int level, const char *str) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * level - the log message level from the values: * MOSQ_LOG_INFO * MOSQ_LOG_NOTICE * MOSQ_LOG_WARNING * MOSQ_LOG_ERR * MOSQ_LOG_DEBUG * str - the message string. */ libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on_log)(struct mosquitto *, void *, int, const char *)); /* * Function: mosquitto_string_option * * Used to set const char* options for the client. * * Parameters: * mosq - a valid mosquitto instance. * option - the option to set. * value - the option specific value. * * Options: * MOSQ_OPT_TLS_ENGINE * Configure the client for TLS Engine support. Pass a TLS Engine ID * to be used when creating TLS connections. * Must be set before . * MOSQ_OPT_TLS_KEYFORM * Configure the client to treat the keyfile differently depending * on its type. Must be set before . * Set as either "pem" or "engine", to determine from where the * private key for a TLS connection will be obtained. Defaults to * "pem", a normal private key file. * MOSQ_OPT_TLS_KPASS_SHA1 * Where the TLS Engine requires the use of a password to be * accessed, this option allows a hex encoded SHA1 hash of the * private key password to be passed to the engine directly. * Must be set before . * MOSQ_OPT_TLS_ALPN * If the broker being connected to has multiple services available * on a single TLS port, such as both MQTT and WebSockets, use this * option to configure the ALPN option for the connection. */ libmosq_EXPORT int mosquitto_string_option(struct mosquitto *mosq, enum mosq_opt_t option, const char *value); /* * Function: mosquitto_reconnect_delay_set * * Control the behaviour of the client when it has unexpectedly disconnected in * or after . The default * behaviour if this function is not used is to repeatedly attempt to reconnect * with a delay of 1 second until the connection succeeds. * * Use reconnect_delay parameter to change the delay between successive * reconnection attempts. You may also enable exponential backoff of the time * between reconnections by setting reconnect_exponential_backoff to true and * set an upper bound on the delay with reconnect_delay_max. * * Example 1: * delay=2, delay_max=10, exponential_backoff=False * Delays would be: 2, 4, 6, 8, 10, 10, ... * * Example 2: * delay=3, delay_max=30, exponential_backoff=True * Delays would be: 3, 6, 12, 24, 30, 30, ... * * Parameters: * mosq - a valid mosquitto instance. * reconnect_delay - the number of seconds to wait between * reconnects. * reconnect_delay_max - the maximum number of seconds to wait * between reconnects. * reconnect_exponential_backoff - use exponential backoff between * reconnect attempts. Set to true to enable * exponential backoff. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid. */ libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff); /* ============================================================================= * * Section: SOCKS5 proxy functions * * ============================================================================= */ /* * Function: mosquitto_socks5_set * * Configure the client to use a SOCKS5 proxy when connecting. Must be called * before connecting. "None" and "username/password" authentication is * supported. * * Parameters: * mosq - a valid mosquitto instance. * host - the SOCKS5 proxy host to connect to. * port - the SOCKS5 proxy port to use. * username - if not NULL, use this username when authenticating with the proxy. * password - if not NULL and username is not NULL, use this password when * authenticating with the proxy. */ libmosq_EXPORT int mosquitto_socks5_set(struct mosquitto *mosq, const char *host, int port, const char *username, const char *password); /* ============================================================================= * * Section: Utility functions * * ============================================================================= */ /* * Function: mosquitto_strerror * * Call to obtain a const string description of a mosquitto error number. * * Parameters: * mosq_errno - a mosquitto error number. * * Returns: * A constant string describing the error. */ libmosq_EXPORT const char *mosquitto_strerror(int mosq_errno); /* * Function: mosquitto_connack_string * * Call to obtain a const string description of an MQTT connection result. * * Parameters: * connack_code - an MQTT connection result. * * Returns: * A constant string describing the result. */ libmosq_EXPORT const char *mosquitto_connack_string(int connack_code); /* * Function: mosquitto_reason_string * * Call to obtain a const string description of an MQTT reason code. * * Parameters: * reason_code - an MQTT reason code. * * Returns: * A constant string describing the reason. */ libmosq_EXPORT const char *mosquitto_reason_string(int reason_code); /* Function: mosquitto_string_to_command * * Take a string input representing an MQTT command and convert it to the * libmosquitto integer representation. * * Parameters: * str - the string to parse. * cmd - pointer to an int, for the result. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - on an invalid input. * * Example: * mosquitto_string_to_command("CONNECT", &cmd); * // cmd == CMD_CONNECT */ libmosq_EXPORT int mosquitto_string_to_command(const char *str, int *cmd); /* * Function: mosquitto_sub_topic_tokenise * * Tokenise a topic or subscription string into an array of strings * representing the topic hierarchy. * * For example: * * subtopic: "a/deep/topic/hierarchy" * * Would result in: * * topics[0] = "a" * topics[1] = "deep" * topics[2] = "topic" * topics[3] = "hierarchy" * * and: * * subtopic: "/a/deep/topic/hierarchy/" * * Would result in: * * topics[0] = NULL * topics[1] = "a" * topics[2] = "deep" * topics[3] = "topic" * topics[4] = "hierarchy" * * Parameters: * subtopic - the subscription/topic to tokenise * topics - a pointer to store the array of strings * count - an int pointer to store the number of items in the topics array. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_NOMEM - if an out of memory condition occurred. * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 * * Example: * * > char **topics; * > int topic_count; * > int i; * > * > mosquitto_sub_topic_tokenise("$SYS/broker/uptime", &topics, &topic_count); * > * > for(i=0; i printf("%d: %s\n", i, topics[i]); * > } * * See Also: * */ libmosq_EXPORT int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count); /* * Function: mosquitto_sub_topic_tokens_free * * Free memory that was allocated in . * * Parameters: * topics - pointer to string array. * count - count of items in string array. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if the input parameters were invalid. * * See Also: * */ libmosq_EXPORT int mosquitto_sub_topic_tokens_free(char ***topics, int count); /* * Function: mosquitto_topic_matches_sub * * Check whether a topic matches a subscription. * * For example: * * foo/bar would match the subscription foo/# or +/bar * non/matching would not match the subscription non/+/+ * * Parameters: * sub - subscription string to check topic against. * topic - topic to check. * result - bool pointer to hold result. Will be set to true if the topic * matches the subscription. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. */ libmosq_EXPORT int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result); /* * Function: mosquitto_topic_matches_sub2 * * Check whether a topic matches a subscription. * * For example: * * foo/bar would match the subscription foo/# or +/bar * non/matching would not match the subscription non/+/+ * * Parameters: * sub - subscription string to check topic against. * sublen - length in bytes of sub string * topic - topic to check. * topiclen - length in bytes of topic string * result - bool pointer to hold result. Will be set to true if the topic * matches the subscription. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if the input parameters were invalid. * MOSQ_ERR_NOMEM - if an out of memory condition occurred. */ libmosq_EXPORT int mosquitto_topic_matches_sub2(const char *sub, size_t sublen, const char *topic, size_t topiclen, bool *result); /* * Function: mosquitto_pub_topic_check * * Check whether a topic to be used for publishing is valid. * * This searches for + or # in a topic and checks its length. * * This check is already carried out in and * , there is no need to call it directly before them. It * may be useful if you wish to check the validity of a topic in advance of * making a connection for example. * * Parameters: * topic - the topic to check * * Returns: * MOSQ_ERR_SUCCESS - for a valid topic * MOSQ_ERR_INVAL - if the topic contains a + or a #, or if it is too long. * MOSQ_ERR_MALFORMED_UTF8 - if sub or topic is not valid UTF-8 * * See Also: * */ libmosq_EXPORT int mosquitto_pub_topic_check(const char *topic); /* * Function: mosquitto_pub_topic_check2 * * Check whether a topic to be used for publishing is valid. * * This searches for + or # in a topic and checks its length. * * This check is already carried out in and * , there is no need to call it directly before them. It * may be useful if you wish to check the validity of a topic in advance of * making a connection for example. * * Parameters: * topic - the topic to check * topiclen - length of the topic in bytes * * Returns: * MOSQ_ERR_SUCCESS - for a valid topic * MOSQ_ERR_INVAL - if the topic contains a + or a #, or if it is too long. * MOSQ_ERR_MALFORMED_UTF8 - if sub or topic is not valid UTF-8 * * See Also: * */ libmosq_EXPORT int mosquitto_pub_topic_check2(const char *topic, size_t topiclen); /* * Function: mosquitto_sub_topic_check * * Check whether a topic to be used for subscribing is valid. * * This searches for + or # in a topic and checks that they aren't in invalid * positions, such as with foo/#/bar, foo/+bar or foo/bar#, and checks its * length. * * This check is already carried out in and * , there is no need to call it directly before them. * It may be useful if you wish to check the validity of a topic in advance of * making a connection for example. * * Parameters: * topic - the topic to check * * Returns: * MOSQ_ERR_SUCCESS - for a valid topic * MOSQ_ERR_INVAL - if the topic contains a + or a # that is in an * invalid position, or if it is too long. * MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8 * * See Also: * */ libmosq_EXPORT int mosquitto_sub_topic_check(const char *topic); /* * Function: mosquitto_sub_topic_check2 * * Check whether a topic to be used for subscribing is valid. * * This searches for + or # in a topic and checks that they aren't in invalid * positions, such as with foo/#/bar, foo/+bar or foo/bar#, and checks its * length. * * This check is already carried out in and * , there is no need to call it directly before them. * It may be useful if you wish to check the validity of a topic in advance of * making a connection for example. * * Parameters: * topic - the topic to check * topiclen - the length in bytes of the topic * * Returns: * MOSQ_ERR_SUCCESS - for a valid topic * MOSQ_ERR_INVAL - if the topic contains a + or a # that is in an * invalid position, or if it is too long. * MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8 * * See Also: * */ libmosq_EXPORT int mosquitto_sub_topic_check2(const char *topic, size_t topiclen); /* * Function: mosquitto_validate_utf8 * * Helper function to validate whether a UTF-8 string is valid, according to * the UTF-8 spec and the MQTT additions. * * Parameters: * str - a string to check * len - the length of the string in bytes * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if str is NULL or len<0 or len>65536 * MOSQ_ERR_MALFORMED_UTF8 - if str is not valid UTF-8 */ libmosq_EXPORT int mosquitto_validate_utf8(const char *str, int len); /* ============================================================================= * * Section: One line client helper functions * * ============================================================================= */ struct libmosquitto_will { char *topic; void *payload; int payloadlen; int qos; bool retain; }; struct libmosquitto_auth { char *username; char *password; }; struct libmosquitto_tls { char *cafile; char *capath; char *certfile; char *keyfile; char *ciphers; char *tls_version; int (*pw_callback)(char *buf, int size, int rwflag, void *userdata); int cert_reqs; }; /* * Function: mosquitto_subscribe_simple * * Helper function to make subscribing to a topic and retrieving some messages * very straightforward. * * This connects to a broker, subscribes to a topic, waits for msg_count * messages to be received, then returns after disconnecting cleanly. * * Parameters: * messages - pointer to a "struct mosquitto_message *". The received * messages will be returned here. On error, this will be set to * NULL. * msg_count - the number of messages to retrieve. * want_retained - if set to true, stale retained messages will be treated as * normal messages with regards to msg_count. If set to * false, they will be ignored. * topic - the subscription topic to use (wildcards are allowed). * qos - the qos to use for the subscription. * host - the broker to connect to. * port - the network port the broker is listening on. * client_id - the client id to use, or NULL if a random client id should be * generated. * keepalive - the MQTT keepalive value. * clean_session - the MQTT clean session flag. * username - the username string, or NULL for no username authentication. * password - the password string, or NULL for an empty password. * will - a libmosquitto_will struct containing will information, or NULL for * no will. * tls - a libmosquitto_tls struct containing TLS related parameters, or NULL * for no use of TLS. * * * Returns: * MOSQ_ERR_SUCCESS - on success * >0 - on error. */ libmosq_EXPORT int mosquitto_subscribe_simple( struct mosquitto_message **messages, int msg_count, bool want_retained, const char *topic, int qos, const char *host, int port, const char *client_id, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls); /* * Function: mosquitto_subscribe_callback * * Helper function to make subscribing to a topic and processing some messages * very straightforward. * * This connects to a broker, subscribes to a topic, then passes received * messages to a user provided callback. If the callback returns a 1, it then * disconnects cleanly and returns. * * Parameters: * callback - a callback function in the following form: * int callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) * Note that this is the same as the normal on_message callback, * except that it returns an int. * userdata - user provided pointer that will be passed to the callback. * topic - the subscription topic to use (wildcards are allowed). * qos - the qos to use for the subscription. * host - the broker to connect to. * port - the network port the broker is listening on. * client_id - the client id to use, or NULL if a random client id should be * generated. * keepalive - the MQTT keepalive value. * clean_session - the MQTT clean session flag. * username - the username string, or NULL for no username authentication. * password - the password string, or NULL for an empty password. * will - a libmosquitto_will struct containing will information, or NULL for * no will. * tls - a libmosquitto_tls struct containing TLS related parameters, or NULL * for no use of TLS. * * * Returns: * MOSQ_ERR_SUCCESS - on success * >0 - on error. */ libmosq_EXPORT int mosquitto_subscribe_callback( int (*callback)(struct mosquitto *, void *, const struct mosquitto_message *), void *userdata, const char *topic, int qos, const char *host, int port, const char *client_id, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls); /* ============================================================================= * * Section: Properties * * ============================================================================= */ /* * Function: mosquitto_property_add_byte * * Add a new byte property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - integer value for the new property * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_IDENTIFIER, 1); */ libmosq_EXPORT int mosquitto_property_add_byte(mosquitto_property **proplist, int identifier, uint8_t value); /* * Function: mosquitto_property_add_int16 * * Add a new int16 property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_RECEIVE_MAXIMUM) * value - integer value for the new property * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_int16(&proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1000); */ libmosq_EXPORT int mosquitto_property_add_int16(mosquitto_property **proplist, int identifier, uint16_t value); /* * Function: mosquitto_property_add_int32 * * Add a new int32 property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_MESSAGE_EXPIRY_INTERVAL) * value - integer value for the new property * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_int32(&proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 86400); */ libmosq_EXPORT int mosquitto_property_add_int32(mosquitto_property **proplist, int identifier, uint32_t value); /* * Function: mosquitto_property_add_varint * * Add a new varint property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_SUBSCRIPTION_IDENTIFIER) * value - integer value for the new property * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_varint(&proplist, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 1); */ libmosq_EXPORT int mosquitto_property_add_varint(mosquitto_property **proplist, int identifier, uint32_t value); /* * Function: mosquitto_property_add_binary * * Add a new binary property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to the property data * len - length of property data in bytes * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_binary(&proplist, MQTT_PROP_AUTHENTICATION_DATA, auth_data, auth_data_len); */ libmosq_EXPORT int mosquitto_property_add_binary(mosquitto_property **proplist, int identifier, const void *value, uint16_t len); /* * Function: mosquitto_property_add_string * * Add a new string property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_CONTENT_TYPE) * value - string value for the new property, must be UTF-8 and zero terminated * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, if value is NULL, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * MOSQ_ERR_MALFORMED_UTF8 - value is not valid UTF-8. * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_string(&proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); */ libmosq_EXPORT int mosquitto_property_add_string(mosquitto_property **proplist, int identifier, const char *value); /* * Function: mosquitto_property_add_string_pair * * Add a new string pair property to a property list. * * If *proplist == NULL, a new list will be created, otherwise the new property * will be appended to the list. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_USER_PROPERTY) * name - string name for the new property, must be UTF-8 and zero terminated * value - string value for the new property, must be UTF-8 and zero terminated * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if identifier is invalid, if name or value is NULL, or if proplist is NULL * MOSQ_ERR_NOMEM - on out of memory * MOSQ_ERR_MALFORMED_UTF8 - if name or value are not valid UTF-8. * * Example: * mosquitto_property *proplist = NULL; * mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "client", "mosquitto_pub"); */ libmosq_EXPORT int mosquitto_property_add_string_pair(mosquitto_property **proplist, int identifier, const char *name, const char *value); /* * Function: mosquitto_property_read_byte * * Attempt to read a byte property matching an identifier, from a property list * or single property. This function can search for multiple entries of the * same identifier by using the returned value and skip_first. Note however * that it is forbidden for most properties to be duplicated. * * If the property is not found, *value will not be modified, so it is safe to * pass a variable with a default value to be potentially overwritten: * * uint16_t keepalive = 60; // default value * // Get value from property list, or keep default if not found. * mosquitto_property_read_int16(proplist, MQTT_PROP_SERVER_KEEP_ALIVE, &keepalive, false); * * Parameters: * proplist - mosquitto_property pointer, the list of properties or single property * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to store the value, or NULL if the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL. * * Example: * // proplist is obtained from a callback * mosquitto_property *prop; * prop = mosquitto_property_read_byte(proplist, identifier, &value, false); * while(prop){ * printf("value: %s\n", value); * prop = mosquitto_property_read_byte(prop, identifier, &value); * } */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_byte( const mosquitto_property *proplist, int identifier, uint8_t *value, bool skip_first); /* * Function: mosquitto_property_read_int16 * * Read an int16 property value from a property. * * Parameters: * property - property to read * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to store the value, or NULL if the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL. * * Example: * See */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_int16( const mosquitto_property *proplist, int identifier, uint16_t *value, bool skip_first); /* * Function: mosquitto_property_read_int32 * * Read an int32 property value from a property. * * Parameters: * property - pointer to mosquitto_property pointer, the list of properties * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to store the value, or NULL if the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL. * * Example: * See */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_int32( const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first); /* * Function: mosquitto_property_read_varint * * Read a varint property value from a property. * * Parameters: * property - property to read * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to store the value, or NULL if the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL. * * Example: * See */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_varint( const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first); /* * Function: mosquitto_property_read_binary * * Read a binary property value from a property. * * On success, value must be free()'d by the application. * * Parameters: * property - property to read * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to store the value, or NULL if the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL, or if an out of memory condition occurred. * * Example: * See */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_binary( const mosquitto_property *proplist, int identifier, void **value, uint16_t *len, bool skip_first); /* * Function: mosquitto_property_read_string * * Read a string property value from a property. * * On success, value must be free()'d by the application. * * Parameters: * property - property to read * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * value - pointer to char*, for the property data to be stored in, or NULL if * the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL, or if an out of memory condition occurred. * * Example: * See */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_string( const mosquitto_property *proplist, int identifier, char **value, bool skip_first); /* * Function: mosquitto_property_read_string_pair * * Read a string pair property value pair from a property. * * On success, name and value must be free()'d by the application. * * Parameters: * property - property to read * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) * name - pointer to char* for the name property data to be stored in, or NULL * if the name is not required. * value - pointer to char*, for the property data to be stored in, or NULL if * the value is not required. * skip_first - boolean that indicates whether the first item in the list * should be ignored or not. Should usually be set to false. * * Returns: * A valid property pointer if the property is found * NULL, if the property is not found, or proplist is NULL, or if an out of memory condition occurred. * * Example: * See */ libmosq_EXPORT const mosquitto_property *mosquitto_property_read_string_pair( const mosquitto_property *proplist, int identifier, char **name, char **value, bool skip_first); /* * Function: mosquitto_property_free_all * * Free all properties from a list of properties. Frees the list and sets *properties to NULL. * * Parameters: * properties - list of properties to free * * Example: * mosquitto_properties *properties = NULL; * // Add properties * mosquitto_property_free_all(&properties); */ libmosq_EXPORT void mosquitto_property_free_all(mosquitto_property **properties); /* * Function: mosquitto_property_copy_all * * Parameters: * dest : pointer for new property list * src : property list * * Returns: * MOSQ_ERR_SUCCESS - on successful copy * MOSQ_ERR_INVAL - if dest is NULL * MOSQ_ERR_NOMEM - on out of memory (dest will be set to NULL) */ libmosq_EXPORT int mosquitto_property_copy_all(mosquitto_property **dest, const mosquitto_property *src); /* * Function: mosquitto_property_check_command * * Check whether a property identifier is valid for the given command. * * Parameters: * command - MQTT command (e.g. CMD_CONNECT) * identifier - MQTT property (e.g. MQTT_PROP_USER_PROPERTY) * * Returns: * MOSQ_ERR_SUCCESS - if the identifier is valid for command * MOSQ_ERR_PROTOCOL - if the identifier is not valid for use with command. */ libmosq_EXPORT int mosquitto_property_check_command(int command, int identifier); /* * Function: mosquitto_property_check_all * * Check whether a list of properties are valid for a particular command, * whether there are duplicates, and whether the values are valid where * possible. * * Note that this function is used internally in the library whenever * properties are passed to it, so in basic use this is not needed, but should * be helpful to check property lists *before* the point of using them. * * Parameters: * command - MQTT command (e.g. CMD_CONNECT) * properties - list of MQTT properties to check. * * Returns: * MOSQ_ERR_SUCCESS - if all properties are valid * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. * MOSQ_ERR_PROTOCOL - if any property is invalid */ libmosq_EXPORT int mosquitto_property_check_all(int command, const mosquitto_property *properties); /* Function: mosquitto_string_to_property_info * * Parse a property name string and convert to a property identifier and data type. * The property name is as defined in the MQTT specification, with - as a * separator, for example: payload-format-indicator. * * Parameters: * propname - the string to parse * identifier - pointer to an int to receive the property identifier * type - pointer to an int to receive the property type * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if the string does not match a property * * Example: * mosquitto_string_to_property_info("response-topic", &id, &type); * // id == MQTT_PROP_RESPONSE_TOPIC * // type == MQTT_PROP_TYPE_STRING */ libmosq_EXPORT int mosquitto_string_to_property_info(const char *propname, int *identifier, int *type); #ifdef __cplusplus } #endif #endif mosquitto-1.6.9/lib/send_subscribe.c0000664000175000017500000000502613626052637016534 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "util_mosq.h" int send__subscribe(struct mosquitto *mosq, int *mid, int topic_count, const char **topic, int topic_qos, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; uint32_t packetlen; uint16_t local_mid; int rc; int i; int proplen, varbytes; assert(mosq); assert(topic); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packetlen = 2; if(mosq->protocol == mosq_p_mqtt5){ proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); packetlen += proplen + varbytes; } for(i=0; icommand = CMD_SUBSCRIBE | (1<<1); packet->remaining_length = packetlen; rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } /* Variable header */ local_mid = mosquitto__mid_generate(mosq); if(mid) *mid = (int)local_mid; packet__write_uint16(packet, local_mid); if(mosq->protocol == mosq_p_mqtt5){ property__write_all(packet, properties, true); } /* Payload */ for(i=0; iid, local_mid, topic[0], topic_qos&0x03, topic_qos&0xFC); # endif #else for(i=0; iid, local_mid, topic[i], topic_qos&0x03, topic_qos&0xFC); } #endif return packet__queue(mosq, packet); } mosquitto-1.6.9/lib/net_mosq.c0000664000175000017500000006444213626052637015376 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #define _GNU_SOURCE #include "config.h" #include #include #include #include #include #ifndef WIN32 #define _GNU_SOURCE #include #include #include #else #include #include #endif #ifdef __ANDROID__ #include #include #include #endif #ifdef HAVE_NETINET_IN_H # include #endif #ifdef __QNX__ #include #endif #ifdef WITH_TLS #include #include #include #include #include #endif #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # ifdef WITH_WEBSOCKETS # include # endif #else # include "read_handle.h" #endif #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "time_mosq.h" #include "util_mosq.h" #ifdef WITH_TLS int tls_ex_index_mosq = -1; UI_METHOD *_ui_method = NULL; /* Functions taken from OpenSSL s_server/s_client */ static int ui_open(UI *ui) { return UI_method_get_opener(UI_OpenSSL())(ui); } static int ui_read(UI *ui, UI_STRING *uis) { return UI_method_get_reader(UI_OpenSSL())(ui, uis); } static int ui_write(UI *ui, UI_STRING *uis) { return UI_method_get_writer(UI_OpenSSL())(ui, uis); } static int ui_close(UI *ui) { return UI_method_get_closer(UI_OpenSSL())(ui); } static void setup_ui_method(void) { _ui_method = UI_create_method("OpenSSL application user interface"); UI_method_set_opener(_ui_method, ui_open); UI_method_set_reader(_ui_method, ui_read); UI_method_set_writer(_ui_method, ui_write); UI_method_set_closer(_ui_method, ui_close); } static void cleanup_ui_method(void) { if(_ui_method){ UI_destroy_method(_ui_method); _ui_method = NULL; } } UI_METHOD *net__get_ui_method(void) { return _ui_method; } #endif int net__init(void) { #ifdef WIN32 WSADATA wsaData; if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){ return MOSQ_ERR_UNKNOWN; } #endif #ifdef WITH_SRV ares_library_init(ARES_LIB_INIT_ALL); #endif #ifdef WITH_TLS # if OPENSSL_VERSION_NUMBER < 0x10100000L SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); # else OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ | OPENSSL_INIT_ADD_ALL_DIGESTS \ | OPENSSL_INIT_LOAD_CONFIG, NULL); # endif #if !defined(OPENSSL_NO_ENGINE) ENGINE_load_builtin_engines(); #endif setup_ui_method(); if(tls_ex_index_mosq == -1){ tls_ex_index_mosq = SSL_get_ex_new_index(0, "client context", NULL, NULL, NULL); } #endif return MOSQ_ERR_SUCCESS; } void net__cleanup(void) { #ifdef WITH_TLS # if OPENSSL_VERSION_NUMBER < 0x10100000L CRYPTO_cleanup_all_ex_data(); ERR_free_strings(); ERR_remove_thread_state(NULL); EVP_cleanup(); # if !defined(OPENSSL_NO_ENGINE) ENGINE_cleanup(); # endif # endif CONF_modules_unload(1); cleanup_ui_method(); #endif #ifdef WITH_SRV ares_library_cleanup(); #endif #ifdef WIN32 WSACleanup(); #endif } /* Close a socket associated with a context and set it to -1. * Returns 1 on failure (context is NULL) * Returns 0 on success. */ #ifdef WITH_BROKER int net__socket_close(struct mosquitto_db *db, struct mosquitto *mosq) #else int net__socket_close(struct mosquitto *mosq) #endif { int rc = 0; assert(mosq); #ifdef WITH_TLS #ifdef WITH_WEBSOCKETS if(!mosq->wsi) #endif { if(mosq->ssl){ if(!SSL_in_init(mosq->ssl)){ SSL_shutdown(mosq->ssl); } SSL_free(mosq->ssl); mosq->ssl = NULL; } } #endif #ifdef WITH_WEBSOCKETS if(mosq->wsi) { if(mosq->state != mosq_cs_disconnecting){ mosquitto__set_state(mosq, mosq_cs_disconnect_ws); } libwebsocket_callback_on_writable(mosq->ws_context, mosq->wsi); }else #endif { if(mosq->sock != INVALID_SOCKET){ #ifdef WITH_BROKER HASH_DELETE(hh_sock, db->contexts_by_sock, mosq); #endif rc = COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; } } #ifdef WITH_BROKER if(mosq->listener){ mosq->listener->client_count--; } #endif return rc; } #ifdef FINAL_WITH_TLS_PSK static unsigned int psk_client_callback(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { struct mosquitto *mosq; int len; UNUSED(hint); mosq = SSL_get_ex_data(ssl, tls_ex_index_mosq); if(!mosq) return 0; snprintf(identity, max_identity_len, "%s", mosq->tls_psk_identity); len = mosquitto__hex2bin(mosq->tls_psk, psk, max_psk_len); if (len < 0) return 0; return len; } #endif #if defined(WITH_BROKER) && defined(__GLIBC__) && defined(WITH_ADNS) /* Async connect, part 1 (dns lookup) */ int net__try_connect_step1(struct mosquitto *mosq, const char *host) { int s; void *sevp = NULL; struct addrinfo *hints; if(mosq->adns){ gai_cancel(mosq->adns); mosquitto__free((struct addrinfo *)mosq->adns->ar_request); mosquitto__free(mosq->adns); } mosq->adns = mosquitto__calloc(1, sizeof(struct gaicb)); if(!mosq->adns){ return MOSQ_ERR_NOMEM; } hints = mosquitto__calloc(1, sizeof(struct addrinfo)); if(!hints){ mosquitto__free(mosq->adns); mosq->adns = NULL; return MOSQ_ERR_NOMEM; } hints->ai_family = AF_UNSPEC; hints->ai_socktype = SOCK_STREAM; mosq->adns->ar_name = host; mosq->adns->ar_request = hints; s = getaddrinfo_a(GAI_NOWAIT, &mosq->adns, 1, sevp); if(s){ errno = s; if(mosq->adns){ mosquitto__free((struct addrinfo *)mosq->adns->ar_request); mosquitto__free(mosq->adns); mosq->adns = NULL; } return MOSQ_ERR_EAI; } return MOSQ_ERR_SUCCESS; } /* Async connect part 2, the connection. */ int net__try_connect_step2(struct mosquitto *mosq, uint16_t port, mosq_sock_t *sock) { struct addrinfo *ainfo, *rp; int rc; ainfo = mosq->adns->ar_result; for(rp = ainfo; rp != NULL; rp = rp->ai_next){ *sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if(*sock == INVALID_SOCKET) continue; if(rp->ai_family == AF_INET){ ((struct sockaddr_in *)rp->ai_addr)->sin_port = htons(port); }else if(rp->ai_family == AF_INET6){ ((struct sockaddr_in6 *)rp->ai_addr)->sin6_port = htons(port); }else{ COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; continue; } /* Set non-blocking */ if(net__socket_nonblock(sock)){ continue; } rc = connect(*sock, rp->ai_addr, rp->ai_addrlen); #ifdef WIN32 errno = WSAGetLastError(); #endif if(rc == 0 || errno == EINPROGRESS || errno == COMPAT_EWOULDBLOCK){ if(rc < 0 && (errno == EINPROGRESS || errno == COMPAT_EWOULDBLOCK)){ rc = MOSQ_ERR_CONN_PENDING; } /* Set non-blocking */ if(net__socket_nonblock(sock)){ continue; } break; } COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; } freeaddrinfo(mosq->adns->ar_result); mosq->adns->ar_result = NULL; mosquitto__free((struct addrinfo *)mosq->adns->ar_request); mosquitto__free(mosq->adns); mosq->adns = NULL; if(!rp){ return MOSQ_ERR_ERRNO; } return rc; } #endif int net__try_connect(const char *host, uint16_t port, mosq_sock_t *sock, const char *bind_address, bool blocking) { struct addrinfo hints; struct addrinfo *ainfo, *rp; struct addrinfo *ainfo_bind, *rp_bind; int s; int rc = MOSQ_ERR_SUCCESS; #ifdef WIN32 uint32_t val = 1; #endif *sock = INVALID_SOCKET; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; s = getaddrinfo(host, NULL, &hints, &ainfo); if(s){ errno = s; return MOSQ_ERR_EAI; } if(bind_address){ s = getaddrinfo(bind_address, NULL, &hints, &ainfo_bind); if(s){ freeaddrinfo(ainfo); errno = s; return MOSQ_ERR_EAI; } } for(rp = ainfo; rp != NULL; rp = rp->ai_next){ *sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if(*sock == INVALID_SOCKET) continue; if(rp->ai_family == AF_INET){ ((struct sockaddr_in *)rp->ai_addr)->sin_port = htons(port); }else if(rp->ai_family == AF_INET6){ ((struct sockaddr_in6 *)rp->ai_addr)->sin6_port = htons(port); }else{ COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; continue; } if(bind_address){ for(rp_bind = ainfo_bind; rp_bind != NULL; rp_bind = rp_bind->ai_next){ if(bind(*sock, rp_bind->ai_addr, rp_bind->ai_addrlen) == 0){ break; } } if(!rp_bind){ COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; continue; } } if(!blocking){ /* Set non-blocking */ if(net__socket_nonblock(sock)){ continue; } } rc = connect(*sock, rp->ai_addr, rp->ai_addrlen); #ifdef WIN32 errno = WSAGetLastError(); #endif if(rc == 0 || errno == EINPROGRESS || errno == COMPAT_EWOULDBLOCK){ if(rc < 0 && (errno == EINPROGRESS || errno == COMPAT_EWOULDBLOCK)){ rc = MOSQ_ERR_CONN_PENDING; } if(blocking){ /* Set non-blocking */ if(net__socket_nonblock(sock)){ continue; } } break; } COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; } freeaddrinfo(ainfo); if(bind_address){ freeaddrinfo(ainfo_bind); } if(!rp){ return MOSQ_ERR_ERRNO; } return rc; } #ifdef WITH_TLS void net__print_ssl_error(struct mosquitto *mosq) { char ebuf[256]; unsigned long e; int num = 0; e = ERR_get_error(); while(e){ log__printf(mosq, MOSQ_LOG_ERR, "OpenSSL Error[%d]: %s", num, ERR_error_string(e, ebuf)); e = ERR_get_error(); num++; } } int net__socket_connect_tls(struct mosquitto *mosq) { int ret, err; ERR_clear_error(); long res; if (mosq->tls_ocsp_required) { // Note: OCSP is available in all currently supported OpenSSL versions. if ((res=SSL_set_tlsext_status_type(mosq->ssl, TLSEXT_STATUSTYPE_ocsp)) != 1) { log__printf(mosq, MOSQ_LOG_ERR, "Could not activate OCSP (error: %ld)", res); return MOSQ_ERR_OCSP; } if ((res=SSL_CTX_set_tlsext_status_cb(mosq->ssl_ctx, mosquitto__verify_ocsp_status_cb)) != 1) { log__printf(mosq, MOSQ_LOG_ERR, "Could not activate OCSP (error: %ld)", res); return MOSQ_ERR_OCSP; } if ((res=SSL_CTX_set_tlsext_status_arg(mosq->ssl_ctx, mosq)) != 1) { log__printf(mosq, MOSQ_LOG_ERR, "Could not activate OCSP (error: %ld)", res); return MOSQ_ERR_OCSP; } } ret = SSL_connect(mosq->ssl); if(ret != 1) { err = SSL_get_error(mosq->ssl, ret); if (err == SSL_ERROR_SYSCALL) { mosq->want_connect = true; return MOSQ_ERR_SUCCESS; } if(err == SSL_ERROR_WANT_READ){ mosq->want_connect = true; /* We always try to read anyway */ }else if(err == SSL_ERROR_WANT_WRITE){ mosq->want_write = true; mosq->want_connect = true; }else{ net__print_ssl_error(mosq); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } }else{ mosq->want_connect = false; } return MOSQ_ERR_SUCCESS; } #endif #ifdef WITH_TLS static int net__init_ssl_ctx(struct mosquitto *mosq) { int ret; ENGINE *engine = NULL; uint8_t tls_alpn_wire[256]; uint8_t tls_alpn_len; if(mosq->ssl_ctx){ if(!mosq->ssl_ctx_defaults){ return MOSQ_ERR_SUCCESS; }else if(!mosq->tls_cafile && !mosq->tls_capath && !mosq->tls_psk){ log__printf(mosq, MOSQ_LOG_ERR, "Error: MOSQ_OPT_SSL_CTX_WITH_DEFAULTS used without specifying cafile, capath or psk."); return MOSQ_ERR_INVAL; } } /* Apply default SSL_CTX settings. This is only used if MOSQ_OPT_SSL_CTX * has not been set, or if both of MOSQ_OPT_SSL_CTX and * MOSQ_OPT_SSL_CTX_WITH_DEFAULTS are set. */ if(mosq->tls_cafile || mosq->tls_capath || mosq->tls_psk){ if(!mosq->ssl_ctx){ #if OPENSSL_VERSION_NUMBER < 0x10100000L mosq->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); #else mosq->ssl_ctx = SSL_CTX_new(TLS_client_method()); #endif if(!mosq->ssl_ctx){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to create TLS context."); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } } if(!mosq->tls_version){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1); #ifdef SSL_OP_NO_TLSv1_3 }else if(!strcmp(mosq->tls_version, "tlsv1.3")){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2); }else if(!strcmp(mosq->tls_version, "tlsv1.2")){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_3); }else if(!strcmp(mosq->tls_version, "tlsv1.1")){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3); #else }else if(!strcmp(mosq->tls_version, "tlsv1.2")){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); }else if(!strcmp(mosq->tls_version, "tlsv1.1")){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_2); #endif }else{ log__printf(mosq, MOSQ_LOG_ERR, "Error: Protocol %s not supported.", mosq->tls_version); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; return MOSQ_ERR_INVAL; } /* Disable compression */ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_COMPRESSION); /* Set ALPN */ if(mosq->tls_alpn) { tls_alpn_len = (uint8_t) strnlen(mosq->tls_alpn, 254); tls_alpn_wire[0] = tls_alpn_len; // first byte is length of string memcpy(tls_alpn_wire + 1, mosq->tls_alpn, tls_alpn_len); SSL_CTX_set_alpn_protos(mosq->ssl_ctx, tls_alpn_wire, tls_alpn_len + 1); } #ifdef SSL_MODE_RELEASE_BUFFERS /* Use even less memory per SSL connection. */ SSL_CTX_set_mode(mosq->ssl_ctx, SSL_MODE_RELEASE_BUFFERS); #endif #if !defined(OPENSSL_NO_ENGINE) if(mosq->tls_engine){ engine = ENGINE_by_id(mosq->tls_engine); if(!engine){ log__printf(mosq, MOSQ_LOG_ERR, "Error loading %s engine\n", mosq->tls_engine); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; return MOSQ_ERR_TLS; } if(!ENGINE_init(engine)){ log__printf(mosq, MOSQ_LOG_ERR, "Failed engine initialisation\n"); ENGINE_free(engine); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; return MOSQ_ERR_TLS; } ENGINE_set_default(engine, ENGINE_METHOD_ALL); ENGINE_free(engine); /* release the structural reference from ENGINE_by_id() */ } #endif if(mosq->tls_ciphers){ ret = SSL_CTX_set_cipher_list(mosq->ssl_ctx, mosq->tls_ciphers); if(ret == 0){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to set TLS ciphers. Check cipher list \"%s\".", mosq->tls_ciphers); #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } } if(mosq->tls_cafile || mosq->tls_capath){ ret = SSL_CTX_load_verify_locations(mosq->ssl_ctx, mosq->tls_cafile, mosq->tls_capath); if(ret == 0){ #ifdef WITH_BROKER if(mosq->tls_cafile && mosq->tls_capath){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check bridge_cafile \"%s\" and bridge_capath \"%s\".", mosq->tls_cafile, mosq->tls_capath); }else if(mosq->tls_cafile){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check bridge_cafile \"%s\".", mosq->tls_cafile); }else{ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check bridge_capath \"%s\".", mosq->tls_capath); } #else if(mosq->tls_cafile && mosq->tls_capath){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check cafile \"%s\" and capath \"%s\".", mosq->tls_cafile, mosq->tls_capath); }else if(mosq->tls_cafile){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check cafile \"%s\".", mosq->tls_cafile); }else{ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check capath \"%s\".", mosq->tls_capath); } #endif #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } if(mosq->tls_cert_reqs == 0){ SSL_CTX_set_verify(mosq->ssl_ctx, SSL_VERIFY_NONE, NULL); }else{ SSL_CTX_set_verify(mosq->ssl_ctx, SSL_VERIFY_PEER, mosquitto__server_certificate_verify); } if(mosq->tls_pw_callback){ SSL_CTX_set_default_passwd_cb(mosq->ssl_ctx, mosq->tls_pw_callback); SSL_CTX_set_default_passwd_cb_userdata(mosq->ssl_ctx, mosq); } if(mosq->tls_certfile){ ret = SSL_CTX_use_certificate_chain_file(mosq->ssl_ctx, mosq->tls_certfile); if(ret != 1){ #ifdef WITH_BROKER log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load client certificate, check bridge_certfile \"%s\".", mosq->tls_certfile); #else log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load client certificate \"%s\".", mosq->tls_certfile); #endif #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } } if(mosq->tls_keyfile){ if(mosq->tls_keyform == mosq_k_engine){ #if !defined(OPENSSL_NO_ENGINE) UI_METHOD *ui_method = net__get_ui_method(); if(mosq->tls_engine_kpass_sha1){ if(!ENGINE_ctrl_cmd(engine, ENGINE_SECRET_MODE, ENGINE_SECRET_MODE_SHA, NULL, NULL, 0)){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to set engine secret mode sha1"); ENGINE_FINISH(engine); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } if(!ENGINE_ctrl_cmd(engine, ENGINE_PIN, 0, mosq->tls_engine_kpass_sha1, NULL, 0)){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to set engine pin"); ENGINE_FINISH(engine); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } ui_method = NULL; } EVP_PKEY *pkey = ENGINE_load_private_key(engine, mosq->tls_keyfile, ui_method, NULL); if(!pkey){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load engine private key file \"%s\".", mosq->tls_keyfile); ENGINE_FINISH(engine); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } if(SSL_CTX_use_PrivateKey(mosq->ssl_ctx, pkey) <= 0){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to use engine private key file \"%s\".", mosq->tls_keyfile); ENGINE_FINISH(engine); COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } #endif }else{ ret = SSL_CTX_use_PrivateKey_file(mosq->ssl_ctx, mosq->tls_keyfile, SSL_FILETYPE_PEM); if(ret != 1){ #ifdef WITH_BROKER log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load client key file, check bridge_keyfile \"%s\".", mosq->tls_keyfile); #else log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load client key file \"%s\".", mosq->tls_keyfile); #endif #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } } ret = SSL_CTX_check_private_key(mosq->ssl_ctx); if(ret != 1){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Client certificate/key are inconsistent."); #if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); #endif COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } } #ifdef FINAL_WITH_TLS_PSK }else if(mosq->tls_psk){ SSL_CTX_set_psk_client_callback(mosq->ssl_ctx, psk_client_callback); #endif } } return MOSQ_ERR_SUCCESS; } #endif int net__socket_connect_step3(struct mosquitto *mosq, const char *host) { #ifdef WITH_TLS BIO *bio; int rc = net__init_ssl_ctx(mosq); if(rc) return rc; if(mosq->ssl_ctx){ if(mosq->ssl){ SSL_free(mosq->ssl); } mosq->ssl = SSL_new(mosq->ssl_ctx); if(!mosq->ssl){ COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } SSL_set_ex_data(mosq->ssl, tls_ex_index_mosq, mosq); bio = BIO_new_socket(mosq->sock, BIO_NOCLOSE); if(!bio){ COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } SSL_set_bio(mosq->ssl, bio, bio); /* * required for the SNI resolving */ if(SSL_set_tlsext_host_name(mosq->ssl, host) != 1) { COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; return MOSQ_ERR_TLS; } if(net__socket_connect_tls(mosq)){ return MOSQ_ERR_TLS; } } #endif return MOSQ_ERR_SUCCESS; } /* Create a socket and connect it to 'ip' on port 'port'. */ int net__socket_connect(struct mosquitto *mosq, const char *host, uint16_t port, const char *bind_address, bool blocking) { mosq_sock_t sock = INVALID_SOCKET; int rc, rc2; if(!mosq || !host || !port) return MOSQ_ERR_INVAL; rc = net__try_connect(host, port, &sock, bind_address, blocking); if(rc > 0) return rc; mosq->sock = sock; #if defined(WITH_SOCKS) && !defined(WITH_BROKER) if(!mosq->socks5_host) #endif { rc2 = net__socket_connect_step3(mosq, host); if(rc2) return rc2; } return MOSQ_ERR_SUCCESS; } ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { #ifdef WITH_TLS int ret; int err; #endif assert(mosq); errno = 0; #ifdef WITH_TLS if(mosq->ssl){ ret = SSL_read(mosq->ssl, buf, count); if(ret <= 0){ err = SSL_get_error(mosq->ssl, ret); if(err == SSL_ERROR_WANT_READ){ ret = -1; errno = EAGAIN; }else if(err == SSL_ERROR_WANT_WRITE){ ret = -1; mosq->want_write = true; errno = EAGAIN; }else{ net__print_ssl_error(mosq); errno = EPROTO; } ERR_clear_error(); #ifdef WIN32 WSASetLastError(errno); #endif } return (ssize_t )ret; }else{ /* Call normal read/recv */ #endif #ifndef WIN32 return read(mosq->sock, buf, count); #else return recv(mosq->sock, buf, count, 0); #endif #ifdef WITH_TLS } #endif } ssize_t net__write(struct mosquitto *mosq, void *buf, size_t count) { #ifdef WITH_TLS int ret; int err; #endif assert(mosq); errno = 0; #ifdef WITH_TLS if(mosq->ssl){ mosq->want_write = false; ret = SSL_write(mosq->ssl, buf, count); if(ret < 0){ err = SSL_get_error(mosq->ssl, ret); if(err == SSL_ERROR_WANT_READ){ ret = -1; errno = EAGAIN; }else if(err == SSL_ERROR_WANT_WRITE){ ret = -1; mosq->want_write = true; errno = EAGAIN; }else{ net__print_ssl_error(mosq); errno = EPROTO; } ERR_clear_error(); #ifdef WIN32 WSASetLastError(errno); #endif } return (ssize_t )ret; }else{ /* Call normal write/send */ #endif #ifndef WIN32 return write(mosq->sock, buf, count); #else return send(mosq->sock, buf, count, 0); #endif #ifdef WITH_TLS } #endif } int net__socket_nonblock(mosq_sock_t *sock) { #ifndef WIN32 int opt; /* Set non-blocking */ opt = fcntl(*sock, F_GETFL, 0); if(opt == -1){ COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; return MOSQ_ERR_ERRNO; } if(fcntl(*sock, F_SETFL, opt | O_NONBLOCK) == -1){ /* If either fcntl fails, don't want to allow this client to connect. */ COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; return MOSQ_ERR_ERRNO; } #else unsigned long opt = 1; if(ioctlsocket(*sock, FIONBIO, &opt)){ COMPAT_CLOSE(*sock); *sock = INVALID_SOCKET; return MOSQ_ERR_ERRNO; } #endif return MOSQ_ERR_SUCCESS; } #ifndef WITH_BROKER int net__socketpair(mosq_sock_t *pairR, mosq_sock_t *pairW) { #ifdef WIN32 int family[2] = {AF_INET, AF_INET6}; int i; struct sockaddr_storage ss; struct sockaddr_in *sa = (struct sockaddr_in *)&ss; struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&ss; socklen_t ss_len; mosq_sock_t spR, spW; mosq_sock_t listensock; *pairR = INVALID_SOCKET; *pairW = INVALID_SOCKET; for(i=0; i<2; i++){ memset(&ss, 0, sizeof(ss)); if(family[i] == AF_INET){ sa->sin_family = family[i]; sa->sin_addr.s_addr = htonl(INADDR_LOOPBACK); sa->sin_port = 0; ss_len = sizeof(struct sockaddr_in); }else if(family[i] == AF_INET6){ sa6->sin6_family = family[i]; sa6->sin6_addr = in6addr_loopback; sa6->sin6_port = 0; ss_len = sizeof(struct sockaddr_in6); }else{ return MOSQ_ERR_INVAL; } listensock = socket(family[i], SOCK_STREAM, IPPROTO_TCP); if(listensock == -1){ continue; } if(bind(listensock, (struct sockaddr *)&ss, ss_len) == -1){ COMPAT_CLOSE(listensock); continue; } if(listen(listensock, 1) == -1){ COMPAT_CLOSE(listensock); continue; } memset(&ss, 0, sizeof(ss)); ss_len = sizeof(ss); if(getsockname(listensock, (struct sockaddr *)&ss, &ss_len) < 0){ COMPAT_CLOSE(listensock); continue; } if(family[i] == AF_INET){ sa->sin_family = family[i]; sa->sin_addr.s_addr = htonl(INADDR_LOOPBACK); ss_len = sizeof(struct sockaddr_in); }else if(family[i] == AF_INET6){ sa6->sin6_family = family[i]; sa6->sin6_addr = in6addr_loopback; ss_len = sizeof(struct sockaddr_in6); } spR = socket(family[i], SOCK_STREAM, IPPROTO_TCP); if(spR == -1){ COMPAT_CLOSE(listensock); continue; } if(net__socket_nonblock(&spR)){ COMPAT_CLOSE(listensock); continue; } if(connect(spR, (struct sockaddr *)&ss, ss_len) < 0){ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno != EINPROGRESS && errno != COMPAT_EWOULDBLOCK){ COMPAT_CLOSE(spR); COMPAT_CLOSE(listensock); continue; } } spW = accept(listensock, NULL, 0); if(spW == -1){ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno != EINPROGRESS && errno != COMPAT_EWOULDBLOCK){ COMPAT_CLOSE(spR); COMPAT_CLOSE(listensock); continue; } } if(net__socket_nonblock(&spW)){ COMPAT_CLOSE(spR); COMPAT_CLOSE(listensock); continue; } COMPAT_CLOSE(listensock); *pairR = spR; *pairW = spW; return MOSQ_ERR_SUCCESS; } return MOSQ_ERR_UNKNOWN; #else int sv[2]; if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1){ return MOSQ_ERR_ERRNO; } if(net__socket_nonblock(&sv[0])){ COMPAT_CLOSE(sv[1]); return MOSQ_ERR_ERRNO; } if(net__socket_nonblock(&sv[1])){ COMPAT_CLOSE(sv[0]); return MOSQ_ERR_ERRNO; } *pairR = sv[0]; *pairW = sv[1]; return MOSQ_ERR_SUCCESS; #endif } #endif mosquitto-1.6.9/lib/messages_mosq.h0000664000175000017500000000262613626052637016420 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MESSAGES_MOSQ_H #define MESSAGES_MOSQ_H #include "mosquitto_internal.h" #include "mosquitto.h" void message__cleanup_all(struct mosquitto *mosq); void message__cleanup(struct mosquitto_message_all **message); int message__delete(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir, int qos); int message__queue(struct mosquitto *mosq, struct mosquitto_message_all *message, enum mosquitto_msg_direction dir); void message__reconnect_reset(struct mosquitto *mosq); int message__release_to_inflight(struct mosquitto *mosq, enum mosquitto_msg_direction dir); int message__remove(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir, struct mosquitto_message_all **message, int qos); void message__retry_check(struct mosquitto *mosq); int message__out_update(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_state state, int qos); #endif mosquitto-1.6.9/lib/send_unsubscribe.c0000664000175000017500000000474413626052637017105 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "util_mosq.h" int send__unsubscribe(struct mosquitto *mosq, int *mid, int topic_count, char *const *const topic, const mosquitto_property *properties) { /* FIXME - only deals with a single topic */ struct mosquitto__packet *packet = NULL; uint32_t packetlen; uint16_t local_mid; int rc; int proplen, varbytes; int i; assert(mosq); assert(topic); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packetlen = 2; for(i=0; iprotocol == mosq_p_mqtt5){ proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); packetlen += proplen + varbytes; } packet->command = CMD_UNSUBSCRIBE | (1<<1); packet->remaining_length = packetlen; rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } /* Variable header */ local_mid = mosquitto__mid_generate(mosq); if(mid) *mid = (int)local_mid; packet__write_uint16(packet, local_mid); if(mosq->protocol == mosq_p_mqtt5){ /* We don't use User Property yet. */ property__write_all(packet, properties, true); } /* Payload */ for(i=0; iid, local_mid, topic[i]); } # endif #else for(i=0; iid, local_mid, topic[i]); } #endif return packet__queue(mosq, packet); } mosquitto-1.6.9/lib/alias_mosq.c0000664000175000017500000000373613626052637015700 0ustar rogerroger/* Copyright (c) 2019-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto.h" #include "alias_mosq.h" #include "memory_mosq.h" int alias__add(struct mosquitto *mosq, const char *topic, int alias) { int i; struct mosquitto__alias *aliases; for(i=0; ialias_count; i++){ if(mosq->aliases[i].alias == alias){ mosquitto__free(mosq->aliases[i].topic); mosq->aliases[i].topic = mosquitto__strdup(topic); if(mosq->aliases[i].topic){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } } } /* New alias */ aliases = mosquitto__realloc(mosq->aliases, sizeof(struct mosquitto__alias)*(mosq->alias_count+1)); if(!aliases) return MOSQ_ERR_NOMEM; mosq->aliases = aliases; mosq->aliases[mosq->alias_count].alias = alias; mosq->aliases[mosq->alias_count].topic = mosquitto__strdup(topic); if(!mosq->aliases[mosq->alias_count].topic){ return MOSQ_ERR_NOMEM; } mosq->alias_count++; return MOSQ_ERR_SUCCESS; } int alias__find(struct mosquitto *mosq, char **topic, int alias) { int i; for(i=0; ialias_count; i++){ if(mosq->aliases[i].alias == alias){ *topic = mosquitto__strdup(mosq->aliases[i].topic); if(*topic){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } } } return MOSQ_ERR_INVAL; } void alias__free_all(struct mosquitto *mosq) { int i; for(i=0; ialias_count; i++){ mosquitto__free(mosq->aliases[i].topic); } mosquitto__free(mosq->aliases); mosq->aliases = NULL; mosq->alias_count = 0; } mosquitto-1.6.9/lib/property_mosq.c0000664000175000017500000007646413626052637016503 0ustar rogerroger/* Copyright (c) 2018-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifndef WIN32 # include #endif #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" int property__read(struct mosquitto__packet *packet, int32_t *len, mosquitto_property *property) { int rc; int32_t property_identifier; uint8_t byte; int8_t byte_count; uint16_t uint16; uint32_t uint32; int32_t varint; char *str1, *str2; int slen1, slen2; if(!property) return MOSQ_ERR_INVAL; rc = packet__read_varint(packet, &property_identifier, NULL); if(rc) return rc; *len -= 1; memset(property, 0, sizeof(mosquitto_property)); property->identifier = property_identifier; switch(property_identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: case MQTT_PROP_MAXIMUM_QOS: case MQTT_PROP_RETAIN_AVAILABLE: case MQTT_PROP_WILDCARD_SUB_AVAILABLE: case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: case MQTT_PROP_SHARED_SUB_AVAILABLE: rc = packet__read_byte(packet, &byte); if(rc) return rc; *len -= 1; /* byte */ property->value.i8 = byte; break; case MQTT_PROP_SERVER_KEEP_ALIVE: case MQTT_PROP_RECEIVE_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS: rc = packet__read_uint16(packet, &uint16); if(rc) return rc; *len -= 2; /* uint16 */ property->value.i16 = uint16; break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: case MQTT_PROP_SESSION_EXPIRY_INTERVAL: case MQTT_PROP_WILL_DELAY_INTERVAL: case MQTT_PROP_MAXIMUM_PACKET_SIZE: rc = packet__read_uint32(packet, &uint32); if(rc) return rc; *len -= 4; /* uint32 */ property->value.i32 = uint32; break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: rc = packet__read_varint(packet, &varint, &byte_count); if(rc) return rc; *len -= byte_count; property->value.varint = varint; break; case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: case MQTT_PROP_AUTHENTICATION_METHOD: case MQTT_PROP_RESPONSE_INFORMATION: case MQTT_PROP_SERVER_REFERENCE: case MQTT_PROP_REASON_STRING: rc = packet__read_string(packet, &str1, &slen1); if(rc) return rc; *len = (*len) - 2 - slen1; /* uint16, string len */ property->value.s.v = str1; property->value.s.len = slen1; break; case MQTT_PROP_AUTHENTICATION_DATA: case MQTT_PROP_CORRELATION_DATA: rc = packet__read_binary(packet, (uint8_t **)&str1, &slen1); if(rc) return rc; *len = (*len) - 2 - slen1; /* uint16, binary len */ property->value.bin.v = str1; property->value.bin.len = slen1; break; case MQTT_PROP_USER_PROPERTY: rc = packet__read_string(packet, &str1, &slen1); if(rc) return rc; *len = (*len) - 2 - slen1; /* uint16, string len */ rc = packet__read_string(packet, &str2, &slen2); if(rc){ mosquitto__free(str1); return rc; } *len = (*len) - 2 - slen2; /* uint16, string len */ property->name.v = str1; property->name.len = slen1; property->value.s.v = str2; property->value.s.len = slen2; break; default: log__printf(NULL, MOSQ_LOG_DEBUG, "Unsupported property type: %d", property_identifier); return MOSQ_ERR_MALFORMED_PACKET; } return MOSQ_ERR_SUCCESS; } int property__read_all(int command, struct mosquitto__packet *packet, mosquitto_property **properties) { int rc; int32_t proplen; mosquitto_property *p, *tail = NULL; rc = packet__read_varint(packet, &proplen, NULL); if(rc) return rc; *properties = NULL; /* The order of properties must be preserved for some types, so keep the * same order for all */ while(proplen > 0){ p = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!p){ mosquitto_property_free_all(properties); return MOSQ_ERR_NOMEM; } rc = property__read(packet, &proplen, p); if(rc){ mosquitto__free(p); mosquitto_property_free_all(properties); return rc; } if(!(*properties)){ *properties = p; }else{ tail->next = p; } tail = p; } rc = mosquitto_property_check_all(command, *properties); if(rc){ mosquitto_property_free_all(properties); return rc; } return MOSQ_ERR_SUCCESS; } void property__free(mosquitto_property **property) { if(!property || !(*property)) return; switch((*property)->identifier){ case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: case MQTT_PROP_AUTHENTICATION_METHOD: case MQTT_PROP_RESPONSE_INFORMATION: case MQTT_PROP_SERVER_REFERENCE: case MQTT_PROP_REASON_STRING: mosquitto__free((*property)->value.s.v); break; case MQTT_PROP_AUTHENTICATION_DATA: case MQTT_PROP_CORRELATION_DATA: mosquitto__free((*property)->value.bin.v); break; case MQTT_PROP_USER_PROPERTY: mosquitto__free((*property)->name.v); mosquitto__free((*property)->value.s.v); break; case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: case MQTT_PROP_SESSION_EXPIRY_INTERVAL: case MQTT_PROP_SERVER_KEEP_ALIVE: case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: case MQTT_PROP_WILL_DELAY_INTERVAL: case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: case MQTT_PROP_RECEIVE_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS: case MQTT_PROP_MAXIMUM_QOS: case MQTT_PROP_RETAIN_AVAILABLE: case MQTT_PROP_MAXIMUM_PACKET_SIZE: case MQTT_PROP_WILDCARD_SUB_AVAILABLE: case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: case MQTT_PROP_SHARED_SUB_AVAILABLE: /* Nothing to free */ break; } free(*property); *property = NULL; } void mosquitto_property_free_all(mosquitto_property **property) { mosquitto_property *p, *next; if(!property) return; p = *property; while(p){ next = p->next; property__free(&p); p = next; } *property = NULL; } int property__get_length(const mosquitto_property *property) { if(!property) return 0; switch(property->identifier){ /* Byte */ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: case MQTT_PROP_MAXIMUM_QOS: case MQTT_PROP_RETAIN_AVAILABLE: case MQTT_PROP_WILDCARD_SUB_AVAILABLE: case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: case MQTT_PROP_SHARED_SUB_AVAILABLE: return 2; /* 1 (identifier) + 1 byte */ /* uint16 */ case MQTT_PROP_SERVER_KEEP_ALIVE: case MQTT_PROP_RECEIVE_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS: return 3; /* 1 (identifier) + 2 bytes */ /* uint32 */ case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: case MQTT_PROP_WILL_DELAY_INTERVAL: case MQTT_PROP_MAXIMUM_PACKET_SIZE: case MQTT_PROP_SESSION_EXPIRY_INTERVAL: return 5; /* 1 (identifier) + 4 bytes */ /* varint */ case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: if(property->value.varint < 128){ return 2; }else if(property->value.varint < 16384){ return 3; }else if(property->value.varint < 2097152){ return 4; }else if(property->value.varint < 268435456){ return 5; }else{ return 0; } /* binary */ case MQTT_PROP_CORRELATION_DATA: case MQTT_PROP_AUTHENTICATION_DATA: return 3 + property->value.bin.len; /* 1 + 2 bytes (len) + X bytes (payload) */ /* string */ case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: case MQTT_PROP_AUTHENTICATION_METHOD: case MQTT_PROP_RESPONSE_INFORMATION: case MQTT_PROP_SERVER_REFERENCE: case MQTT_PROP_REASON_STRING: return 3 + property->value.s.len; /* 1 + 2 bytes (len) + X bytes (string) */ /* string pair */ case MQTT_PROP_USER_PROPERTY: return 5 + property->value.s.len + property->name.len; /* 1 + 2*(2 bytes (len) + X bytes (string))*/ default: return 0; } return 0; } int property__get_length_all(const mosquitto_property *property) { const mosquitto_property *p; int len = 0; p = property; while(p){ len += property__get_length(p); p = p->next; } return len; } int property__write(struct mosquitto__packet *packet, const mosquitto_property *property) { int rc; rc = packet__write_varint(packet, property->identifier); if(rc) return rc; switch(property->identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: case MQTT_PROP_MAXIMUM_QOS: case MQTT_PROP_RETAIN_AVAILABLE: case MQTT_PROP_WILDCARD_SUB_AVAILABLE: case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: case MQTT_PROP_SHARED_SUB_AVAILABLE: packet__write_byte(packet, property->value.i8); break; case MQTT_PROP_SERVER_KEEP_ALIVE: case MQTT_PROP_RECEIVE_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS: packet__write_uint16(packet, property->value.i16); break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: case MQTT_PROP_SESSION_EXPIRY_INTERVAL: case MQTT_PROP_WILL_DELAY_INTERVAL: case MQTT_PROP_MAXIMUM_PACKET_SIZE: packet__write_uint32(packet, property->value.i32); break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: return packet__write_varint(packet, property->value.varint); case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: case MQTT_PROP_AUTHENTICATION_METHOD: case MQTT_PROP_RESPONSE_INFORMATION: case MQTT_PROP_SERVER_REFERENCE: case MQTT_PROP_REASON_STRING: packet__write_string(packet, property->value.s.v, property->value.s.len); break; case MQTT_PROP_AUTHENTICATION_DATA: case MQTT_PROP_CORRELATION_DATA: packet__write_uint16(packet, property->value.bin.len); packet__write_bytes(packet, property->value.bin.v, property->value.bin.len); break; case MQTT_PROP_USER_PROPERTY: packet__write_string(packet, property->name.v, property->name.len); packet__write_string(packet, property->value.s.v, property->value.s.len); break; default: log__printf(NULL, MOSQ_LOG_DEBUG, "Unsupported property type: %d", property->identifier); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } int property__write_all(struct mosquitto__packet *packet, const mosquitto_property *properties, bool write_len) { int rc; const mosquitto_property *p; if(write_len){ rc = packet__write_varint(packet, property__get_length_all(properties)); if(rc) return rc; } p = properties; while(p){ rc = property__write(packet, p); if(rc) return rc; p = p->next; } return MOSQ_ERR_SUCCESS; } int mosquitto_property_check_command(int command, int identifier) { switch(identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_CORRELATION_DATA: if(command != CMD_PUBLISH && command != CMD_WILL){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: if(command != CMD_PUBLISH && command != CMD_SUBSCRIBE){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_SESSION_EXPIRY_INTERVAL: if(command != CMD_CONNECT && command != CMD_CONNACK && command != CMD_DISCONNECT){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_AUTHENTICATION_METHOD: case MQTT_PROP_AUTHENTICATION_DATA: if(command != CMD_CONNECT && command != CMD_CONNACK && command != CMD_AUTH){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: case MQTT_PROP_SERVER_KEEP_ALIVE: case MQTT_PROP_RESPONSE_INFORMATION: case MQTT_PROP_MAXIMUM_QOS: case MQTT_PROP_RETAIN_AVAILABLE: case MQTT_PROP_WILDCARD_SUB_AVAILABLE: case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: case MQTT_PROP_SHARED_SUB_AVAILABLE: if(command != CMD_CONNACK){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_WILL_DELAY_INTERVAL: if(command != CMD_WILL){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: if(command != CMD_CONNECT){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_SERVER_REFERENCE: if(command != CMD_CONNACK && command != CMD_DISCONNECT){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_REASON_STRING: if(command == CMD_CONNECT || command == CMD_PUBLISH || command == CMD_SUBSCRIBE || command == CMD_UNSUBSCRIBE){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_RECEIVE_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: case MQTT_PROP_MAXIMUM_PACKET_SIZE: if(command != CMD_CONNECT && command != CMD_CONNACK){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_TOPIC_ALIAS: if(command != CMD_PUBLISH){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_USER_PROPERTY: break; default: return MOSQ_ERR_PROTOCOL; } return MOSQ_ERR_SUCCESS; } int mosquitto_string_to_property_info(const char *propname, int *identifier, int *type) { if(!propname) return MOSQ_ERR_INVAL; if(!strcasecmp(propname, "payload-format-indicator")){ *identifier = MQTT_PROP_PAYLOAD_FORMAT_INDICATOR; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "message-expiry-interval")){ *identifier = MQTT_PROP_MESSAGE_EXPIRY_INTERVAL; *type = MQTT_PROP_TYPE_INT32; }else if(!strcasecmp(propname, "content-type")){ *identifier = MQTT_PROP_CONTENT_TYPE; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "response-topic")){ *identifier = MQTT_PROP_RESPONSE_TOPIC; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "correlation-data")){ *identifier = MQTT_PROP_CORRELATION_DATA; *type = MQTT_PROP_TYPE_BINARY; }else if(!strcasecmp(propname, "subscription-identifier")){ *identifier = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; *type = MQTT_PROP_TYPE_VARINT; }else if(!strcasecmp(propname, "session-expiry-interval")){ *identifier = MQTT_PROP_SESSION_EXPIRY_INTERVAL; *type = MQTT_PROP_TYPE_INT32; }else if(!strcasecmp(propname, "assigned-client-identifier")){ *identifier = MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "server-keep-alive")){ *identifier = MQTT_PROP_SERVER_KEEP_ALIVE; *type = MQTT_PROP_TYPE_INT16; }else if(!strcasecmp(propname, "authentication-method")){ *identifier = MQTT_PROP_AUTHENTICATION_METHOD; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "authentication-data")){ *identifier = MQTT_PROP_AUTHENTICATION_DATA; *type = MQTT_PROP_TYPE_BINARY; }else if(!strcasecmp(propname, "request-problem-information")){ *identifier = MQTT_PROP_REQUEST_PROBLEM_INFORMATION; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "will-delay-interval")){ *identifier = MQTT_PROP_WILL_DELAY_INTERVAL; *type = MQTT_PROP_TYPE_INT32; }else if(!strcasecmp(propname, "request-response-information")){ *identifier = MQTT_PROP_REQUEST_RESPONSE_INFORMATION; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "response-information")){ *identifier = MQTT_PROP_RESPONSE_INFORMATION; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "server-reference")){ *identifier = MQTT_PROP_SERVER_REFERENCE; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "reason-string")){ *identifier = MQTT_PROP_REASON_STRING; *type = MQTT_PROP_TYPE_STRING; }else if(!strcasecmp(propname, "receive-maximum")){ *identifier = MQTT_PROP_RECEIVE_MAXIMUM; *type = MQTT_PROP_TYPE_INT16; }else if(!strcasecmp(propname, "topic-alias-maximum")){ *identifier = MQTT_PROP_TOPIC_ALIAS_MAXIMUM; *type = MQTT_PROP_TYPE_INT16; }else if(!strcasecmp(propname, "topic-alias")){ *identifier = MQTT_PROP_TOPIC_ALIAS; *type = MQTT_PROP_TYPE_INT16; }else if(!strcasecmp(propname, "maximum-qos")){ *identifier = MQTT_PROP_MAXIMUM_QOS; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "retain-available")){ *identifier = MQTT_PROP_RETAIN_AVAILABLE; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "user-property")){ *identifier = MQTT_PROP_USER_PROPERTY; *type = MQTT_PROP_TYPE_STRING_PAIR; }else if(!strcasecmp(propname, "maximum-packet-size")){ *identifier = MQTT_PROP_MAXIMUM_PACKET_SIZE; *type = MQTT_PROP_TYPE_INT32; }else if(!strcasecmp(propname, "wildcard-subscription-available")){ *identifier = MQTT_PROP_WILDCARD_SUB_AVAILABLE; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "subscription-identifier-available")){ *identifier = MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE; *type = MQTT_PROP_TYPE_BYTE; }else if(!strcasecmp(propname, "shared-subscription-available")){ *identifier = MQTT_PROP_SHARED_SUB_AVAILABLE; *type = MQTT_PROP_TYPE_BYTE; }else{ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static void property__add(mosquitto_property **proplist, struct mqtt5__property *prop) { mosquitto_property *p; if(!(*proplist)){ *proplist = prop; } p = *proplist; while(p->next){ p = p->next; } p->next = prop; prop->next = NULL; } int mosquitto_property_add_byte(mosquitto_property **proplist, int identifier, uint8_t value) { mosquitto_property *prop; if(!proplist) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_PAYLOAD_FORMAT_INDICATOR && identifier != MQTT_PROP_REQUEST_PROBLEM_INFORMATION && identifier != MQTT_PROP_REQUEST_RESPONSE_INFORMATION && identifier != MQTT_PROP_MAXIMUM_QOS && identifier != MQTT_PROP_RETAIN_AVAILABLE && identifier != MQTT_PROP_WILDCARD_SUB_AVAILABLE && identifier != MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE && identifier != MQTT_PROP_SHARED_SUB_AVAILABLE){ return MOSQ_ERR_INVAL; } prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; prop->value.i8 = value; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_add_int16(mosquitto_property **proplist, int identifier, uint16_t value) { mosquitto_property *prop; if(!proplist) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_SERVER_KEEP_ALIVE && identifier != MQTT_PROP_RECEIVE_MAXIMUM && identifier != MQTT_PROP_TOPIC_ALIAS_MAXIMUM && identifier != MQTT_PROP_TOPIC_ALIAS){ return MOSQ_ERR_INVAL; } prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; prop->value.i16 = value; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_add_int32(mosquitto_property **proplist, int identifier, uint32_t value) { mosquitto_property *prop; if(!proplist) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_MESSAGE_EXPIRY_INTERVAL && identifier != MQTT_PROP_SESSION_EXPIRY_INTERVAL && identifier != MQTT_PROP_WILL_DELAY_INTERVAL && identifier != MQTT_PROP_MAXIMUM_PACKET_SIZE){ return MOSQ_ERR_INVAL; } prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; prop->value.i32 = value; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_add_varint(mosquitto_property **proplist, int identifier, uint32_t value) { mosquitto_property *prop; if(!proplist || value > 268435455) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_SUBSCRIPTION_IDENTIFIER) return MOSQ_ERR_INVAL; prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; prop->value.varint = value; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_add_binary(mosquitto_property **proplist, int identifier, const void *value, uint16_t len) { mosquitto_property *prop; if(!proplist) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_CORRELATION_DATA && identifier != MQTT_PROP_AUTHENTICATION_DATA){ return MOSQ_ERR_INVAL; } prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; if(len){ prop->value.bin.v = mosquitto__malloc(len); if(!prop->value.bin.v){ mosquitto__free(prop); return MOSQ_ERR_NOMEM; } memcpy(prop->value.bin.v, value, len); prop->value.bin.len = len; } property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_add_string(mosquitto_property **proplist, int identifier, const char *value) { mosquitto_property *prop; if(!proplist) return MOSQ_ERR_INVAL; if(value){ if(mosquitto_validate_utf8(value, strlen(value))) return MOSQ_ERR_MALFORMED_UTF8; } if(identifier != MQTT_PROP_CONTENT_TYPE && identifier != MQTT_PROP_RESPONSE_TOPIC && identifier != MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER && identifier != MQTT_PROP_AUTHENTICATION_METHOD && identifier != MQTT_PROP_RESPONSE_INFORMATION && identifier != MQTT_PROP_SERVER_REFERENCE && identifier != MQTT_PROP_REASON_STRING){ return MOSQ_ERR_INVAL; } prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; if(value && strlen(value)){ prop->value.s.v = mosquitto__strdup(value); if(!prop->value.s.v){ mosquitto__free(prop); return MOSQ_ERR_NOMEM; } prop->value.s.len = strlen(value); } property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_add_string_pair(mosquitto_property **proplist, int identifier, const char *name, const char *value) { mosquitto_property *prop; if(!proplist) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_USER_PROPERTY) return MOSQ_ERR_INVAL; if(name){ if(mosquitto_validate_utf8(name, strlen(name))) return MOSQ_ERR_MALFORMED_UTF8; } if(value){ if(mosquitto_validate_utf8(value, strlen(value))) return MOSQ_ERR_MALFORMED_UTF8; } prop = mosquitto__calloc(1, sizeof(mosquitto_property)); if(!prop) return MOSQ_ERR_NOMEM; prop->client_generated = true; prop->identifier = identifier; if(name && strlen(name)){ prop->name.v = mosquitto__strdup(name); if(!prop->name.v){ mosquitto__free(prop); return MOSQ_ERR_NOMEM; } prop->name.len = strlen(name); } if(value && strlen(value)){ prop->value.s.v = mosquitto__strdup(value); if(!prop->value.s.v){ mosquitto__free(prop->name.v); mosquitto__free(prop); return MOSQ_ERR_NOMEM; } prop->value.s.len = strlen(value); } property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } int mosquitto_property_check_all(int command, const mosquitto_property *properties) { const mosquitto_property *p, *tail; int rc; p = properties; while(p){ /* Validity checks */ if(p->identifier == MQTT_PROP_REQUEST_PROBLEM_INFORMATION || p->identifier == MQTT_PROP_REQUEST_RESPONSE_INFORMATION || p->identifier == MQTT_PROP_MAXIMUM_QOS || p->identifier == MQTT_PROP_RETAIN_AVAILABLE || p->identifier == MQTT_PROP_WILDCARD_SUB_AVAILABLE || p->identifier == MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE || p->identifier == MQTT_PROP_SHARED_SUB_AVAILABLE){ if(p->value.i8 > 1){ return MOSQ_ERR_PROTOCOL; } }else if(p->identifier == MQTT_PROP_MAXIMUM_PACKET_SIZE){ if( p->value.i32 == 0){ return MOSQ_ERR_PROTOCOL; } }else if(p->identifier == MQTT_PROP_RECEIVE_MAXIMUM || p->identifier == MQTT_PROP_TOPIC_ALIAS){ if(p->value.i16 == 0){ return MOSQ_ERR_PROTOCOL; } } /* Check for properties on incorrect commands */ rc = mosquitto_property_check_command(command, p->identifier); if(rc) return rc; /* Check for duplicates */ tail = p->next; while(tail){ if(p->identifier == tail->identifier && p->identifier != MQTT_PROP_USER_PROPERTY){ return MOSQ_ERR_DUPLICATE_PROPERTY; } tail = tail->next; } p = p->next; } return MOSQ_ERR_SUCCESS; } const mosquitto_property *property__get_property(const mosquitto_property *proplist, int identifier, bool skip_first) { const mosquitto_property *p; bool is_first = true; p = proplist; while(p){ if(p->identifier == identifier){ if(!is_first || !skip_first){ return p; } is_first = false; } p = p->next; } return NULL; } const mosquitto_property *mosquitto_property_read_byte(const mosquitto_property *proplist, int identifier, uint8_t *value, bool skip_first) { const mosquitto_property *p; if(!proplist) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_PAYLOAD_FORMAT_INDICATOR && p->identifier != MQTT_PROP_REQUEST_PROBLEM_INFORMATION && p->identifier != MQTT_PROP_REQUEST_RESPONSE_INFORMATION && p->identifier != MQTT_PROP_MAXIMUM_QOS && p->identifier != MQTT_PROP_RETAIN_AVAILABLE && p->identifier != MQTT_PROP_WILDCARD_SUB_AVAILABLE && p->identifier != MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE && p->identifier != MQTT_PROP_SHARED_SUB_AVAILABLE){ return NULL; } if(value) *value = p->value.i8; return p; } const mosquitto_property *mosquitto_property_read_int16(const mosquitto_property *proplist, int identifier, uint16_t *value, bool skip_first) { const mosquitto_property *p; if(!proplist) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_SERVER_KEEP_ALIVE && p->identifier != MQTT_PROP_RECEIVE_MAXIMUM && p->identifier != MQTT_PROP_TOPIC_ALIAS_MAXIMUM && p->identifier != MQTT_PROP_TOPIC_ALIAS){ return NULL; } if(value) *value = p->value.i16; return p; } const mosquitto_property *mosquitto_property_read_int32(const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first) { const mosquitto_property *p; if(!proplist) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_MESSAGE_EXPIRY_INTERVAL && p->identifier != MQTT_PROP_SESSION_EXPIRY_INTERVAL && p->identifier != MQTT_PROP_WILL_DELAY_INTERVAL && p->identifier != MQTT_PROP_MAXIMUM_PACKET_SIZE){ return NULL; } if(value) *value = p->value.i32; return p; } const mosquitto_property *mosquitto_property_read_varint(const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first) { const mosquitto_property *p; if(!proplist) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_SUBSCRIPTION_IDENTIFIER){ return NULL; } if(value) *value = p->value.varint; return p; } const mosquitto_property *mosquitto_property_read_binary(const mosquitto_property *proplist, int identifier, void **value, uint16_t *len, bool skip_first) { const mosquitto_property *p; if(!proplist || (value && !len) || (!value && len)) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_CORRELATION_DATA && p->identifier != MQTT_PROP_AUTHENTICATION_DATA){ return NULL; } if(value){ *len = p->value.bin.len; *value = malloc(*len); if(!(*value)) return NULL; memcpy(*value, p->value.bin.v, *len); } return p; } const mosquitto_property *mosquitto_property_read_string(const mosquitto_property *proplist, int identifier, char **value, bool skip_first) { const mosquitto_property *p; if(!proplist) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_CONTENT_TYPE && p->identifier != MQTT_PROP_RESPONSE_TOPIC && p->identifier != MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER && p->identifier != MQTT_PROP_AUTHENTICATION_METHOD && p->identifier != MQTT_PROP_RESPONSE_INFORMATION && p->identifier != MQTT_PROP_SERVER_REFERENCE && p->identifier != MQTT_PROP_REASON_STRING){ return NULL; } if(value){ *value = calloc(1, p->value.s.len+1); if(!(*value)) return NULL; memcpy(*value, p->value.s.v, p->value.s.len); } return p; } const mosquitto_property *mosquitto_property_read_string_pair(const mosquitto_property *proplist, int identifier, char **name, char **value, bool skip_first) { const mosquitto_property *p; if(!proplist) return NULL; p = property__get_property(proplist, identifier, skip_first); if(!p) return NULL; if(p->identifier != MQTT_PROP_USER_PROPERTY) return NULL; if(name){ *name = calloc(1, p->name.len+1); if(!(*name)) return NULL; memcpy(*name, p->name.v, p->name.len); } if(value){ *value = calloc(1, p->value.s.len+1); if(!(*value)){ if(name){ free(*name); *name = NULL; } return NULL; } memcpy(*value, p->value.s.v, p->value.s.len); } return p; } int mosquitto_property_copy_all(mosquitto_property **dest, const mosquitto_property *src) { mosquitto_property *pnew, *plast = NULL; if(!src) return MOSQ_ERR_SUCCESS; if(!dest) return MOSQ_ERR_INVAL; *dest = NULL; while(src){ pnew = calloc(1, sizeof(mosquitto_property)); if(!pnew){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } if(plast){ plast->next = pnew; }else{ *dest = pnew; } plast = pnew; pnew->identifier = src->identifier; switch(pnew->identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: case MQTT_PROP_MAXIMUM_QOS: case MQTT_PROP_RETAIN_AVAILABLE: case MQTT_PROP_WILDCARD_SUB_AVAILABLE: case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: case MQTT_PROP_SHARED_SUB_AVAILABLE: pnew->value.i8 = src->value.i8; break; case MQTT_PROP_SERVER_KEEP_ALIVE: case MQTT_PROP_RECEIVE_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: case MQTT_PROP_TOPIC_ALIAS: pnew->value.i16 = src->value.i16; break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: case MQTT_PROP_SESSION_EXPIRY_INTERVAL: case MQTT_PROP_WILL_DELAY_INTERVAL: case MQTT_PROP_MAXIMUM_PACKET_SIZE: pnew->value.i32 = src->value.i32; break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: pnew->value.varint = src->value.varint; break; case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: case MQTT_PROP_AUTHENTICATION_METHOD: case MQTT_PROP_RESPONSE_INFORMATION: case MQTT_PROP_SERVER_REFERENCE: case MQTT_PROP_REASON_STRING: pnew->value.s.len = src->value.s.len; pnew->value.s.v = strdup(src->value.s.v); if(!pnew->value.s.v){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } break; case MQTT_PROP_AUTHENTICATION_DATA: case MQTT_PROP_CORRELATION_DATA: pnew->value.bin.len = src->value.bin.len; pnew->value.bin.v = malloc(pnew->value.bin.len); if(!pnew->value.bin.v){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } memcpy(pnew->value.bin.v, src->value.bin.v, pnew->value.bin.len); break; case MQTT_PROP_USER_PROPERTY: pnew->value.s.len = src->value.s.len; pnew->value.s.v = strdup(src->value.s.v); if(!pnew->value.s.v){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } pnew->name.len = src->name.len; pnew->name.v = strdup(src->name.v); if(!pnew->name.v){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } break; default: mosquitto_property_free_all(dest); return MOSQ_ERR_INVAL; } src = src->next; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/utf8_mosq.c0000664000175000017500000000566013626052637015473 0ustar rogerroger/* Copyright (c) 2016-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation. */ #include "config.h" #include #include "mosquitto.h" int mosquitto_validate_utf8(const char *str, int len) { int i; int j; int codelen; int codepoint; const unsigned char *ustr = (const unsigned char *)str; if(!str) return MOSQ_ERR_INVAL; if(len < 0 || len > 65536) return MOSQ_ERR_INVAL; for(i=0; i 0xF4){ /* Invalid, this would produce values > 0x10FFFF. */ return MOSQ_ERR_MALFORMED_UTF8; } codelen = 4; codepoint = (ustr[i] & 0x07); }else{ /* Unexpected continuation byte. */ return MOSQ_ERR_MALFORMED_UTF8; } /* Reconstruct full code point */ if(i == len-codelen+1){ /* Not enough data */ return MOSQ_ERR_MALFORMED_UTF8; } for(j=0; j= 0xD800 && codepoint <= 0xDFFF){ return MOSQ_ERR_MALFORMED_UTF8; } /* Check for overlong or out of range encodings */ /* Checking codelen == 2 isn't necessary here, because it is already * covered above in the C0 and C1 checks. * if(codelen == 2 && codepoint < 0x0080){ * return MOSQ_ERR_MALFORMED_UTF8; * }else */ if(codelen == 3 && codepoint < 0x0800){ return MOSQ_ERR_MALFORMED_UTF8; }else if(codelen == 4 && (codepoint < 0x10000 || codepoint > 0x10FFFF)){ return MOSQ_ERR_MALFORMED_UTF8; } /* Check for non-characters */ if(codepoint >= 0xFDD0 && codepoint <= 0xFDEF){ return MOSQ_ERR_MALFORMED_UTF8; } if((codepoint & 0xFFFF) == 0xFFFE || (codepoint & 0xFFFF) == 0xFFFF){ return MOSQ_ERR_MALFORMED_UTF8; } /* Check for control characters */ if(codepoint <= 0x001F || (codepoint >= 0x007F && codepoint <= 0x009F)){ return MOSQ_ERR_MALFORMED_UTF8; } } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/srv_mosq.c0000664000175000017500000000545713626052637015423 0ustar rogerroger/* Copyright (c) 2013-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_SRV # include # include # include # include #endif #include "logging_mosq.h" #include "memory_mosq.h" #include "mosquitto_internal.h" #include "mosquitto.h" #include "util_mosq.h" #ifdef WITH_SRV static void srv_callback(void *arg, int status, int timeouts, unsigned char *abuf, int alen) { struct mosquitto *mosq = arg; struct ares_srv_reply *reply = NULL; if(status == ARES_SUCCESS){ status = ares_parse_srv_reply(abuf, alen, &reply); if(status == ARES_SUCCESS){ // FIXME - choose which answer to use based on rfc2782 page 3. */ mosquitto_connect(mosq, reply->host, reply->port, mosq->keepalive); } }else{ log__printf(mosq, MOSQ_LOG_ERR, "Error: SRV lookup failed (%d).", status); /* FIXME - calling on_disconnect here isn't correct. */ pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_disconnect){ mosq->in_callback = true; mosq->on_disconnect(mosq, mosq->userdata, MOSQ_ERR_LOOKUP); mosq->in_callback = false; } if(mosq->on_disconnect_v5){ mosq->in_callback = true; mosq->on_disconnect_v5(mosq, mosq->userdata, MOSQ_ERR_LOOKUP, NULL); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); } } #endif int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address) { #ifdef WITH_SRV char *h; int rc; if(!mosq) return MOSQ_ERR_INVAL; rc = ares_init(&mosq->achan); if(rc != ARES_SUCCESS){ return MOSQ_ERR_UNKNOWN; } if(!host){ // get local domain }else{ #ifdef WITH_TLS if(mosq->tls_cafile || mosq->tls_capath || mosq->tls_psk){ h = mosquitto__malloc(strlen(host) + strlen("_secure-mqtt._tcp.") + 1); if(!h) return MOSQ_ERR_NOMEM; sprintf(h, "_secure-mqtt._tcp.%s", host); }else{ #endif h = mosquitto__malloc(strlen(host) + strlen("_mqtt._tcp.") + 1); if(!h) return MOSQ_ERR_NOMEM; sprintf(h, "_mqtt._tcp.%s", host); #ifdef WITH_TLS } #endif ares_search(mosq->achan, h, ns_c_in, ns_t_srv, srv_callback, mosq); mosquitto__free(h); } mosquitto__set_state(mosq, mosq_cs_connect_srv); mosq->keepalive = keepalive; return MOSQ_ERR_SUCCESS; #else UNUSED(mosq); UNUSED(host); UNUSED(keepalive); UNUSED(bind_address); return MOSQ_ERR_NOT_SUPPORTED; #endif } mosquitto-1.6.9/lib/util_topic.c0000664000175000017500000001523713626052637015722 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #ifdef WIN32 # include # include # include # include #else # include #endif #ifdef WITH_BROKER #include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "memory_mosq.h" #include "net_mosq.h" #include "send_mosq.h" #include "time_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" /* Check that a topic used for publishing is valid. * Search for + or # in a topic. Return MOSQ_ERR_INVAL if found. * Also returns MOSQ_ERR_INVAL if the topic string is too long. * Returns MOSQ_ERR_SUCCESS if everything is fine. */ int mosquitto_pub_topic_check(const char *str) { int len = 0; #ifdef WITH_BROKER int hier_count = 0; #endif while(str && str[0]){ if(str[0] == '+' || str[0] == '#'){ return MOSQ_ERR_INVAL; } #ifdef WITH_BROKER else if(str[0] == '/'){ hier_count++; } #endif len++; str = &str[1]; } if(len > 65535) return MOSQ_ERR_INVAL; #ifdef WITH_BROKER if(hier_count > TOPIC_HIERARCHY_LIMIT) return MOSQ_ERR_INVAL; #endif return MOSQ_ERR_SUCCESS; } int mosquitto_pub_topic_check2(const char *str, size_t len) { size_t i; #ifdef WITH_BROKER int hier_count = 0; #endif if(len > 65535) return MOSQ_ERR_INVAL; for(i=0; i TOPIC_HIERARCHY_LIMIT) return MOSQ_ERR_INVAL; #endif return MOSQ_ERR_SUCCESS; } /* Check that a topic used for subscriptions is valid. * Search for + or # in a topic, check they aren't in invalid positions such as * foo/#/bar, foo/+bar or foo/bar#. * Return MOSQ_ERR_INVAL if invalid position found. * Also returns MOSQ_ERR_INVAL if the topic string is too long. * Returns MOSQ_ERR_SUCCESS if everything is fine. */ int mosquitto_sub_topic_check(const char *str) { char c = '\0'; int len = 0; #ifdef WITH_BROKER int hier_count = 0; #endif while(str && str[0]){ if(str[0] == '+'){ if((c != '\0' && c != '/') || (str[1] != '\0' && str[1] != '/')){ return MOSQ_ERR_INVAL; } }else if(str[0] == '#'){ if((c != '\0' && c != '/') || str[1] != '\0'){ return MOSQ_ERR_INVAL; } } #ifdef WITH_BROKER else if(str[0] == '/'){ hier_count++; } #endif len++; c = str[0]; str = &str[1]; } if(len > 65535) return MOSQ_ERR_INVAL; #ifdef WITH_BROKER if(hier_count > TOPIC_HIERARCHY_LIMIT) return MOSQ_ERR_INVAL; #endif return MOSQ_ERR_SUCCESS; } int mosquitto_sub_topic_check2(const char *str, size_t len) { char c = '\0'; size_t i; #ifdef WITH_BROKER int hier_count = 0; #endif if(len > 65535) return MOSQ_ERR_INVAL; for(i=0; i TOPIC_HIERARCHY_LIMIT) return MOSQ_ERR_INVAL; #endif return MOSQ_ERR_SUCCESS; } int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result) { return mosquitto_topic_matches_sub2(sub, 0, topic, 0, result); } /* Does a topic match a subscription? */ int mosquitto_topic_matches_sub2(const char *sub, size_t sublen, const char *topic, size_t topiclen, bool *result) { size_t spos; UNUSED(sublen); UNUSED(topiclen); if(!result) return MOSQ_ERR_INVAL; *result = false; if(!sub || !topic || sub[0] == 0 || topic[0] == 0){ return MOSQ_ERR_INVAL; } if((sub[0] == '$' && topic[0] != '$') || (topic[0] == '$' && sub[0] != '$')){ return MOSQ_ERR_SUCCESS; } spos = 0; while(sub[0] != 0){ if(topic[0] == '+' || topic[0] == '#'){ return MOSQ_ERR_INVAL; } if(sub[0] != topic[0] || topic[0] == 0){ /* Check for wildcard matches */ if(sub[0] == '+'){ /* Check for bad "+foo" or "a/+foo" subscription */ if(spos > 0 && sub[-1] != '/'){ return MOSQ_ERR_INVAL; } /* Check for bad "foo+" or "foo+/a" subscription */ if(sub[1] != 0 && sub[1] != '/'){ return MOSQ_ERR_INVAL; } spos++; sub++; while(topic[0] != 0 && topic[0] != '/'){ if(topic[0] == '+' || topic[0] == '#'){ return MOSQ_ERR_INVAL; } topic++; } if(topic[0] == 0 && sub[0] == 0){ *result = true; return MOSQ_ERR_SUCCESS; } }else if(sub[0] == '#'){ /* Check for bad "foo#" subscription */ if(spos > 0 && sub[-1] != '/'){ return MOSQ_ERR_INVAL; } /* Check for # not the final character of the sub, e.g. "#foo" */ if(sub[1] != 0){ return MOSQ_ERR_INVAL; }else{ while(topic[0] != 0){ if(topic[0] == '+' || topic[0] == '#'){ return MOSQ_ERR_INVAL; } topic++; } *result = true; return MOSQ_ERR_SUCCESS; } }else{ /* Check for e.g. foo/bar matching foo/+/# */ if(topic[0] == 0 && spos > 0 && sub[-1] == '+' && sub[0] == '/' && sub[1] == '#') { *result = true; return MOSQ_ERR_SUCCESS; } /* There is no match at this point, but is the sub invalid? */ while(sub[0] != 0){ if(sub[0] == '#' && sub[1] != 0){ return MOSQ_ERR_INVAL; } spos++; sub++; } /* Valid input, but no match */ return MOSQ_ERR_SUCCESS; } }else{ /* sub[spos] == topic[tpos] */ if(topic[1] == 0){ /* Check for e.g. foo matching foo/# */ if(sub[1] == '/' && sub[2] == '#' && sub[3] == 0){ *result = true; return MOSQ_ERR_SUCCESS; } } spos++; sub++; topic++; if(sub[0] == 0 && topic[0] == 0){ *result = true; return MOSQ_ERR_SUCCESS; }else if(topic[0] == 0 && sub[0] == '+' && sub[1] == 0){ if(spos > 0 && sub[-1] != '/'){ return MOSQ_ERR_INVAL; } spos++; sub++; *result = true; return MOSQ_ERR_SUCCESS; } } } if((topic[0] != 0 || sub[0] != 0)){ *result = false; } while(topic[0] != 0){ if(topic[0] == '+' || topic[0] == '#'){ return MOSQ_ERR_INVAL; } topic++; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/mosquitto_internal.h0000664000175000017500000002211413626052637017504 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. Tatsuzo Osawa - Add epoll. */ #ifndef MOSQUITTO_INTERNAL_H #define MOSQUITTO_INTERNAL_H #include "config.h" #ifdef WIN32 # include #endif #ifdef WITH_TLS # include #else # include #endif #include #if defined(WITH_THREADING) && !defined(WITH_BROKER) # include #else # include #endif #ifdef WITH_SRV # include #endif #ifdef WIN32 # if _MSC_VER < 1600 typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; # else # include # endif #else # include #endif #include "mosquitto.h" #include "time_mosq.h" #ifdef WITH_BROKER # ifdef __linux__ # include # endif # include "uthash.h" struct mosquitto_client_msg; #endif #ifdef WIN32 typedef SOCKET mosq_sock_t; #else typedef int mosq_sock_t; #endif enum mosquitto_msg_direction { mosq_md_in = 0, mosq_md_out = 1 }; enum mosquitto_msg_state { mosq_ms_invalid = 0, mosq_ms_publish_qos0 = 1, mosq_ms_publish_qos1 = 2, mosq_ms_wait_for_puback = 3, mosq_ms_publish_qos2 = 4, mosq_ms_wait_for_pubrec = 5, mosq_ms_resend_pubrel = 6, mosq_ms_wait_for_pubrel = 7, mosq_ms_resend_pubcomp = 8, mosq_ms_wait_for_pubcomp = 9, mosq_ms_send_pubrec = 10, mosq_ms_queued = 11 }; enum mosquitto_client_state { mosq_cs_new = 0, mosq_cs_connected = 1, mosq_cs_disconnecting = 2, mosq_cs_active = 3, mosq_cs_connect_pending = 4, mosq_cs_connect_srv = 5, mosq_cs_disconnect_ws = 6, mosq_cs_disconnected = 7, mosq_cs_socks5_new = 8, mosq_cs_socks5_start = 9, mosq_cs_socks5_request = 10, mosq_cs_socks5_reply = 11, mosq_cs_socks5_auth_ok = 12, mosq_cs_socks5_userpass_reply = 13, mosq_cs_socks5_send_userpass = 14, mosq_cs_expiring = 15, mosq_cs_duplicate = 17, /* client that has been taken over by another with the same id */ mosq_cs_disconnect_with_will = 18, mosq_cs_disused = 19, /* client that has been added to the disused list to be freed */ mosq_cs_authenticating = 20, /* Client has sent CONNECT but is still undergoing extended authentication */ mosq_cs_reauthenticating = 21, /* Client is undergoing reauthentication and shouldn't do anything else until complete */ }; enum mosquitto__protocol { mosq_p_invalid = 0, mosq_p_mqtt31 = 1, mosq_p_mqtt311 = 2, mosq_p_mqtts = 3, mosq_p_mqtt5 = 5, }; enum mosquitto__threaded_state { mosq_ts_none, /* No threads in use */ mosq_ts_self, /* Threads started by libmosquitto */ mosq_ts_external /* Threads started by external code */ }; enum mosquitto__transport { mosq_t_invalid = 0, mosq_t_tcp = 1, mosq_t_ws = 2, mosq_t_sctp = 3 }; struct mosquitto__alias{ char *topic; uint16_t alias; }; struct session_expiry_list { struct mosquitto *context; struct session_expiry_list *prev; struct session_expiry_list *next; }; struct mosquitto__packet{ uint8_t *payload; struct mosquitto__packet *next; uint32_t remaining_mult; uint32_t remaining_length; uint32_t packet_length; uint32_t to_process; uint32_t pos; uint16_t mid; uint8_t command; int8_t remaining_count; }; struct mosquitto_message_all{ struct mosquitto_message_all *next; struct mosquitto_message_all *prev; mosquitto_property *properties; time_t timestamp; //enum mosquitto_msg_direction direction; enum mosquitto_msg_state state; bool dup; struct mosquitto_message msg; uint32_t expiry_interval; }; #ifdef WITH_TLS enum mosquitto__keyform { mosq_k_pem = 0, mosq_k_engine = 1, }; #endif struct will_delay_list { struct mosquitto *context; struct will_delay_list *prev; struct will_delay_list *next; }; struct mosquitto_msg_data{ #ifdef WITH_BROKER struct mosquitto_client_msg *inflight; struct mosquitto_client_msg *queued; unsigned long msg_bytes; unsigned long msg_bytes12; int msg_count; int msg_count12; #else struct mosquitto_message_all *inflight; int queue_len; # ifdef WITH_THREADING pthread_mutex_t mutex; # endif #endif int inflight_quota; uint16_t inflight_maximum; }; struct mosquitto { mosq_sock_t sock; #ifndef WITH_BROKER mosq_sock_t sockpairR, sockpairW; #endif #if defined(__GLIBC__) && defined(WITH_ADNS) struct gaicb *adns; /* For getaddrinfo_a */ #endif enum mosquitto__protocol protocol; char *address; char *id; char *username; char *password; uint16_t keepalive; uint16_t last_mid; enum mosquitto_client_state state; time_t last_msg_in; time_t next_msg_out; time_t ping_t; struct mosquitto__packet in_packet; struct mosquitto__packet *current_out_packet; struct mosquitto__packet *out_packet; struct mosquitto_message_all *will; struct mosquitto__alias *aliases; struct will_delay_list *will_delay_entry; uint32_t maximum_packet_size; int alias_count; uint32_t will_delay_interval; time_t will_delay_time; #ifdef WITH_TLS SSL *ssl; SSL_CTX *ssl_ctx; char *tls_cafile; char *tls_capath; char *tls_certfile; char *tls_keyfile; int (*tls_pw_callback)(char *buf, int size, int rwflag, void *userdata); char *tls_version; char *tls_ciphers; char *tls_psk; char *tls_psk_identity; int tls_cert_reqs; bool tls_insecure; bool ssl_ctx_defaults; bool tls_ocsp_required; char *tls_engine; char *tls_engine_kpass_sha1; enum mosquitto__keyform tls_keyform; char *tls_alpn; #endif bool want_write; bool want_connect; #if defined(WITH_THREADING) && !defined(WITH_BROKER) pthread_mutex_t callback_mutex; pthread_mutex_t log_callback_mutex; pthread_mutex_t msgtime_mutex; pthread_mutex_t out_packet_mutex; pthread_mutex_t current_out_packet_mutex; pthread_mutex_t state_mutex; pthread_mutex_t mid_mutex; pthread_t thread_id; #endif bool clean_start; uint32_t session_expiry_interval; time_t session_expiry_time; #ifdef WITH_BROKER bool removed_from_by_id; /* True if removed from by_id hash */ bool is_dropping; bool is_bridge; struct mosquitto__bridge *bridge; struct mosquitto_msg_data msgs_in; struct mosquitto_msg_data msgs_out; struct mosquitto__acl_user *acl_list; struct mosquitto__listener *listener; struct mosquitto__packet *out_packet_last; struct mosquitto__subhier **subs; struct mosquitto__subshared_ref **shared_subs; char *auth_method; int sub_count; int shared_sub_count; int pollfd_index; # ifdef WITH_WEBSOCKETS # if defined(LWS_LIBRARY_VERSION_NUMBER) struct lws *wsi; # else struct libwebsocket_context *ws_context; struct libwebsocket *wsi; # endif # endif bool ws_want_write; bool assigned_id; #else # ifdef WITH_SOCKS char *socks5_host; int socks5_port; char *socks5_username; char *socks5_password; # endif void *userdata; bool in_callback; struct mosquitto_msg_data msgs_in; struct mosquitto_msg_data msgs_out; void (*on_connect)(struct mosquitto *, void *userdata, int rc); void (*on_connect_with_flags)(struct mosquitto *, void *userdata, int rc, int flags); void (*on_connect_v5)(struct mosquitto *, void *userdata, int rc, int flags, const mosquitto_property *props); void (*on_disconnect)(struct mosquitto *, void *userdata, int rc); void (*on_disconnect_v5)(struct mosquitto *, void *userdata, int rc, const mosquitto_property *props); void (*on_publish)(struct mosquitto *, void *userdata, int mid); void (*on_publish_v5)(struct mosquitto *, void *userdata, int mid, int reason_code, const mosquitto_property *props); void (*on_message)(struct mosquitto *, void *userdata, const struct mosquitto_message *message); void (*on_message_v5)(struct mosquitto *, void *userdata, const struct mosquitto_message *message, const mosquitto_property *props); void (*on_subscribe)(struct mosquitto *, void *userdata, int mid, int qos_count, const int *granted_qos); void (*on_subscribe_v5)(struct mosquitto *, void *userdata, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); void (*on_unsubscribe)(struct mosquitto *, void *userdata, int mid); void (*on_unsubscribe_v5)(struct mosquitto *, void *userdata, int mid, const mosquitto_property *props); void (*on_log)(struct mosquitto *, void *userdata, int level, const char *str); //void (*on_error)(); char *host; int port; char *bind_address; unsigned int reconnects; unsigned int reconnect_delay; unsigned int reconnect_delay_max; bool reconnect_exponential_backoff; char threaded; struct mosquitto__packet *out_packet_last; # ifdef WITH_SRV ares_channel achan; # endif #endif uint8_t maximum_qos; #ifdef WITH_BROKER UT_hash_handle hh_id; UT_hash_handle hh_sock; struct mosquitto *for_free_next; struct session_expiry_list *expiry_list_item; #endif #ifdef WITH_EPOLL uint32_t events; #endif }; #define STREMPTY(str) (str[0] == '\0') void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties); #endif mosquitto-1.6.9/lib/time_mosq.c0000664000175000017500000000243513626052637015540 0ustar rogerroger/* Copyright (c) 2013-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef __APPLE__ #include #include #endif #ifdef WIN32 # define _WIN32_WINNT _WIN32_WINNT_VISTA # include #else # include #endif #include #include "mosquitto.h" #include "time_mosq.h" time_t mosquitto_time(void) { #ifdef WIN32 return GetTickCount64()/1000; #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return tp.tv_sec; #elif defined(__APPLE__) static mach_timebase_info_data_t tb; uint64_t ticks; uint64_t sec; ticks = mach_absolute_time(); if(tb.denom == 0){ mach_timebase_info(&tb); } sec = ticks*tb.numer/tb.denom/1000000000; return (time_t)sec; #else return time(NULL); #endif } mosquitto-1.6.9/lib/thread_mosq.c0000664000175000017500000000533613626052637016054 0ustar rogerroger/* Copyright (c) 2011-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifndef WIN32 #include #endif #include "mosquitto_internal.h" #include "net_mosq.h" #include "util_mosq.h" void *mosquitto__thread_main(void *obj); int mosquitto_loop_start(struct mosquitto *mosq) { #if defined(WITH_THREADING) && defined(HAVE_PTHREAD_CANCEL) if(!mosq || mosq->threaded != mosq_ts_none) return MOSQ_ERR_INVAL; mosq->threaded = mosq_ts_self; if(!pthread_create(&mosq->thread_id, NULL, mosquitto__thread_main, mosq)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ERRNO; } #else return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_loop_stop(struct mosquitto *mosq, bool force) { #if defined(WITH_THREADING) && defined(HAVE_PTHREAD_CANCEL) # ifndef WITH_BROKER char sockpair_data = 0; # endif if(!mosq || mosq->threaded != mosq_ts_self) return MOSQ_ERR_INVAL; /* Write a single byte to sockpairW (connected to sockpairR) to break out * of select() if in threaded mode. */ if(mosq->sockpairW != INVALID_SOCKET){ #ifndef WIN32 if(write(mosq->sockpairW, &sockpair_data, 1)){ } #else send(mosq->sockpairW, &sockpair_data, 1, 0); #endif } if(force){ pthread_cancel(mosq->thread_id); } pthread_join(mosq->thread_id, NULL); mosq->thread_id = pthread_self(); mosq->threaded = mosq_ts_none; return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } #ifdef WITH_THREADING void *mosquitto__thread_main(void *obj) { struct mosquitto *mosq = obj; int state; #ifndef WIN32 struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10000000; #endif if(!mosq) return NULL; do{ state = mosquitto__get_state(mosq); if(state == mosq_cs_new){ #ifdef WIN32 Sleep(10); #else nanosleep(&ts, NULL); #endif }else{ break; } }while(1); if(!mosq->keepalive){ /* Sleep for a day if keepalive disabled. */ mosquitto_loop_forever(mosq, 1000*86400, 1); }else{ /* Sleep for our keepalive value. publish() etc. will wake us up. */ mosquitto_loop_forever(mosq, mosq->keepalive*1000, 1); } return obj; } #endif int mosquitto_threaded_set(struct mosquitto *mosq, bool threaded) { if(!mosq) return MOSQ_ERR_INVAL; if(threaded){ mosq->threaded = mosq_ts_external; }else{ mosq->threaded = mosq_ts_none; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/options.c0000664000175000017500000002545513626052637015245 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifndef WIN32 # include #endif #include #ifdef WITH_TLS # ifdef WIN32 # include # endif # include #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "memory_mosq.h" #include "misc_mosq.h" #include "mqtt_protocol.h" #include "util_mosq.h" #include "will_mosq.h" int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain) { return mosquitto_will_set_v5(mosq, topic, payloadlen, payload, qos, retain, NULL); } int mosquitto_will_set_v5(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { int rc; if(!mosq) return MOSQ_ERR_INVAL; if(properties){ rc = mosquitto_property_check_all(CMD_WILL, properties); if(rc) return rc; } return will__set(mosq, topic, payloadlen, payload, qos, retain, properties); } int mosquitto_will_clear(struct mosquitto *mosq) { if(!mosq) return MOSQ_ERR_INVAL; return will__clear(mosq); } int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username, const char *password) { if(!mosq) return MOSQ_ERR_INVAL; if(mosq->protocol == mosq_p_mqtt311 || mosq->protocol == mosq_p_mqtt31){ if(password != NULL && username == NULL){ return MOSQ_ERR_INVAL; } } mosquitto__free(mosq->username); mosq->username = NULL; mosquitto__free(mosq->password); mosq->password = NULL; if(username){ if(mosquitto_validate_utf8(username, strlen(username))){ return MOSQ_ERR_MALFORMED_UTF8; } mosq->username = mosquitto__strdup(username); if(!mosq->username) return MOSQ_ERR_NOMEM; } if(password){ mosq->password = mosquitto__strdup(password); if(!mosq->password){ mosquitto__free(mosq->username); mosq->username = NULL; return MOSQ_ERR_NOMEM; } } return MOSQ_ERR_SUCCESS; } int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff) { if(!mosq) return MOSQ_ERR_INVAL; if(reconnect_delay == 0) reconnect_delay = 1; mosq->reconnect_delay = reconnect_delay; mosq->reconnect_delay_max = reconnect_delay_max; mosq->reconnect_exponential_backoff = reconnect_exponential_backoff; return MOSQ_ERR_SUCCESS; } int mosquitto_tls_set(struct mosquitto *mosq, const char *cafile, const char *capath, const char *certfile, const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)) { #ifdef WITH_TLS FILE *fptr; if(!mosq || (!cafile && !capath) || (certfile && !keyfile) || (!certfile && keyfile)) return MOSQ_ERR_INVAL; mosquitto__free(mosq->tls_cafile); mosq->tls_cafile = NULL; if(cafile){ fptr = mosquitto__fopen(cafile, "rt", false); if(fptr){ fclose(fptr); }else{ return MOSQ_ERR_INVAL; } mosq->tls_cafile = mosquitto__strdup(cafile); if(!mosq->tls_cafile){ return MOSQ_ERR_NOMEM; } } mosquitto__free(mosq->tls_capath); mosq->tls_capath = NULL; if(capath){ mosq->tls_capath = mosquitto__strdup(capath); if(!mosq->tls_capath){ return MOSQ_ERR_NOMEM; } } mosquitto__free(mosq->tls_certfile); mosq->tls_certfile = NULL; if(certfile){ fptr = mosquitto__fopen(certfile, "rt", false); if(fptr){ fclose(fptr); }else{ mosquitto__free(mosq->tls_cafile); mosq->tls_cafile = NULL; mosquitto__free(mosq->tls_capath); mosq->tls_capath = NULL; return MOSQ_ERR_INVAL; } mosq->tls_certfile = mosquitto__strdup(certfile); if(!mosq->tls_certfile){ return MOSQ_ERR_NOMEM; } } mosquitto__free(mosq->tls_keyfile); mosq->tls_keyfile = NULL; if(keyfile){ fptr = mosquitto__fopen(keyfile, "rt", false); if(fptr){ fclose(fptr); }else{ mosquitto__free(mosq->tls_cafile); mosq->tls_cafile = NULL; mosquitto__free(mosq->tls_capath); mosq->tls_capath = NULL; mosquitto__free(mosq->tls_certfile); mosq->tls_certfile = NULL; return MOSQ_ERR_INVAL; } mosq->tls_keyfile = mosquitto__strdup(keyfile); if(!mosq->tls_keyfile){ return MOSQ_ERR_NOMEM; } } mosq->tls_pw_callback = pw_callback; return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers) { #ifdef WITH_TLS if(!mosq) return MOSQ_ERR_INVAL; mosq->tls_cert_reqs = cert_reqs; if(tls_version){ if(!strcasecmp(tls_version, "tlsv1.3") || !strcasecmp(tls_version, "tlsv1.2") || !strcasecmp(tls_version, "tlsv1.1")){ mosq->tls_version = mosquitto__strdup(tls_version); if(!mosq->tls_version) return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_INVAL; } }else{ mosq->tls_version = mosquitto__strdup("tlsv1.2"); if(!mosq->tls_version) return MOSQ_ERR_NOMEM; } if(ciphers){ mosq->tls_ciphers = mosquitto__strdup(ciphers); if(!mosq->tls_ciphers) return MOSQ_ERR_NOMEM; }else{ mosq->tls_ciphers = NULL; } return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value) { #ifdef WITH_TLS if(!mosq) return MOSQ_ERR_INVAL; mosq->tls_insecure = value; return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_string_option(struct mosquitto *mosq, enum mosq_opt_t option, const char *value) { #ifdef WITH_TLS ENGINE *eng; char *str; #endif if(!mosq) return MOSQ_ERR_INVAL; switch(option){ case MOSQ_OPT_TLS_ENGINE: #ifdef WITH_TLS # if !defined(OPENSSL_NO_ENGINE) eng = ENGINE_by_id(value); if(!eng){ return MOSQ_ERR_INVAL; } ENGINE_free(eng); /* release the structural reference from ENGINE_by_id() */ mosq->tls_engine = mosquitto__strdup(value); if(!mosq->tls_engine){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; #endif #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; case MOSQ_OPT_TLS_KEYFORM: #ifdef WITH_TLS if(!value) return MOSQ_ERR_INVAL; if(!strcasecmp(value, "pem")){ mosq->tls_keyform = mosq_k_pem; }else if (!strcasecmp(value, "engine")){ mosq->tls_keyform = mosq_k_engine; }else{ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; case MOSQ_OPT_TLS_ENGINE_KPASS_SHA1: #ifdef WITH_TLS if(mosquitto__hex2bin_sha1(value, (unsigned char**)&str) != MOSQ_ERR_SUCCESS){ return MOSQ_ERR_INVAL; } mosq->tls_engine_kpass_sha1 = str; return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; case MOSQ_OPT_TLS_ALPN: #ifdef WITH_TLS mosq->tls_alpn = mosquitto__strdup(value); if(!mosq->tls_alpn){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; default: return MOSQ_ERR_INVAL; } } int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers) { #ifdef FINAL_WITH_TLS_PSK if(!mosq || !psk || !identity) return MOSQ_ERR_INVAL; /* Check for hex only digits */ if(strspn(psk, "0123456789abcdefABCDEF") < strlen(psk)){ return MOSQ_ERR_INVAL; } mosq->tls_psk = mosquitto__strdup(psk); if(!mosq->tls_psk) return MOSQ_ERR_NOMEM; mosq->tls_psk_identity = mosquitto__strdup(identity); if(!mosq->tls_psk_identity){ mosquitto__free(mosq->tls_psk); return MOSQ_ERR_NOMEM; } if(ciphers){ mosq->tls_ciphers = mosquitto__strdup(ciphers); if(!mosq->tls_ciphers) return MOSQ_ERR_NOMEM; }else{ mosq->tls_ciphers = NULL; } return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_opts_set(struct mosquitto *mosq, enum mosq_opt_t option, void *value) { int ival; if(!mosq || !value) return MOSQ_ERR_INVAL; switch(option){ case MOSQ_OPT_PROTOCOL_VERSION: ival = *((int *)value); return mosquitto_int_option(mosq, option, ival); case MOSQ_OPT_SSL_CTX: #ifdef WITH_TLS mosq->ssl_ctx = (SSL_CTX *)value; if(mosq->ssl_ctx){ #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) SSL_CTX_up_ref(mosq->ssl_ctx); #else CRYPTO_add(&(mosq->ssl_ctx)->references, 1, CRYPTO_LOCK_SSL_CTX); #endif } break; #else return MOSQ_ERR_NOT_SUPPORTED; #endif default: return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } int mosquitto_int_option(struct mosquitto *mosq, enum mosq_opt_t option, int value) { if(!mosq) return MOSQ_ERR_INVAL; switch(option){ case MOSQ_OPT_PROTOCOL_VERSION: if(value == MQTT_PROTOCOL_V31){ mosq->protocol = mosq_p_mqtt31; }else if(value == MQTT_PROTOCOL_V311){ mosq->protocol = mosq_p_mqtt311; }else if(value == MQTT_PROTOCOL_V5){ mosq->protocol = mosq_p_mqtt5; }else{ return MOSQ_ERR_INVAL; } break; case MOSQ_OPT_RECEIVE_MAXIMUM: if(value < 0 || value > 65535){ return MOSQ_ERR_INVAL; } if(value == 0){ mosq->msgs_in.inflight_maximum = 65535; }else{ mosq->msgs_in.inflight_maximum = value; } break; case MOSQ_OPT_SEND_MAXIMUM: if(value < 0 || value > 65535){ return MOSQ_ERR_INVAL; } if(value == 0){ mosq->msgs_out.inflight_maximum = 65535; }else{ mosq->msgs_out.inflight_maximum = value; } break; case MOSQ_OPT_SSL_CTX_WITH_DEFAULTS: #if defined(WITH_TLS) && OPENSSL_VERSION_NUMBER >= 0x10100000L if(value){ mosq->ssl_ctx_defaults = true; }else{ mosq->ssl_ctx_defaults = false; } break; #else return MOSQ_ERR_NOT_SUPPORTED; #endif case MOSQ_OPT_TLS_OCSP_REQUIRED: #ifdef WITH_TLS mosq->tls_ocsp_required = (bool)value; #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; default: return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } int mosquitto_void_option(struct mosquitto *mosq, enum mosq_opt_t option, void *value) { if(!mosq || !value) return MOSQ_ERR_INVAL; switch(option){ case MOSQ_OPT_SSL_CTX: #ifdef WITH_TLS mosq->ssl_ctx = (SSL_CTX *)value; if(mosq->ssl_ctx){ #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) SSL_CTX_up_ref(mosq->ssl_ctx); #else CRYPTO_add(&(mosq->ssl_ctx)->references, 1, CRYPTO_LOCK_SSL_CTX); #endif } break; #else return MOSQ_ERR_NOT_SUPPORTED; #endif default: return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } void mosquitto_user_data_set(struct mosquitto *mosq, void *userdata) { if(mosq){ mosq->userdata = userdata; } } void *mosquitto_userdata(struct mosquitto *mosq) { return mosq->userdata; } mosquitto-1.6.9/lib/handle_pubrec.c0000664000175000017500000000621513626052637016336 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" int handle__pubrec(struct mosquitto_db *db, struct mosquitto *mosq) { uint8_t reason_code = 0; uint16_t mid; int rc; mosquitto_property *properties = NULL; int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc) return rc; if(mid == 0) return MOSQ_ERR_PROTOCOL; if(mosq->protocol == mosq_p_mqtt5 && mosq->in_packet.remaining_length > 2){ rc = packet__read_byte(&mosq->in_packet, &reason_code); if(rc) return rc; if(mosq->in_packet.remaining_length > 3){ rc = property__read_all(CMD_PUBREC, &mosq->in_packet, &properties); if(rc) return rc; /* Immediately free, we don't do anything with Reason String or User Property at the moment */ mosquitto_property_free_all(&properties); } } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PUBREC from %s (Mid: %d)", mosq->id, mid); if(reason_code < 0x80){ rc = db__message_update_outgoing(mosq, mid, mosq_ms_wait_for_pubcomp, 2); }else{ return db__message_delete_outgoing(db, mosq, mid, mosq_ms_wait_for_pubrec, 2); } #else UNUSED(db); log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PUBREC (Mid: %d)", mosq->id, mid); if(reason_code < 0x80 || mosq->protocol != mosq_p_mqtt5){ rc = message__out_update(mosq, mid, mosq_ms_wait_for_pubcomp, 2); }else{ if(!message__delete(mosq, mid, mosq_md_out, 2)){ /* Only inform the client the message has been sent once. */ pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_publish_v5){ mosq->in_callback = true; mosq->on_publish_v5(mosq, mosq->userdata, mid, reason_code, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); } util__increment_send_quota(mosq); pthread_mutex_lock(&mosq->msgs_out.mutex); message__release_to_inflight(mosq, mosq_md_out); pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_SUCCESS; } #endif if(rc == MOSQ_ERR_NOT_FOUND){ log__printf(mosq, MOSQ_LOG_WARNING, "Warning: Received PUBREC from %s for an unknown packet identifier %d.", mosq->id, mid); }else if(rc != MOSQ_ERR_SUCCESS){ return rc; } rc = send__pubrel(mosq, mid); if(rc) return rc; return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/handle_unsuback.c0000664000175000017500000000432213626052637016666 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" int handle__unsuback(struct mosquitto *mosq) { uint16_t mid; int rc; mosquitto_property *properties = NULL; int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received UNSUBACK from %s", mosq->id); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received UNSUBACK", mosq->id); #endif rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc) return rc; if(mid == 0) return MOSQ_ERR_PROTOCOL; if(mosq->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_UNSUBACK, &mosq->in_packet, &properties); if(rc) return rc; } #ifdef WITH_BROKER /* Immediately free, we don't do anything with Reason String or User Property at the moment */ mosquitto_property_free_all(&properties); #else pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_unsubscribe){ mosq->in_callback = true; mosq->on_unsubscribe(mosq, mosq->userdata, mid); mosq->in_callback = false; } if(mosq->on_unsubscribe_v5){ mosq->in_callback = true; mosq->on_unsubscribe_v5(mosq, mosq->userdata, mid, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); mosquitto_property_free_all(&properties); #endif return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/lib/connect.c0000664000175000017500000002024213626052637015170 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "memory_mosq.h" #include "packet_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "send_mosq.h" #include "socks_mosq.h" #include "util_mosq.h" static char alphanum[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static int mosquitto__reconnect(struct mosquitto *mosq, bool blocking, const mosquitto_property *properties); static int mosquitto__connect_init(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address); static int mosquitto__connect_init(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address) { int i; int rc; if(!mosq) return MOSQ_ERR_INVAL; if(!host || port <= 0) return MOSQ_ERR_INVAL; if(keepalive < 5) return MOSQ_ERR_INVAL; if(mosq->id == NULL && (mosq->protocol == mosq_p_mqtt31 || mosq->protocol == mosq_p_mqtt311)){ mosq->id = (char *)mosquitto__calloc(24, sizeof(char)); if(!mosq->id){ return MOSQ_ERR_NOMEM; } mosq->id[0] = 'm'; mosq->id[1] = 'o'; mosq->id[2] = 's'; mosq->id[3] = 'q'; mosq->id[4] = '-'; rc = util__random_bytes(&mosq->id[5], 18); if(rc) return rc; for(i=5; i<23; i++){ mosq->id[i] = alphanum[(mosq->id[i]&0x7F)%(sizeof(alphanum)-1)]; } } mosquitto__free(mosq->host); mosq->host = mosquitto__strdup(host); if(!mosq->host) return MOSQ_ERR_NOMEM; mosq->port = port; mosquitto__free(mosq->bind_address); if(bind_address){ mosq->bind_address = mosquitto__strdup(bind_address); if(!mosq->bind_address) return MOSQ_ERR_NOMEM; } mosq->keepalive = keepalive; mosq->msgs_in.inflight_quota = mosq->msgs_in.inflight_maximum; mosq->msgs_out.inflight_quota = mosq->msgs_out.inflight_maximum; if(mosq->sockpairR != INVALID_SOCKET){ COMPAT_CLOSE(mosq->sockpairR); mosq->sockpairR = INVALID_SOCKET; } if(mosq->sockpairW != INVALID_SOCKET){ COMPAT_CLOSE(mosq->sockpairW); mosq->sockpairW = INVALID_SOCKET; } if(net__socketpair(&mosq->sockpairR, &mosq->sockpairW)){ log__printf(mosq, MOSQ_LOG_WARNING, "Warning: Unable to open socket pair, outgoing publish commands may be delayed."); } return MOSQ_ERR_SUCCESS; } int mosquitto_connect(struct mosquitto *mosq, const char *host, int port, int keepalive) { return mosquitto_connect_bind(mosq, host, port, keepalive, NULL); } int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address) { return mosquitto_connect_bind_v5(mosq, host, port, keepalive, bind_address, NULL); } int mosquitto_connect_bind_v5(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties) { int rc; if(properties){ rc = mosquitto_property_check_all(CMD_CONNECT, properties); if(rc) return rc; } rc = mosquitto__connect_init(mosq, host, port, keepalive, bind_address); if(rc) return rc; mosquitto__set_state(mosq, mosq_cs_new); return mosquitto__reconnect(mosq, true, properties); } int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port, int keepalive) { return mosquitto_connect_bind_async(mosq, host, port, keepalive, NULL); } int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address) { int rc = mosquitto__connect_init(mosq, host, port, keepalive, bind_address); if(rc) return rc; return mosquitto__reconnect(mosq, false, NULL); } int mosquitto_reconnect_async(struct mosquitto *mosq) { return mosquitto__reconnect(mosq, false, NULL); } int mosquitto_reconnect(struct mosquitto *mosq) { return mosquitto__reconnect(mosq, true, NULL); } static int mosquitto__reconnect(struct mosquitto *mosq, bool blocking, const mosquitto_property *properties) { const mosquitto_property *outgoing_properties = NULL; mosquitto_property local_property; int rc; if(!mosq) return MOSQ_ERR_INVAL; if(!mosq->host || mosq->port <= 0) return MOSQ_ERR_INVAL; if(mosq->protocol != mosq_p_mqtt5 && properties) return MOSQ_ERR_NOT_SUPPORTED; if(properties){ if(properties->client_generated){ outgoing_properties = properties; }else{ memcpy(&local_property, properties, sizeof(mosquitto_property)); local_property.client_generated = true; local_property.next = NULL; outgoing_properties = &local_property; } rc = mosquitto_property_check_all(CMD_CONNECT, outgoing_properties); if(rc) return rc; } pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); mosq->next_msg_out = mosq->last_msg_in + mosq->keepalive; pthread_mutex_unlock(&mosq->msgtime_mutex); mosq->ping_t = 0; packet__cleanup(&mosq->in_packet); packet__cleanup_all(mosq); message__reconnect_reset(mosq); if(mosq->sock != INVALID_SOCKET){ net__socket_close(mosq); //close socket } #ifdef WITH_SOCKS if(mosq->socks5_host){ rc = net__socket_connect(mosq, mosq->socks5_host, mosq->socks5_port, mosq->bind_address, blocking); }else #endif { rc = net__socket_connect(mosq, mosq->host, mosq->port, mosq->bind_address, blocking); } if(rc>0){ mosquitto__set_state(mosq, mosq_cs_connect_pending); return rc; } #ifdef WITH_SOCKS if(mosq->socks5_host){ mosquitto__set_state(mosq, mosq_cs_socks5_new); return socks5__send(mosq); }else #endif { mosquitto__set_state(mosq, mosq_cs_connected); rc = send__connect(mosq, mosq->keepalive, mosq->clean_start, outgoing_properties); if(rc){ packet__cleanup_all(mosq); net__socket_close(mosq); mosquitto__set_state(mosq, mosq_cs_new); } return rc; } } int mosquitto_disconnect(struct mosquitto *mosq) { return mosquitto_disconnect_v5(mosq, 0, NULL); } int mosquitto_disconnect_v5(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties) { const mosquitto_property *outgoing_properties = NULL; mosquitto_property local_property; int rc; if(!mosq) return MOSQ_ERR_INVAL; if(mosq->protocol != mosq_p_mqtt5 && properties) return MOSQ_ERR_NOT_SUPPORTED; if(properties){ if(properties->client_generated){ outgoing_properties = properties; }else{ memcpy(&local_property, properties, sizeof(mosquitto_property)); local_property.client_generated = true; local_property.next = NULL; outgoing_properties = &local_property; } rc = mosquitto_property_check_all(CMD_DISCONNECT, outgoing_properties); if(rc) return rc; } mosquitto__set_state(mosq, mosq_cs_disconnected); if(mosq->sock == INVALID_SOCKET){ return MOSQ_ERR_NO_CONN; }else{ return send__disconnect(mosq, reason_code, outgoing_properties); } } void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties) { mosquitto__set_state(mosq, mosq_cs_disconnected); net__socket_close(mosq); /* Free data and reset values */ pthread_mutex_lock(&mosq->out_packet_mutex); mosq->current_out_packet = mosq->out_packet; if(mosq->out_packet){ mosq->out_packet = mosq->out_packet->next; if(!mosq->out_packet){ mosq->out_packet_last = NULL; } } pthread_mutex_unlock(&mosq->out_packet_mutex); pthread_mutex_lock(&mosq->msgtime_mutex); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; pthread_mutex_unlock(&mosq->msgtime_mutex); pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_disconnect){ mosq->in_callback = true; mosq->on_disconnect(mosq, mosq->userdata, reason_code); mosq->in_callback = false; } if(mosq->on_disconnect_v5){ mosq->in_callback = true; mosq->on_disconnect_v5(mosq, mosq->userdata, reason_code, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); pthread_mutex_unlock(&mosq->current_out_packet_mutex); } mosquitto-1.6.9/lib/read_handle.h0000664000175000017500000000253313626052637015775 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef READ_HANDLE_H #define READ_HANDLE_H #include "mosquitto.h" struct mosquitto_db; int handle__pingreq(struct mosquitto *mosq); int handle__pingresp(struct mosquitto *mosq); #ifdef WITH_BROKER int handle__pubackcomp(struct mosquitto_db *db, struct mosquitto *mosq, const char *type); #else int handle__packet(struct mosquitto *mosq); int handle__connack(struct mosquitto *mosq); int handle__disconnect(struct mosquitto *mosq); int handle__pubackcomp(struct mosquitto *mosq, const char *type); int handle__publish(struct mosquitto *mosq); int handle__auth(struct mosquitto *mosq); #endif int handle__pubrec(struct mosquitto_db *db, struct mosquitto *mosq); int handle__pubrel(struct mosquitto_db *db, struct mosquitto *mosq); int handle__suback(struct mosquitto *mosq); int handle__unsuback(struct mosquitto *mosq); #endif mosquitto-1.6.9/lib/helpers.c0000664000175000017500000001146313626052637015206 0ustar rogerroger/* Copyright (c) 2016-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto.h" #include "mosquitto_internal.h" struct userdata__callback { const char *topic; int (*callback)(struct mosquitto *, void *, const struct mosquitto_message *); void *userdata; int qos; }; struct userdata__simple { struct mosquitto_message *messages; int max_msg_count; int message_count; bool want_retained; }; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { struct userdata__callback *userdata = obj; UNUSED(rc); mosquitto_subscribe(mosq, NULL, userdata->topic, userdata->qos); } static void on_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) { int rc; struct userdata__callback *userdata = obj; rc = userdata->callback(mosq, userdata->userdata, message); if(rc){ mosquitto_disconnect(mosq); } } static int on_message_simple(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) { struct userdata__simple *userdata = obj; int rc; if(userdata->max_msg_count == 0){ return 0; } /* Don't process stale retained messages if 'want_retained' was false */ if(!userdata->want_retained && message->retain){ return 0; } userdata->max_msg_count--; rc = mosquitto_message_copy(&userdata->messages[userdata->message_count], message); if(rc){ return rc; } userdata->message_count++; if(userdata->max_msg_count == 0){ mosquitto_disconnect(mosq); } return 0; } libmosq_EXPORT int mosquitto_subscribe_simple( struct mosquitto_message **messages, int msg_count, bool want_retained, const char *topic, int qos, const char *host, int port, const char *client_id, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls) { struct userdata__simple userdata; int rc; int i; if(!topic || msg_count < 1 || !messages){ return MOSQ_ERR_INVAL; } *messages = NULL; userdata.messages = calloc(sizeof(struct mosquitto_message), msg_count); if(!userdata.messages){ return MOSQ_ERR_NOMEM; } userdata.message_count = 0; userdata.max_msg_count = msg_count; userdata.want_retained = want_retained; rc = mosquitto_subscribe_callback( on_message_simple, &userdata, topic, qos, host, port, client_id, keepalive, clean_session, username, password, will, tls); if(!rc && userdata.max_msg_count == 0){ *messages = userdata.messages; return MOSQ_ERR_SUCCESS; }else{ for(i=0; itopic, will->payloadlen, will->payload, will->qos, will->retain); if(rc){ mosquitto_destroy(mosq); return rc; } } if(username){ rc = mosquitto_username_pw_set(mosq, username, password); if(rc){ mosquitto_destroy(mosq); return rc; } } if(tls){ rc = mosquitto_tls_set(mosq, tls->cafile, tls->capath, tls->certfile, tls->keyfile, tls->pw_callback); if(rc){ mosquitto_destroy(mosq); return rc; } rc = mosquitto_tls_opts_set(mosq, tls->cert_reqs, tls->tls_version, tls->ciphers); if(rc){ mosquitto_destroy(mosq); return rc; } } mosquitto_connect_callback_set(mosq, on_connect); mosquitto_message_callback_set(mosq, on_message_callback); rc = mosquitto_connect(mosq, host, port, keepalive); if(rc){ mosquitto_destroy(mosq); return rc; } rc = mosquitto_loop_forever(mosq, -1, 1); mosquitto_destroy(mosq); return rc; } mosquitto-1.6.9/lib/cpp/0000775000175000017500000000000013626052637014155 5ustar rogerrogermosquitto-1.6.9/lib/cpp/CMakeLists.txt0000664000175000017500000000231113626052637016712 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/lib/cpp ${STDBOOL_H_PATH} ${STDINT_H_PATH}) link_directories(${mosquitto_BINARY_DIR}/lib) set(CPP_SRC mosquittopp.cpp mosquittopp.h) add_library(mosquittopp SHARED ${CPP_SRC}) set_target_properties(mosquittopp PROPERTIES POSITION_INDEPENDENT_CODE 1 ) target_link_libraries(mosquittopp libmosquitto) set_target_properties(mosquittopp PROPERTIES VERSION ${VERSION} SOVERSION 1 ) install(TARGETS mosquittopp RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") if (WITH_STATIC_LIBRARIES) add_library(mosquittopp_static STATIC ${C_SRC} ${CPP_SRC} ) if (WITH_PIC) set_target_properties(mosquittopp_static PROPERTIES POSITION_INDEPENDENT_CODE 1 ) endif (WITH_PIC) target_link_libraries(mosquittopp_static ${LIBRARIES}) set_target_properties(mosquittopp_static PROPERTIES OUTPUT_NAME mosquittopp_static VERSION ${VERSION} ) target_compile_definitions(mosquittopp_static PUBLIC "LIBMOSQUITTO_STATIC") install(TARGETS mosquittopp_static ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}") endif (WITH_STATIC_LIBRARIES) install(FILES mosquittopp.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") mosquitto-1.6.9/lib/cpp/mosquittopp.cpp0000664000175000017500000002335313626052637017273 0ustar rogerroger/* Copyright (c) 2010-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include #include #include #define UNUSED(A) (void)(A) namespace mosqpp { static void on_connect_wrapper(struct mosquitto *mosq, void *userdata, int rc) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_connect(rc); } static void on_connect_with_flags_wrapper(struct mosquitto *mosq, void *userdata, int rc, int flags) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_connect_with_flags(rc, flags); } static void on_disconnect_wrapper(struct mosquitto *mosq, void *userdata, int rc) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_disconnect(rc); } static void on_publish_wrapper(struct mosquitto *mosq, void *userdata, int mid) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_publish(mid); } static void on_message_wrapper(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_message(message); } static void on_subscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_subscribe(mid, qos_count, granted_qos); } static void on_unsubscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_unsubscribe(mid); } static void on_log_wrapper(struct mosquitto *mosq, void *userdata, int level, const char *str) { class mosquittopp *m = (class mosquittopp *)userdata; UNUSED(mosq); m->on_log(level, str); } int lib_version(int *major, int *minor, int *revision) { if(major) *major = LIBMOSQUITTO_MAJOR; if(minor) *minor = LIBMOSQUITTO_MINOR; if(revision) *revision = LIBMOSQUITTO_REVISION; return LIBMOSQUITTO_VERSION_NUMBER; } int lib_init() { return mosquitto_lib_init(); } int lib_cleanup() { return mosquitto_lib_cleanup(); } const char* strerror(int mosq_errno) { return mosquitto_strerror(mosq_errno); } const char* connack_string(int connack_code) { return mosquitto_connack_string(connack_code); } int sub_topic_tokenise(const char *subtopic, char ***topics, int *count) { return mosquitto_sub_topic_tokenise(subtopic, topics, count); } int sub_topic_tokens_free(char ***topics, int count) { return mosquitto_sub_topic_tokens_free(topics, count); } int topic_matches_sub(const char *sub, const char *topic, bool *result) { return mosquitto_topic_matches_sub(sub, topic, result); } int validate_utf8(const char *str, int len) { return mosquitto_validate_utf8(str, len); } int subscribe_simple( struct mosquitto_message **messages, int msg_count, bool retained, const char *topic, int qos, const char *host, int port, const char *client_id, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls) { return mosquitto_subscribe_simple( messages, msg_count, retained, topic, qos, host, port, client_id, keepalive, clean_session, username, password, will, tls); } mosqpp_EXPORT int subscribe_callback( int (*callback)(struct mosquitto *, void *, const struct mosquitto_message *), void *userdata, const char *topic, int qos, const char *host, int port, const char *client_id, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls) { return mosquitto_subscribe_callback( callback, userdata, topic, qos, host, port, client_id, keepalive, clean_session, username, password, will, tls); } mosquittopp::mosquittopp(const char *id, bool clean_session) { m_mosq = mosquitto_new(id, clean_session, this); mosquitto_connect_callback_set(m_mosq, on_connect_wrapper); mosquitto_connect_with_flags_callback_set(m_mosq, on_connect_with_flags_wrapper); mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper); mosquitto_publish_callback_set(m_mosq, on_publish_wrapper); mosquitto_message_callback_set(m_mosq, on_message_wrapper); mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper); mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper); mosquitto_log_callback_set(m_mosq, on_log_wrapper); } mosquittopp::~mosquittopp() { mosquitto_destroy(m_mosq); } int mosquittopp::reinitialise(const char *id, bool clean_session) { int rc; rc = mosquitto_reinitialise(m_mosq, id, clean_session, this); if(rc == MOSQ_ERR_SUCCESS){ mosquitto_connect_callback_set(m_mosq, on_connect_wrapper); mosquitto_connect_with_flags_callback_set(m_mosq, on_connect_with_flags_wrapper); mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper); mosquitto_publish_callback_set(m_mosq, on_publish_wrapper); mosquitto_message_callback_set(m_mosq, on_message_wrapper); mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper); mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper); mosquitto_log_callback_set(m_mosq, on_log_wrapper); } return rc; } int mosquittopp::connect(const char *host, int port, int keepalive) { return mosquitto_connect(m_mosq, host, port, keepalive); } int mosquittopp::connect(const char *host, int port, int keepalive, const char *bind_address) { return mosquitto_connect_bind(m_mosq, host, port, keepalive, bind_address); } int mosquittopp::connect_async(const char *host, int port, int keepalive) { return mosquitto_connect_async(m_mosq, host, port, keepalive); } int mosquittopp::connect_async(const char *host, int port, int keepalive, const char *bind_address) { return mosquitto_connect_bind_async(m_mosq, host, port, keepalive, bind_address); } int mosquittopp::reconnect() { return mosquitto_reconnect(m_mosq); } int mosquittopp::reconnect_async() { return mosquitto_reconnect_async(m_mosq); } int mosquittopp::disconnect() { return mosquitto_disconnect(m_mosq); } int mosquittopp::socket() { return mosquitto_socket(m_mosq); } int mosquittopp::will_set(const char *topic, int payloadlen, const void *payload, int qos, bool retain) { return mosquitto_will_set(m_mosq, topic, payloadlen, payload, qos, retain); } int mosquittopp::will_clear() { return mosquitto_will_clear(m_mosq); } int mosquittopp::username_pw_set(const char *username, const char *password) { return mosquitto_username_pw_set(m_mosq, username, password); } int mosquittopp::publish(int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain) { return mosquitto_publish(m_mosq, mid, topic, payloadlen, payload, qos, retain); } void mosquittopp::reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff) { mosquitto_reconnect_delay_set(m_mosq, reconnect_delay, reconnect_delay_max, reconnect_exponential_backoff); } int mosquittopp::max_inflight_messages_set(unsigned int max_inflight_messages) { return mosquitto_max_inflight_messages_set(m_mosq, max_inflight_messages); } void mosquittopp::message_retry_set(unsigned int message_retry) { mosquitto_message_retry_set(m_mosq, message_retry); } int mosquittopp::subscribe(int *mid, const char *sub, int qos) { return mosquitto_subscribe(m_mosq, mid, sub, qos); } int mosquittopp::unsubscribe(int *mid, const char *sub) { return mosquitto_unsubscribe(m_mosq, mid, sub); } int mosquittopp::loop(int timeout, int max_packets) { return mosquitto_loop(m_mosq, timeout, max_packets); } int mosquittopp::loop_misc() { return mosquitto_loop_misc(m_mosq); } int mosquittopp::loop_read(int max_packets) { return mosquitto_loop_read(m_mosq, max_packets); } int mosquittopp::loop_write(int max_packets) { return mosquitto_loop_write(m_mosq, max_packets); } int mosquittopp::loop_forever(int timeout, int max_packets) { return mosquitto_loop_forever(m_mosq, timeout, max_packets); } int mosquittopp::loop_start() { return mosquitto_loop_start(m_mosq); } int mosquittopp::loop_stop(bool force) { return mosquitto_loop_stop(m_mosq, force); } bool mosquittopp::want_write() { return mosquitto_want_write(m_mosq); } int mosquittopp::opts_set(enum mosq_opt_t option, void *value) { return mosquitto_opts_set(m_mosq, option, value); } int mosquittopp::threaded_set(bool threaded) { return mosquitto_threaded_set(m_mosq, threaded); } void mosquittopp::user_data_set(void *userdata) { mosquitto_user_data_set(m_mosq, userdata); } int mosquittopp::socks5_set(const char *host, int port, const char *username, const char *password) { return mosquitto_socks5_set(m_mosq, host, port, username, password); } int mosquittopp::tls_set(const char *cafile, const char *capath, const char *certfile, const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)) { return mosquitto_tls_set(m_mosq, cafile, capath, certfile, keyfile, pw_callback); } int mosquittopp::tls_opts_set(int cert_reqs, const char *tls_version, const char *ciphers) { return mosquitto_tls_opts_set(m_mosq, cert_reqs, tls_version, ciphers); } int mosquittopp::tls_insecure_set(bool value) { return mosquitto_tls_insecure_set(m_mosq, value); } int mosquittopp::tls_psk_set(const char *psk, const char *identity, const char *ciphers) { return mosquitto_tls_psk_set(m_mosq, psk, identity, ciphers); } } mosquitto-1.6.9/lib/cpp/mosquittopp.h0000664000175000017500000001354413626052637016741 0ustar rogerroger/* Copyright (c) 2010-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTOPP_H #define MOSQUITTOPP_H #if defined(_WIN32) && !defined(LIBMOSQUITTO_STATIC) # ifdef mosquittopp_EXPORTS # define mosqpp_EXPORT __declspec(dllexport) # else # define mosqpp_EXPORT __declspec(dllimport) # endif #else # define mosqpp_EXPORT #endif #if defined(__GNUC__) || defined(__clang__) # define DEPRECATED __attribute__ ((deprecated)) #else # define DEPRECATED #endif #include #include #include namespace mosqpp { mosqpp_EXPORT const char * DEPRECATED strerror(int mosq_errno); mosqpp_EXPORT const char * DEPRECATED connack_string(int connack_code); mosqpp_EXPORT int DEPRECATED sub_topic_tokenise(const char *subtopic, char ***topics, int *count); mosqpp_EXPORT int DEPRECATED sub_topic_tokens_free(char ***topics, int count); mosqpp_EXPORT int DEPRECATED lib_version(int *major, int *minor, int *revision); mosqpp_EXPORT int DEPRECATED lib_init(); mosqpp_EXPORT int DEPRECATED lib_cleanup(); mosqpp_EXPORT int DEPRECATED topic_matches_sub(const char *sub, const char *topic, bool *result); mosqpp_EXPORT int DEPRECATED validate_utf8(const char *str, int len); mosqpp_EXPORT int DEPRECATED subscribe_simple( struct mosquitto_message **messages, int msg_count, bool retained, const char *topic, int qos=0, const char *host="localhost", int port=1883, const char *client_id=NULL, int keepalive=60, bool clean_session=true, const char *username=NULL, const char *password=NULL, const struct libmosquitto_will *will=NULL, const struct libmosquitto_tls *tls=NULL); mosqpp_EXPORT int DEPRECATED subscribe_callback( int (*callback)(struct mosquitto *, void *, const struct mosquitto_message *), void *userdata, const char *topic, int qos=0, bool retained=true, const char *host="localhost", int port=1883, const char *client_id=NULL, int keepalive=60, bool clean_session=true, const char *username=NULL, const char *password=NULL, const struct libmosquitto_will *will=NULL, const struct libmosquitto_tls *tls=NULL); /* * Class: mosquittopp * * A mosquitto client class. This is a C++ wrapper class for the mosquitto C * library. Please see mosquitto.h for details of the functions. */ class mosqpp_EXPORT DEPRECATED mosquittopp { private: struct mosquitto *m_mosq; public: DEPRECATED mosquittopp(const char *id=NULL, bool clean_session=true); virtual ~mosquittopp(); int DEPRECATED reinitialise(const char *id, bool clean_session); int DEPRECATED socket(); int DEPRECATED will_set(const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false); int DEPRECATED will_clear(); int DEPRECATED username_pw_set(const char *username, const char *password=NULL); int DEPRECATED connect(const char *host, int port=1883, int keepalive=60); int DEPRECATED connect_async(const char *host, int port=1883, int keepalive=60); int DEPRECATED connect(const char *host, int port, int keepalive, const char *bind_address); int DEPRECATED connect_async(const char *host, int port, int keepalive, const char *bind_address); int DEPRECATED reconnect(); int DEPRECATED reconnect_async(); int DEPRECATED disconnect(); int DEPRECATED publish(int *mid, const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false); int DEPRECATED subscribe(int *mid, const char *sub, int qos=0); int DEPRECATED unsubscribe(int *mid, const char *sub); void DEPRECATED reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff); int DEPRECATED max_inflight_messages_set(unsigned int max_inflight_messages); void DEPRECATED message_retry_set(unsigned int message_retry); void DEPRECATED user_data_set(void *userdata); int DEPRECATED tls_set(const char *cafile, const char *capath=NULL, const char *certfile=NULL, const char *keyfile=NULL, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)=NULL); int DEPRECATED tls_opts_set(int cert_reqs, const char *tls_version=NULL, const char *ciphers=NULL); int DEPRECATED tls_insecure_set(bool value); int DEPRECATED tls_psk_set(const char *psk, const char *identity, const char *ciphers=NULL); int DEPRECATED opts_set(enum mosq_opt_t option, void *value); int DEPRECATED loop(int timeout=-1, int max_packets=1); int DEPRECATED loop_misc(); int DEPRECATED loop_read(int max_packets=1); int DEPRECATED loop_write(int max_packets=1); int DEPRECATED loop_forever(int timeout=-1, int max_packets=1); int DEPRECATED loop_start(); int DEPRECATED loop_stop(bool force=false); bool DEPRECATED want_write(); int DEPRECATED threaded_set(bool threaded=true); int DEPRECATED socks5_set(const char *host, int port=1080, const char *username=NULL, const char *password=NULL); // names in the functions commented to prevent unused parameter warning virtual void on_connect(int /*rc*/) {return;} virtual void on_connect_with_flags(int /*rc*/, int /*flags*/) {return;} virtual void on_disconnect(int /*rc*/) {return;} virtual void on_publish(int /*mid*/) {return;} virtual void on_message(const struct mosquitto_message * /*message*/) {return;} virtual void on_subscribe(int /*mid*/, int /*qos_count*/, const int * /*granted_qos*/) {return;} virtual void on_unsubscribe(int /*mid*/) {return;} virtual void on_log(int /*level*/, const char * /*str*/) {return;} virtual void on_error() {return;} }; } #endif mosquitto-1.6.9/lib/cpp/Makefile0000664000175000017500000000324613626052637015622 0ustar rogerrogerinclude ../../config.mk ifneq ($(UNAME),SunOS) LIB_LDFLAGS:=$(LDFLAGS) -Wl,-soname,libmosquittopp.so.${SOVERSION} endif .PHONY : clean install ALL_DEPS=libmosquittopp.so.${SOVERSION} ifeq ($(WITH_STATIC_LIBRARIES),yes) ALL_DEPS+=libmosquittopp.a endif all : ${ALL_DEPS} install : all $(INSTALL) -d "${DESTDIR}${libdir}/" $(INSTALL) ${STRIP_OPTS} libmosquittopp.so.${SOVERSION} "${DESTDIR}${libdir}/libmosquittopp.so.${SOVERSION}" ln -sf libmosquittopp.so.${SOVERSION} "${DESTDIR}${libdir}/libmosquittopp.so" ifeq ($(WITH_STATIC_LIBRARIES),yes) $(INSTALL) libmosquittopp.a "${DESTDIR}${libdir}/libmosquittopp.a" ${CROSS_COMPILE}${STRIP} -g --strip-unneeded "${DESTDIR}${libdir}/libmosquittopp.a" endif $(INSTALL) -d "${DESTDIR}${incdir}/" $(INSTALL) mosquittopp.h "${DESTDIR}${incdir}/mosquittopp.h" $(INSTALL) -d "${DESTDIR}${libdir}/pkgconfig/" $(INSTALL) -m644 ../../libmosquittopp.pc.in "${DESTDIR}${libdir}/pkgconfig/libmosquittopp.pc" sed -i -e "s#@CMAKE_INSTALL_PREFIX@#${prefix}#" -e "s#@VERSION@#${VERSION}#" "${DESTDIR}${libdir}/pkgconfig/libmosquittopp.pc" uninstall : -rm -f "${DESTDIR}${libdir}/libmosquittopp.so.${SOVERSION}" -rm -f "${DESTDIR}${libdir}/libmosquittopp.so" -rm -f "${DESTDIR}${libdir}/libmosquittopp.a" -rm -f "${DESTDIR}${incdir}/mosquittopp.h" clean : -rm -f *.o libmosquittopp.so.${SOVERSION} libmosquittopp.a libmosquittopp.so.${SOVERSION} : mosquittopp.o ${CROSS_COMPILE}$(CXX) -shared $(LIB_LDFLAGS) $< -o $@ ../libmosquitto.so.${SOVERSION} $(LIB_LIDADD) libmosquittopp.a : mosquittopp.o ${CROSS_COMPILE}$(AR) cr $@ $^ mosquittopp.o : mosquittopp.cpp mosquittopp.h ${CROSS_COMPILE}$(CXX) $(LIB_CPPFLAGS) $(LIB_CXXFLAGS) -c $< -o $@ mosquitto-1.6.9/lib/net_mosq.h0000664000175000017500000000522313626052637015373 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef NET_MOSQ_H #define NET_MOSQ_H #ifndef WIN32 # include #else # include # ifndef _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # define _SSIZE_T_DEFINED # endif #endif #include "mosquitto_internal.h" #include "mosquitto.h" #ifdef WITH_BROKER struct mosquitto_db; #endif #ifdef WIN32 # define COMPAT_CLOSE(a) closesocket(a) # define COMPAT_ECONNRESET WSAECONNRESET # define COMPAT_EWOULDBLOCK WSAEWOULDBLOCK #else # define COMPAT_CLOSE(a) close(a) # define COMPAT_ECONNRESET ECONNRESET # define COMPAT_EWOULDBLOCK EWOULDBLOCK #endif /* For when not using winsock libraries. */ #ifndef INVALID_SOCKET #define INVALID_SOCKET -1 #endif /* Macros for accessing the MSB and LSB of a uint16_t */ #define MOSQ_MSB(A) (uint8_t)((A & 0xFF00) >> 8) #define MOSQ_LSB(A) (uint8_t)(A & 0x00FF) int net__init(void); void net__cleanup(void); int net__socket_connect(struct mosquitto *mosq, const char *host, uint16_t port, const char *bind_address, bool blocking); #ifdef WITH_BROKER int net__socket_close(struct mosquitto_db *db, struct mosquitto *mosq); #else int net__socket_close(struct mosquitto *mosq); #endif int net__try_connect(const char *host, uint16_t port, mosq_sock_t *sock, const char *bind_address, bool blocking); int net__try_connect_step1(struct mosquitto *mosq, const char *host); int net__try_connect_step2(struct mosquitto *mosq, uint16_t port, mosq_sock_t *sock); int net__socket_connect_step3(struct mosquitto *mosq, const char *host); int net__socket_nonblock(mosq_sock_t *sock); int net__socketpair(mosq_sock_t *sp1, mosq_sock_t *sp2); ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count); ssize_t net__write(struct mosquitto *mosq, void *buf, size_t count); #ifdef WITH_TLS void net__print_ssl_error(struct mosquitto *mosq); int net__socket_apply_tls(struct mosquitto *mosq); int net__socket_connect_tls(struct mosquitto *mosq); int mosquitto__verify_ocsp_status_cb(SSL * ssl, void *arg); UI_METHOD *net__get_ui_method(void); #define ENGINE_FINISH(e) if(e) ENGINE_finish(e) #define ENGINE_SECRET_MODE "SECRET_MODE" #define ENGINE_SECRET_MODE_SHA 0x1000 #define ENGINE_PIN "PIN" #endif #endif mosquitto-1.6.9/lib/tls_mosq.h0000664000175000017500000000171113626052637015405 0ustar rogerroger/* Copyright (c) 2013-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef TLS_MOSQ_H #define TLS_MOSQ_H #ifdef WITH_TLS # define SSL_DATA_PENDING(A) ((A)->ssl && SSL_pending((A)->ssl)) #else # define SSL_DATA_PENDING(A) 0 #endif #ifdef WITH_TLS #include #include int mosquitto__server_certificate_verify(int preverify_ok, X509_STORE_CTX *ctx); int mosquitto__verify_certificate_hostname(X509 *cert, const char *hostname); #endif /* WITH_TLS */ #endif mosquitto-1.6.9/lib/property_mosq.h0000664000175000017500000000252213626052637016470 0ustar rogerroger/* Copyright (c) 2018-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef PROPERTY_MOSQ_H #define PROPERTY_MOSQ_H #include "mosquitto_internal.h" #include "mosquitto.h" struct mqtt__string { char *v; int len; }; struct mqtt5__property { struct mqtt5__property *next; union { uint8_t i8; uint16_t i16; uint32_t i32; uint32_t varint; struct mqtt__string bin; struct mqtt__string s; } value; struct mqtt__string name; int32_t identifier; bool client_generated; }; int property__read_all(int command, struct mosquitto__packet *packet, mosquitto_property **property); int property__write_all(struct mosquitto__packet *packet, const mosquitto_property *property, bool write_len); void property__free(mosquitto_property **property); int property__get_length(const mosquitto_property *property); int property__get_length_all(const mosquitto_property *property); #endif mosquitto-1.6.9/lib/read_handle.c0000664000175000017500000000354313626052637015772 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "time_mosq.h" #include "util_mosq.h" int handle__packet(struct mosquitto *mosq) { assert(mosq); switch((mosq->in_packet.command)&0xF0){ case CMD_PINGREQ: return handle__pingreq(mosq); case CMD_PINGRESP: return handle__pingresp(mosq); case CMD_PUBACK: return handle__pubackcomp(mosq, "PUBACK"); case CMD_PUBCOMP: return handle__pubackcomp(mosq, "PUBCOMP"); case CMD_PUBLISH: return handle__publish(mosq); case CMD_PUBREC: return handle__pubrec(NULL, mosq); case CMD_PUBREL: return handle__pubrel(NULL, mosq); case CMD_CONNACK: return handle__connack(mosq); case CMD_SUBACK: return handle__suback(mosq); case CMD_UNSUBACK: return handle__unsuback(mosq); case CMD_DISCONNECT: return handle__disconnect(mosq); case CMD_AUTH: return handle__auth(mosq); default: /* If we don't recognise the command, return an error straight away. */ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unrecognised command %d\n", (mosq->in_packet.command)&0xF0); return MOSQ_ERR_PROTOCOL; } } mosquitto-1.6.9/lib/callbacks.c0000664000175000017500000001047413626052637015464 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto.h" #include "mosquitto_internal.h" void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_connect = on_connect; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_connect_with_flags_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int, int)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_connect_with_flags = on_connect; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_connect_v5_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int, int, const mosquitto_property *)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_connect_v5 = on_connect; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_disconnect_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_disconnect = on_disconnect; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_disconnect_v5_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int, const mosquitto_property *)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_disconnect_v5 = on_disconnect; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_publish_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_publish = on_publish; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_publish_v5_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int, int, const mosquitto_property *props)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_publish_v5 = on_publish; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_message_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_message = on_message; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_message_v5_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *, const mosquitto_property *props)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_message_v5 = on_message; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_subscribe_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_subscribe = on_subscribe; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_subscribe_v5_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *, const mosquitto_property *props)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_subscribe_v5 = on_subscribe; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_unsubscribe = on_unsubscribe; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_unsubscribe_v5_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int, const mosquitto_property *props)) { pthread_mutex_lock(&mosq->callback_mutex); mosq->on_unsubscribe_v5 = on_unsubscribe; pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on_log)(struct mosquitto *, void *, int, const char *)) { pthread_mutex_lock(&mosq->log_callback_mutex); mosq->on_log = on_log; pthread_mutex_unlock(&mosq->log_callback_mutex); } mosquitto-1.6.9/lib/send_disconnect.c0000664000175000017500000000422213626052637016701 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" int send__disconnect(struct mosquitto *mosq, uint8_t reason_code, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; int rc; int proplen, varbytes; assert(mosq); #ifdef WITH_BROKER # ifdef WITH_BRIDGE if(mosq->bridge){ log__printf(mosq, MOSQ_LOG_DEBUG, "Bridge %s sending DISCONNECT", mosq->id); }else # else { log__printf(mosq, MOSQ_LOG_DEBUG, "Sending DISCONNECT to %s (rc%d)", mosq->id, reason_code); } # endif #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending DISCONNECT", mosq->id); #endif assert(mosq); packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = CMD_DISCONNECT; if(mosq->protocol == mosq_p_mqtt5 && (reason_code != 0 || properties)){ packet->remaining_length = 1; if(properties){ proplen = property__get_length_all(properties); varbytes = packet__varint_bytes(proplen); packet->remaining_length += proplen + varbytes; } }else{ packet->remaining_length = 0; } rc = packet__alloc(packet); if(rc){ mosquitto__free(packet); return rc; } if(mosq->protocol == mosq_p_mqtt5 && (reason_code != 0 || properties)){ packet__write_byte(packet, reason_code); if(properties){ property__write_all(packet, properties, true); } } return packet__queue(mosq, packet); } mosquitto-1.6.9/lib/loop.c0000664000175000017500000002212313626052637014510 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #ifndef WIN32 #include #include #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "net_mosq.h" #include "packet_mosq.h" #include "socks_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #if !defined(WIN32) && !defined(__SYMBIAN32__) #define HAVE_PSELECT #endif int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_packets) { #ifdef HAVE_PSELECT struct timespec local_timeout; #else struct timeval local_timeout; #endif fd_set readfds, writefds; int fdcount; int rc; char pairbuf; int maxfd = 0; time_t now; #ifdef WITH_SRV int state; #endif if(!mosq || max_packets < 1) return MOSQ_ERR_INVAL; #ifndef WIN32 if(mosq->sock >= FD_SETSIZE || mosq->sockpairR >= FD_SETSIZE){ return MOSQ_ERR_INVAL; } #endif FD_ZERO(&readfds); FD_ZERO(&writefds); if(mosq->sock != INVALID_SOCKET){ maxfd = mosq->sock; FD_SET(mosq->sock, &readfds); pthread_mutex_lock(&mosq->current_out_packet_mutex); pthread_mutex_lock(&mosq->out_packet_mutex); if(mosq->out_packet || mosq->current_out_packet){ FD_SET(mosq->sock, &writefds); } #ifdef WITH_TLS if(mosq->ssl){ if(mosq->want_write){ FD_SET(mosq->sock, &writefds); }else if(mosq->want_connect){ /* Remove possible FD_SET from above, we don't want to check * for writing if we are still connecting, unless want_write is * definitely set. The presence of outgoing packets does not * matter yet. */ FD_CLR(mosq->sock, &writefds); } } #endif pthread_mutex_unlock(&mosq->out_packet_mutex); pthread_mutex_unlock(&mosq->current_out_packet_mutex); }else{ #ifdef WITH_SRV if(mosq->achan){ state = mosquitto__get_state(mosq); if(state == mosq_cs_connect_srv){ rc = ares_fds(mosq->achan, &readfds, &writefds); if(rc > maxfd){ maxfd = rc; } }else{ return MOSQ_ERR_NO_CONN; } } #else return MOSQ_ERR_NO_CONN; #endif } if(mosq->sockpairR != INVALID_SOCKET){ /* sockpairR is used to break out of select() before the timeout, on a * call to publish() etc. */ FD_SET(mosq->sockpairR, &readfds); if(mosq->sockpairR > maxfd){ maxfd = mosq->sockpairR; } } if(timeout < 0){ timeout = 1000; } now = mosquitto_time(); if(mosq->next_msg_out && now + timeout/1000 > mosq->next_msg_out){ timeout = (mosq->next_msg_out - now)*1000; } if(timeout < 0){ /* There has been a delay somewhere which means we should have already * sent a message. */ timeout = 0; } local_timeout.tv_sec = timeout/1000; #ifdef HAVE_PSELECT local_timeout.tv_nsec = (timeout-local_timeout.tv_sec*1000)*1e6; #else local_timeout.tv_usec = (timeout-local_timeout.tv_sec*1000)*1000; #endif #ifdef HAVE_PSELECT fdcount = pselect(maxfd+1, &readfds, &writefds, NULL, &local_timeout, NULL); #else fdcount = select(maxfd+1, &readfds, &writefds, NULL, &local_timeout); #endif if(fdcount == -1){ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EINTR){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ERRNO; } }else{ if(mosq->sock != INVALID_SOCKET){ if(FD_ISSET(mosq->sock, &readfds)){ rc = mosquitto_loop_read(mosq, max_packets); if(rc || mosq->sock == INVALID_SOCKET){ return rc; } } if(mosq->sockpairR != INVALID_SOCKET && FD_ISSET(mosq->sockpairR, &readfds)){ #ifndef WIN32 if(read(mosq->sockpairR, &pairbuf, 1) == 0){ } #else recv(mosq->sockpairR, &pairbuf, 1, 0); #endif /* Fake write possible, to stimulate output write even though * we didn't ask for it, because at that point the publish or * other command wasn't present. */ if(mosq->sock != INVALID_SOCKET) FD_SET(mosq->sock, &writefds); } if(mosq->sock != INVALID_SOCKET && FD_ISSET(mosq->sock, &writefds)){ #ifdef WITH_TLS if(mosq->want_connect){ rc = net__socket_connect_tls(mosq); if(rc) return rc; }else #endif { rc = mosquitto_loop_write(mosq, max_packets); if(rc || mosq->sock == INVALID_SOCKET){ return rc; } } } } #ifdef WITH_SRV if(mosq->achan){ ares_process(mosq->achan, &readfds, &writefds); } #endif } return mosquitto_loop_misc(mosq); } int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) { int run = 1; int rc; unsigned long reconnect_delay; #ifndef WIN32 struct timespec req, rem; #endif int state; if(!mosq) return MOSQ_ERR_INVAL; mosq->reconnects = 0; while(run){ do{ rc = mosquitto_loop(mosq, timeout, max_packets); }while(run && rc == MOSQ_ERR_SUCCESS); /* Quit after fatal errors. */ switch(rc){ case MOSQ_ERR_NOMEM: case MOSQ_ERR_PROTOCOL: case MOSQ_ERR_INVAL: case MOSQ_ERR_NOT_FOUND: case MOSQ_ERR_TLS: case MOSQ_ERR_PAYLOAD_SIZE: case MOSQ_ERR_NOT_SUPPORTED: case MOSQ_ERR_AUTH: case MOSQ_ERR_ACL_DENIED: case MOSQ_ERR_UNKNOWN: case MOSQ_ERR_EAI: case MOSQ_ERR_PROXY: return rc; case MOSQ_ERR_ERRNO: break; } if(errno == EPROTO){ return rc; } do{ rc = MOSQ_ERR_SUCCESS; state = mosquitto__get_state(mosq); if(state == mosq_cs_disconnecting || state == mosq_cs_disconnected){ run = 0; }else{ if(mosq->reconnect_delay_max > mosq->reconnect_delay){ if(mosq->reconnect_exponential_backoff){ reconnect_delay = mosq->reconnect_delay*(mosq->reconnects+1)*(mosq->reconnects+1); }else{ reconnect_delay = mosq->reconnect_delay*(mosq->reconnects+1); } }else{ reconnect_delay = mosq->reconnect_delay; } if(reconnect_delay > mosq->reconnect_delay_max){ reconnect_delay = mosq->reconnect_delay_max; }else{ mosq->reconnects++; } #ifdef WIN32 Sleep(reconnect_delay*1000); #else req.tv_sec = reconnect_delay; req.tv_nsec = 0; while(nanosleep(&req, &rem) == -1 && errno == EINTR){ req = rem; } #endif state = mosquitto__get_state(mosq); if(state == mosq_cs_disconnecting || state == mosq_cs_disconnected){ run = 0; }else{ rc = mosquitto_reconnect(mosq); } } }while(run && rc != MOSQ_ERR_SUCCESS); } return rc; } int mosquitto_loop_misc(struct mosquitto *mosq) { if(!mosq) return MOSQ_ERR_INVAL; if(mosq->sock == INVALID_SOCKET) return MOSQ_ERR_NO_CONN; return mosquitto__check_keepalive(mosq); } static int mosquitto__loop_rc_handle(struct mosquitto *mosq, int rc) { int state; if(rc){ net__socket_close(mosq); state = mosquitto__get_state(mosq); if(state == mosq_cs_disconnecting || state == mosq_cs_disconnected){ rc = MOSQ_ERR_SUCCESS; } pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_disconnect){ mosq->in_callback = true; mosq->on_disconnect(mosq, mosq->userdata, rc); mosq->in_callback = false; } if(mosq->on_disconnect_v5){ mosq->in_callback = true; mosq->on_disconnect_v5(mosq, mosq->userdata, rc, NULL); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); } return rc; } int mosquitto_loop_read(struct mosquitto *mosq, int max_packets) { int rc; int i; if(max_packets < 1) return MOSQ_ERR_INVAL; #ifdef WITH_TLS if(mosq->want_connect){ return net__socket_connect_tls(mosq); } #endif pthread_mutex_lock(&mosq->msgs_out.mutex); max_packets = mosq->msgs_out.queue_len; pthread_mutex_unlock(&mosq->msgs_out.mutex); pthread_mutex_lock(&mosq->msgs_in.mutex); max_packets += mosq->msgs_in.queue_len; pthread_mutex_unlock(&mosq->msgs_in.mutex); if(max_packets < 1) max_packets = 1; /* Queue len here tells us how many messages are awaiting processing and * have QoS > 0. We should try to deal with that many in this loop in order * to keep up. */ for(i=0; isocks5_host){ rc = socks5__read(mosq); }else #endif { rc = packet__read(mosq); } if(rc || errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ return mosquitto__loop_rc_handle(mosq, rc); } } return rc; } int mosquitto_loop_write(struct mosquitto *mosq, int max_packets) { int rc; int i; if(max_packets < 1) return MOSQ_ERR_INVAL; pthread_mutex_lock(&mosq->msgs_out.mutex); max_packets = mosq->msgs_out.queue_len; pthread_mutex_unlock(&mosq->msgs_out.mutex); pthread_mutex_lock(&mosq->msgs_in.mutex); max_packets += mosq->msgs_in.queue_len; pthread_mutex_unlock(&mosq->msgs_in.mutex); if(max_packets < 1) max_packets = 1; /* Queue len here tells us how many messages are awaiting processing and * have QoS > 0. We should try to deal with that many in this loop in order * to keep up. */ for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef ALIAS_MOSQ_H #define ALIAS_MOSQ_H #include "mosquitto_internal.h" int alias__add(struct mosquitto *mosq, const char *topic, int alias); int alias__find(struct mosquitto *mosq, char **topic, int alias); void alias__free_all(struct mosquitto *mosq); #endif mosquitto-1.6.9/lib/mosquitto.c0000664000175000017500000003661213626052637015613 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifndef WIN32 #include #include #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "will_mosq.h" void mosquitto__destroy(struct mosquitto *mosq); int mosquitto_lib_version(int *major, int *minor, int *revision) { if(major) *major = LIBMOSQUITTO_MAJOR; if(minor) *minor = LIBMOSQUITTO_MINOR; if(revision) *revision = LIBMOSQUITTO_REVISION; return LIBMOSQUITTO_VERSION_NUMBER; } int mosquitto_lib_init(void) { #ifdef WIN32 srand(GetTickCount64()); #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); srand(tp.tv_nsec); #elif defined(__APPLE__) uint64_t ticks; ticks = mach_absolute_time(); srand((unsigned int)ticks); #else struct timeval tv; gettimeofday(&tv, NULL); srand(tv.tv_sec*1000 + tv.tv_usec/1000); #endif return net__init(); } int mosquitto_lib_cleanup(void) { net__cleanup(); return MOSQ_ERR_SUCCESS; } struct mosquitto *mosquitto_new(const char *id, bool clean_start, void *userdata) { struct mosquitto *mosq = NULL; int rc; if(clean_start == false && id == NULL){ errno = EINVAL; return NULL; } #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif mosq = (struct mosquitto *)mosquitto__calloc(1, sizeof(struct mosquitto)); if(mosq){ mosq->sock = INVALID_SOCKET; mosq->sockpairR = INVALID_SOCKET; mosq->sockpairW = INVALID_SOCKET; #ifdef WITH_THREADING mosq->thread_id = pthread_self(); #endif rc = mosquitto_reinitialise(mosq, id, clean_start, userdata); if(rc){ mosquitto_destroy(mosq); if(rc == MOSQ_ERR_INVAL){ errno = EINVAL; }else if(rc == MOSQ_ERR_NOMEM){ errno = ENOMEM; } return NULL; } }else{ errno = ENOMEM; } return mosq; } int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_start, void *userdata) { if(!mosq) return MOSQ_ERR_INVAL; if(clean_start == false && id == NULL){ return MOSQ_ERR_INVAL; } mosquitto__destroy(mosq); memset(mosq, 0, sizeof(struct mosquitto)); if(userdata){ mosq->userdata = userdata; }else{ mosq->userdata = mosq; } mosq->protocol = mosq_p_mqtt311; mosq->sock = INVALID_SOCKET; mosq->sockpairR = INVALID_SOCKET; mosq->sockpairW = INVALID_SOCKET; mosq->keepalive = 60; mosq->clean_start = clean_start; if(id){ if(STREMPTY(id)){ return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(id, strlen(id))){ return MOSQ_ERR_MALFORMED_UTF8; } mosq->id = mosquitto__strdup(id); } mosq->in_packet.payload = NULL; packet__cleanup(&mosq->in_packet); mosq->out_packet = NULL; mosq->current_out_packet = NULL; mosq->last_msg_in = mosquitto_time(); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; mosq->ping_t = 0; mosq->last_mid = 0; mosq->state = mosq_cs_new; mosq->maximum_qos = 2; mosq->msgs_in.inflight_maximum = 20; mosq->msgs_out.inflight_maximum = 20; mosq->msgs_in.inflight_quota = 20; mosq->msgs_out.inflight_quota = 20; mosq->will = NULL; mosq->on_connect = NULL; mosq->on_publish = NULL; mosq->on_message = NULL; mosq->on_subscribe = NULL; mosq->on_unsubscribe = NULL; mosq->host = NULL; mosq->port = 1883; mosq->in_callback = false; mosq->reconnect_delay = 1; mosq->reconnect_delay_max = 1; mosq->reconnect_exponential_backoff = false; mosq->threaded = mosq_ts_none; #ifdef WITH_TLS mosq->ssl = NULL; mosq->ssl_ctx = NULL; mosq->tls_cert_reqs = SSL_VERIFY_PEER; mosq->tls_insecure = false; mosq->want_write = false; mosq->tls_ocsp_required = false; #endif #ifdef WITH_THREADING pthread_mutex_init(&mosq->callback_mutex, NULL); pthread_mutex_init(&mosq->log_callback_mutex, NULL); pthread_mutex_init(&mosq->state_mutex, NULL); pthread_mutex_init(&mosq->out_packet_mutex, NULL); pthread_mutex_init(&mosq->current_out_packet_mutex, NULL); pthread_mutex_init(&mosq->msgtime_mutex, NULL); pthread_mutex_init(&mosq->msgs_in.mutex, NULL); pthread_mutex_init(&mosq->msgs_out.mutex, NULL); pthread_mutex_init(&mosq->mid_mutex, NULL); mosq->thread_id = pthread_self(); #endif return MOSQ_ERR_SUCCESS; } void mosquitto__destroy(struct mosquitto *mosq) { struct mosquitto__packet *packet; if(!mosq) return; #ifdef WITH_THREADING # ifdef HAVE_PTHREAD_CANCEL if(mosq->threaded == mosq_ts_self && !pthread_equal(mosq->thread_id, pthread_self())){ pthread_cancel(mosq->thread_id); pthread_join(mosq->thread_id, NULL); mosq->threaded = mosq_ts_none; } # endif if(mosq->id){ /* If mosq->id is not NULL then the client has already been initialised * and so the mutexes need destroying. If mosq->id is NULL, the mutexes * haven't been initialised. */ pthread_mutex_destroy(&mosq->callback_mutex); pthread_mutex_destroy(&mosq->log_callback_mutex); pthread_mutex_destroy(&mosq->state_mutex); pthread_mutex_destroy(&mosq->out_packet_mutex); pthread_mutex_destroy(&mosq->current_out_packet_mutex); pthread_mutex_destroy(&mosq->msgtime_mutex); pthread_mutex_destroy(&mosq->msgs_in.mutex); pthread_mutex_destroy(&mosq->msgs_out.mutex); pthread_mutex_destroy(&mosq->mid_mutex); } #endif if(mosq->sock != INVALID_SOCKET){ net__socket_close(mosq); } message__cleanup_all(mosq); will__clear(mosq); #ifdef WITH_TLS if(mosq->ssl){ SSL_free(mosq->ssl); } if(mosq->ssl_ctx){ SSL_CTX_free(mosq->ssl_ctx); } mosquitto__free(mosq->tls_cafile); mosquitto__free(mosq->tls_capath); mosquitto__free(mosq->tls_certfile); mosquitto__free(mosq->tls_keyfile); if(mosq->tls_pw_callback) mosq->tls_pw_callback = NULL; mosquitto__free(mosq->tls_version); mosquitto__free(mosq->tls_ciphers); mosquitto__free(mosq->tls_psk); mosquitto__free(mosq->tls_psk_identity); mosquitto__free(mosq->tls_alpn); #endif mosquitto__free(mosq->address); mosq->address = NULL; mosquitto__free(mosq->id); mosq->id = NULL; mosquitto__free(mosq->username); mosq->username = NULL; mosquitto__free(mosq->password); mosq->password = NULL; mosquitto__free(mosq->host); mosq->host = NULL; mosquitto__free(mosq->bind_address); mosq->bind_address = NULL; /* Out packet cleanup */ if(mosq->out_packet && !mosq->current_out_packet){ mosq->current_out_packet = mosq->out_packet; mosq->out_packet = mosq->out_packet->next; } while(mosq->current_out_packet){ packet = mosq->current_out_packet; /* Free data and reset values */ mosq->current_out_packet = mosq->out_packet; if(mosq->out_packet){ mosq->out_packet = mosq->out_packet->next; } packet__cleanup(packet); mosquitto__free(packet); } packet__cleanup(&mosq->in_packet); if(mosq->sockpairR != INVALID_SOCKET){ COMPAT_CLOSE(mosq->sockpairR); mosq->sockpairR = INVALID_SOCKET; } if(mosq->sockpairW != INVALID_SOCKET){ COMPAT_CLOSE(mosq->sockpairW); mosq->sockpairW = INVALID_SOCKET; } } void mosquitto_destroy(struct mosquitto *mosq) { if(!mosq) return; mosquitto__destroy(mosq); mosquitto__free(mosq); } int mosquitto_socket(struct mosquitto *mosq) { if(!mosq) return INVALID_SOCKET; return mosq->sock; } bool mosquitto_want_write(struct mosquitto *mosq) { bool result = false; if(mosq->out_packet || mosq->current_out_packet){ result = true; } #ifdef WITH_TLS if(mosq->ssl){ if (mosq->want_write) { result = true; }else if(mosq->want_connect){ result = false; } } #endif return result; } const char *mosquitto_strerror(int mosq_errno) { switch(mosq_errno){ case MOSQ_ERR_AUTH_CONTINUE: return "Continue with authentication."; case MOSQ_ERR_NO_SUBSCRIBERS: return "No subscribers."; case MOSQ_ERR_SUB_EXISTS: return "Subscription already exists."; case MOSQ_ERR_CONN_PENDING: return "Connection pending."; case MOSQ_ERR_SUCCESS: return "No error."; case MOSQ_ERR_NOMEM: return "Out of memory."; case MOSQ_ERR_PROTOCOL: return "A network protocol error occurred when communicating with the broker."; case MOSQ_ERR_INVAL: return "Invalid function arguments provided."; case MOSQ_ERR_NO_CONN: return "The client is not currently connected."; case MOSQ_ERR_CONN_REFUSED: return "The connection was refused."; case MOSQ_ERR_NOT_FOUND: return "Message not found (internal error)."; case MOSQ_ERR_CONN_LOST: return "The connection was lost."; case MOSQ_ERR_TLS: return "A TLS error occurred."; case MOSQ_ERR_PAYLOAD_SIZE: return "Payload too large."; case MOSQ_ERR_NOT_SUPPORTED: return "This feature is not supported."; case MOSQ_ERR_AUTH: return "Authorisation failed."; case MOSQ_ERR_ACL_DENIED: return "Access denied by ACL."; case MOSQ_ERR_UNKNOWN: return "Unknown error."; case MOSQ_ERR_ERRNO: return strerror(errno); case MOSQ_ERR_EAI: return "Lookup error."; case MOSQ_ERR_PROXY: return "Proxy error."; case MOSQ_ERR_MALFORMED_UTF8: return "Malformed UTF-8"; case MOSQ_ERR_DUPLICATE_PROPERTY: return "Duplicate property in property list"; case MOSQ_ERR_TLS_HANDSHAKE: return "TLS handshake failed."; case MOSQ_ERR_QOS_NOT_SUPPORTED: return "Requested QoS not supported on server."; case MOSQ_ERR_OVERSIZE_PACKET: return "Packet larger than supported by the server."; case MOSQ_ERR_OCSP: return "OCSP error."; default: return "Unknown error."; } } const char *mosquitto_connack_string(int connack_code) { switch(connack_code){ case 0: return "Connection Accepted."; case 1: return "Connection Refused: unacceptable protocol version."; case 2: return "Connection Refused: identifier rejected."; case 3: return "Connection Refused: broker unavailable."; case 4: return "Connection Refused: bad user name or password."; case 5: return "Connection Refused: not authorised."; default: return "Connection Refused: unknown reason."; } } const char *mosquitto_reason_string(int reason_code) { switch(reason_code){ case MQTT_RC_SUCCESS: return "Success"; case MQTT_RC_GRANTED_QOS1: return "Granted QoS 1"; case MQTT_RC_GRANTED_QOS2: return "Granted QoS 2"; case MQTT_RC_DISCONNECT_WITH_WILL_MSG: return "Disconnect with Will Message"; case MQTT_RC_NO_MATCHING_SUBSCRIBERS: return "No matching subscribers"; case MQTT_RC_NO_SUBSCRIPTION_EXISTED: return "No subscription existed"; case MQTT_RC_CONTINUE_AUTHENTICATION: return "Continue authentication"; case MQTT_RC_REAUTHENTICATE: return "Re-authenticate"; case MQTT_RC_UNSPECIFIED: return "Unspecified error"; case MQTT_RC_MALFORMED_PACKET: return "Malformed Packet"; case MQTT_RC_PROTOCOL_ERROR: return "Protocol Error"; case MQTT_RC_IMPLEMENTATION_SPECIFIC: return "Implementation specific error"; case MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION: return "Unsupported Protocol Version"; case MQTT_RC_CLIENTID_NOT_VALID: return "Client Identifier not valid"; case MQTT_RC_BAD_USERNAME_OR_PASSWORD: return "Bad User Name or Password"; case MQTT_RC_NOT_AUTHORIZED: return "Not authorized"; case MQTT_RC_SERVER_UNAVAILABLE: return "Server unavailable"; case MQTT_RC_SERVER_BUSY: return "Server busy"; case MQTT_RC_BANNED: return "Banned"; case MQTT_RC_SERVER_SHUTTING_DOWN: return "Server shutting down"; case MQTT_RC_BAD_AUTHENTICATION_METHOD: return "Bad authentication method"; case MQTT_RC_KEEP_ALIVE_TIMEOUT: return "Keep Alive timeout"; case MQTT_RC_SESSION_TAKEN_OVER: return "Session taken over"; case MQTT_RC_TOPIC_FILTER_INVALID: return "Topic Filter invalid"; case MQTT_RC_TOPIC_NAME_INVALID: return "Topic Name invalid"; case MQTT_RC_PACKET_ID_IN_USE: return "Packet Identifier in use"; case MQTT_RC_PACKET_ID_NOT_FOUND: return "Packet Identifier not found"; case MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED: return "Receive Maximum exceeded"; case MQTT_RC_TOPIC_ALIAS_INVALID: return "Topic Alias invalid"; case MQTT_RC_PACKET_TOO_LARGE: return "Packet too large"; case MQTT_RC_MESSAGE_RATE_TOO_HIGH: return "Message rate too high"; case MQTT_RC_QUOTA_EXCEEDED: return "Quota exceeded"; case MQTT_RC_ADMINISTRATIVE_ACTION: return "Administrative action"; case MQTT_RC_PAYLOAD_FORMAT_INVALID: return "Payload format invalid"; case MQTT_RC_RETAIN_NOT_SUPPORTED: return "Retain not supported"; case MQTT_RC_QOS_NOT_SUPPORTED: return "QoS not supported"; case MQTT_RC_USE_ANOTHER_SERVER: return "Use another server"; case MQTT_RC_SERVER_MOVED: return "Server moved"; case MQTT_RC_SHARED_SUBS_NOT_SUPPORTED: return "Shared Subscriptions not supported"; case MQTT_RC_CONNECTION_RATE_EXCEEDED: return "Connection rate exceeded"; case MQTT_RC_MAXIMUM_CONNECT_TIME: return "Maximum connect time"; case MQTT_RC_SUBSCRIPTION_IDS_NOT_SUPPORTED: return "Subscription identifiers not supported"; case MQTT_RC_WILDCARD_SUBS_NOT_SUPPORTED: return "Wildcard Subscriptions not supported"; default: return "Unknown reason"; } } int mosquitto_string_to_command(const char *str, int *cmd) { if(!strcasecmp(str, "connect")){ *cmd = CMD_CONNECT; }else if(!strcasecmp(str, "connack")){ *cmd = CMD_CONNACK; }else if(!strcasecmp(str, "publish")){ *cmd = CMD_PUBLISH; }else if(!strcasecmp(str, "puback")){ *cmd = CMD_PUBACK; }else if(!strcasecmp(str, "pubrec")){ *cmd = CMD_PUBREC; }else if(!strcasecmp(str, "pubrel")){ *cmd = CMD_PUBREL; }else if(!strcasecmp(str, "pubcomp")){ *cmd = CMD_PUBCOMP; }else if(!strcasecmp(str, "subscribe")){ *cmd = CMD_SUBSCRIBE; }else if(!strcasecmp(str, "unsubscribe")){ *cmd = CMD_UNSUBSCRIBE; }else if(!strcasecmp(str, "disconnect")){ *cmd = CMD_DISCONNECT; }else if(!strcasecmp(str, "auth")){ *cmd = CMD_AUTH; }else if(!strcasecmp(str, "will")){ *cmd = CMD_WILL; }else{ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count) { int len; int hier_count = 1; int start, stop; int hier; int tlen; int i, j; if(!subtopic || !topics || !count) return MOSQ_ERR_INVAL; len = strlen(subtopic); for(i=0; i len-1){ /* Separator at end of line */ }else{ hier_count++; } } } (*topics) = mosquitto__calloc(hier_count, sizeof(char *)); if(!(*topics)) return MOSQ_ERR_NOMEM; start = 0; hier = 0; for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # ifdef WITH_WEBSOCKETS # include # endif #else # include "read_handle.h" #endif #include "memory_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "util_mosq.h" #ifdef WITH_BROKER # include "sys_tree.h" # include "send_mosq.h" #else # define G_BYTES_RECEIVED_INC(A) # define G_BYTES_SENT_INC(A) # define G_MSGS_SENT_INC(A) # define G_PUB_MSGS_SENT_INC(A) #endif int packet__alloc(struct mosquitto__packet *packet) { uint8_t remaining_bytes[5], byte; uint32_t remaining_length; int i; assert(packet); remaining_length = packet->remaining_length; packet->payload = NULL; packet->remaining_count = 0; do{ byte = remaining_length % 128; remaining_length = remaining_length / 128; /* If there are more digits to encode, set the top bit of this digit */ if(remaining_length > 0){ byte = byte | 0x80; } remaining_bytes[packet->remaining_count] = byte; packet->remaining_count++; }while(remaining_length > 0 && packet->remaining_count < 5); if(packet->remaining_count == 5) return MOSQ_ERR_PAYLOAD_SIZE; packet->packet_length = packet->remaining_length + 1 + packet->remaining_count; #ifdef WITH_WEBSOCKETS packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length + LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING); #else packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length); #endif if(!packet->payload) return MOSQ_ERR_NOMEM; packet->payload[0] = packet->command; for(i=0; iremaining_count; i++){ packet->payload[i+1] = remaining_bytes[i]; } packet->pos = 1 + packet->remaining_count; return MOSQ_ERR_SUCCESS; } void packet__cleanup(struct mosquitto__packet *packet) { if(!packet) return; /* Free data and reset values */ packet->command = 0; packet->remaining_count = 0; packet->remaining_mult = 1; packet->remaining_length = 0; mosquitto__free(packet->payload); packet->payload = NULL; packet->to_process = 0; packet->pos = 0; } void packet__cleanup_all(struct mosquitto *mosq) { struct mosquitto__packet *packet; pthread_mutex_lock(&mosq->current_out_packet_mutex); pthread_mutex_lock(&mosq->out_packet_mutex); /* Out packet cleanup */ if(mosq->out_packet && !mosq->current_out_packet){ mosq->current_out_packet = mosq->out_packet; mosq->out_packet = mosq->out_packet->next; } while(mosq->current_out_packet){ packet = mosq->current_out_packet; /* Free data and reset values */ mosq->current_out_packet = mosq->out_packet; if(mosq->out_packet){ mosq->out_packet = mosq->out_packet->next; } packet__cleanup(packet); mosquitto__free(packet); } packet__cleanup(&mosq->in_packet); pthread_mutex_unlock(&mosq->out_packet_mutex); pthread_mutex_unlock(&mosq->current_out_packet_mutex); } int packet__queue(struct mosquitto *mosq, struct mosquitto__packet *packet) { #ifndef WITH_BROKER char sockpair_data = 0; #endif assert(mosq); assert(packet); packet->pos = 0; packet->to_process = packet->packet_length; packet->next = NULL; pthread_mutex_lock(&mosq->out_packet_mutex); if(mosq->out_packet){ mosq->out_packet_last->next = packet; }else{ mosq->out_packet = packet; } mosq->out_packet_last = packet; pthread_mutex_unlock(&mosq->out_packet_mutex); #ifdef WITH_BROKER # ifdef WITH_WEBSOCKETS if(mosq->wsi){ libwebsocket_callback_on_writable(mosq->ws_context, mosq->wsi); return MOSQ_ERR_SUCCESS; }else{ return packet__write(mosq); } # else return packet__write(mosq); # endif #else /* Write a single byte to sockpairW (connected to sockpairR) to break out * of select() if in threaded mode. */ if(mosq->sockpairW != INVALID_SOCKET){ #ifndef WIN32 if(write(mosq->sockpairW, &sockpair_data, 1)){ } #else send(mosq->sockpairW, &sockpair_data, 1, 0); #endif } if(mosq->in_callback == false && mosq->threaded == mosq_ts_none){ return packet__write(mosq); }else{ return MOSQ_ERR_SUCCESS; } #endif } int packet__check_oversize(struct mosquitto *mosq, uint32_t remaining_length) { uint32_t len; if(mosq->maximum_packet_size == 0) return MOSQ_ERR_SUCCESS; len = remaining_length + packet__varint_bytes(remaining_length); if(len > mosq->maximum_packet_size){ return MOSQ_ERR_OVERSIZE_PACKET; }else{ return MOSQ_ERR_SUCCESS; } } int packet__write(struct mosquitto *mosq) { ssize_t write_length; struct mosquitto__packet *packet; int state; if(!mosq) return MOSQ_ERR_INVAL; if(mosq->sock == INVALID_SOCKET) return MOSQ_ERR_NO_CONN; pthread_mutex_lock(&mosq->current_out_packet_mutex); pthread_mutex_lock(&mosq->out_packet_mutex); if(mosq->out_packet && !mosq->current_out_packet){ mosq->current_out_packet = mosq->out_packet; mosq->out_packet = mosq->out_packet->next; if(!mosq->out_packet){ mosq->out_packet_last = NULL; } } pthread_mutex_unlock(&mosq->out_packet_mutex); state = mosquitto__get_state(mosq); #if defined(WITH_TLS) && !defined(WITH_BROKER) if((state == mosq_cs_connect_pending) || mosq->want_connect){ #else if(state == mosq_cs_connect_pending){ #endif pthread_mutex_unlock(&mosq->current_out_packet_mutex); return MOSQ_ERR_SUCCESS; } while(mosq->current_out_packet){ packet = mosq->current_out_packet; while(packet->to_process > 0){ write_length = net__write(mosq, &(packet->payload[packet->pos]), packet->to_process); if(write_length > 0){ G_BYTES_SENT_INC(write_length); packet->to_process -= write_length; packet->pos += write_length; }else{ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK #ifdef WIN32 || errno == WSAENOTCONN #endif ){ pthread_mutex_unlock(&mosq->current_out_packet_mutex); return MOSQ_ERR_SUCCESS; }else{ pthread_mutex_unlock(&mosq->current_out_packet_mutex); switch(errno){ case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } } G_MSGS_SENT_INC(1); if(((packet->command)&0xF6) == CMD_PUBLISH){ G_PUB_MSGS_SENT_INC(1); #ifndef WITH_BROKER pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_publish){ /* This is a QoS=0 message */ mosq->in_callback = true; mosq->on_publish(mosq, mosq->userdata, packet->mid); mosq->in_callback = false; } if(mosq->on_publish_v5){ /* This is a QoS=0 message */ mosq->in_callback = true; mosq->on_publish_v5(mosq, mosq->userdata, packet->mid, 0, NULL); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); }else if(((packet->command)&0xF0) == CMD_DISCONNECT){ do_client_disconnect(mosq, MOSQ_ERR_SUCCESS, NULL); packet__cleanup(packet); mosquitto__free(packet); return MOSQ_ERR_SUCCESS; #endif } /* Free data and reset values */ pthread_mutex_lock(&mosq->out_packet_mutex); mosq->current_out_packet = mosq->out_packet; if(mosq->out_packet){ mosq->out_packet = mosq->out_packet->next; if(!mosq->out_packet){ mosq->out_packet_last = NULL; } } pthread_mutex_unlock(&mosq->out_packet_mutex); packet__cleanup(packet); mosquitto__free(packet); pthread_mutex_lock(&mosq->msgtime_mutex); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; pthread_mutex_unlock(&mosq->msgtime_mutex); } pthread_mutex_unlock(&mosq->current_out_packet_mutex); return MOSQ_ERR_SUCCESS; } #ifdef WITH_BROKER int packet__read(struct mosquitto_db *db, struct mosquitto *mosq) #else int packet__read(struct mosquitto *mosq) #endif { uint8_t byte; ssize_t read_length; int rc = 0; int state; if(!mosq){ return MOSQ_ERR_INVAL; } if(mosq->sock == INVALID_SOCKET){ return MOSQ_ERR_NO_CONN; } state = mosquitto__get_state(mosq); if(state == mosq_cs_connect_pending){ return MOSQ_ERR_SUCCESS; } /* This gets called if pselect() indicates that there is network data * available - ie. at least one byte. What we do depends on what data we * already have. * If we've not got a command, attempt to read one and save it. This should * always work because it's only a single byte. * Then try to read the remaining length. This may fail because it is may * be more than one byte - will need to save data pending next read if it * does fail. * Then try to read the remaining payload, where 'payload' here means the * combined variable header and actual payload. This is the most likely to * fail due to longer length, so save current data and current position. * After all data is read, send to mosquitto__handle_packet() to deal with. * Finally, free the memory and reset everything to starting conditions. */ if(!mosq->in_packet.command){ read_length = net__read(mosq, &byte, 1); if(read_length == 1){ mosq->in_packet.command = byte; #ifdef WITH_BROKER G_BYTES_RECEIVED_INC(1); /* Clients must send CONNECT as their first command. */ if(!(mosq->bridge) && mosq->state == mosq_cs_connected && (byte&0xF0) != CMD_CONNECT){ return MOSQ_ERR_PROTOCOL; } #endif }else{ if(read_length == 0){ return MOSQ_ERR_CONN_LOST; /* EOF */ } #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ return MOSQ_ERR_SUCCESS; }else{ switch(errno){ case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } } /* remaining_count is the number of bytes that the remaining_length * parameter occupied in this incoming packet. We don't use it here as such * (it is used when allocating an outgoing packet), but we must be able to * determine whether all of the remaining_length parameter has been read. * remaining_count has three states here: * 0 means that we haven't read any remaining_length bytes * <0 means we have read some remaining_length bytes but haven't finished * >0 means we have finished reading the remaining_length bytes. */ if(mosq->in_packet.remaining_count <= 0){ do{ read_length = net__read(mosq, &byte, 1); if(read_length == 1){ mosq->in_packet.remaining_count--; /* Max 4 bytes length for remaining length as defined by protocol. * Anything more likely means a broken/malicious client. */ if(mosq->in_packet.remaining_count < -4){ return MOSQ_ERR_PROTOCOL; } G_BYTES_RECEIVED_INC(1); mosq->in_packet.remaining_length += (byte & 127) * mosq->in_packet.remaining_mult; mosq->in_packet.remaining_mult *= 128; }else{ if(read_length == 0){ return MOSQ_ERR_CONN_LOST; /* EOF */ } #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ return MOSQ_ERR_SUCCESS; }else{ switch(errno){ case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } }while((byte & 128) != 0); /* We have finished reading remaining_length, so make remaining_count * positive. */ mosq->in_packet.remaining_count *= -1; #ifdef WITH_BROKER if(db->config->max_packet_size > 0 && mosq->in_packet.remaining_length+1 > db->config->max_packet_size){ log__printf(NULL, MOSQ_LOG_INFO, "Client %s sent too large packet %d, disconnecting.", mosq->id, mosq->in_packet.remaining_length+1); if(mosq->protocol == mosq_p_mqtt5){ send__disconnect(mosq, MQTT_RC_PACKET_TOO_LARGE, NULL); } return MOSQ_ERR_OVERSIZE_PACKET; } #else // FIXME - client case for incoming message received from broker too large #endif if(mosq->in_packet.remaining_length > 0){ mosq->in_packet.payload = mosquitto__malloc(mosq->in_packet.remaining_length*sizeof(uint8_t)); if(!mosq->in_packet.payload){ return MOSQ_ERR_NOMEM; } mosq->in_packet.to_process = mosq->in_packet.remaining_length; } } while(mosq->in_packet.to_process>0){ read_length = net__read(mosq, &(mosq->in_packet.payload[mosq->in_packet.pos]), mosq->in_packet.to_process); if(read_length > 0){ G_BYTES_RECEIVED_INC(read_length); mosq->in_packet.to_process -= read_length; mosq->in_packet.pos += read_length; }else{ #ifdef WIN32 errno = WSAGetLastError(); #endif if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK){ if(mosq->in_packet.to_process > 1000){ /* Update last_msg_in time if more than 1000 bytes left to * receive. Helps when receiving large messages. * This is an arbitrary limit, but with some consideration. * If a client can't send 1000 bytes in a second it * probably shouldn't be using a 1 second keep alive. */ pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); pthread_mutex_unlock(&mosq->msgtime_mutex); } return MOSQ_ERR_SUCCESS; }else{ switch(errno){ case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; default: return MOSQ_ERR_ERRNO; } } } } /* All data for this packet is read. */ mosq->in_packet.pos = 0; #ifdef WITH_BROKER G_MSGS_RECEIVED_INC(1); if(((mosq->in_packet.command)&0xF5) == CMD_PUBLISH){ G_PUB_MSGS_RECEIVED_INC(1); } rc = handle__packet(db, mosq); #else rc = handle__packet(mosq); #endif /* Free data and reset values */ packet__cleanup(&mosq->in_packet); pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); pthread_mutex_unlock(&mosq->msgtime_mutex); return rc; } mosquitto-1.6.9/lib/send_mosq.h0000664000175000017500000000430013626052637015531 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef SEND_MOSQ_H #define SEND_MOSQ_H #include "mosquitto.h" #include "property_mosq.h" int send__simple_command(struct mosquitto *mosq, uint8_t command); int send__command_with_mid(struct mosquitto *mosq, uint8_t command, uint16_t mid, bool dup, uint8_t reason_code, const mosquitto_property *properties); int send__real_publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval); int send__connect(struct mosquitto *mosq, uint16_t keepalive, bool clean_session, const mosquitto_property *properties); int send__disconnect(struct mosquitto *mosq, uint8_t reason_code, const mosquitto_property *properties); int send__pingreq(struct mosquitto *mosq); int send__pingresp(struct mosquitto *mosq); int send__puback(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code); int send__pubcomp(struct mosquitto *mosq, uint16_t mid); int send__publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval); int send__pubrec(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code); int send__pubrel(struct mosquitto *mosq, uint16_t mid); int send__subscribe(struct mosquitto *mosq, int *mid, int topic_count, char *const *const topic, int topic_qos, const mosquitto_property *properties); int send__unsubscribe(struct mosquitto *mosq, int *mid, int topic_count, char *const *const topic, const mosquitto_property *properties); #endif mosquitto-1.6.9/lib/handle_publish.c0000664000175000017500000001111213626052637016514 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "memory_mosq.h" #include "mqtt_protocol.h" #include "messages_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "time_mosq.h" #include "util_mosq.h" int handle__publish(struct mosquitto *mosq) { uint8_t header; struct mosquitto_message_all *message; int rc = 0; uint16_t mid; int slen; mosquitto_property *properties = NULL; int state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } message = mosquitto__calloc(1, sizeof(struct mosquitto_message_all)); if(!message) return MOSQ_ERR_NOMEM; header = mosq->in_packet.command; message->dup = (header & 0x08)>>3; message->msg.qos = (header & 0x06)>>1; message->msg.retain = (header & 0x01); rc = packet__read_string(&mosq->in_packet, &message->msg.topic, &slen); if(rc){ message__cleanup(&message); return rc; } if(!slen){ message__cleanup(&message); return MOSQ_ERR_PROTOCOL; } if(message->msg.qos > 0){ if(mosq->protocol == mosq_p_mqtt5){ if(mosq->msgs_in.inflight_quota == 0){ message__cleanup(&message); /* FIXME - should send a DISCONNECT here */ return MOSQ_ERR_PROTOCOL; } } rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc){ message__cleanup(&message); return rc; } if(mid == 0){ message__cleanup(&message); return MOSQ_ERR_PROTOCOL; } message->msg.mid = (int)mid; } if(mosq->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_PUBLISH, &mosq->in_packet, &properties); if(rc) return rc; } message->msg.payloadlen = mosq->in_packet.remaining_length - mosq->in_packet.pos; if(message->msg.payloadlen){ message->msg.payload = mosquitto__calloc(message->msg.payloadlen+1, sizeof(uint8_t)); if(!message->msg.payload){ message__cleanup(&message); mosquitto_property_free_all(&properties); return MOSQ_ERR_NOMEM; } rc = packet__read_bytes(&mosq->in_packet, message->msg.payload, message->msg.payloadlen); if(rc){ message__cleanup(&message); mosquitto_property_free_all(&properties); return rc; } } log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PUBLISH (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", mosq->id, message->dup, message->msg.qos, message->msg.retain, message->msg.mid, message->msg.topic, (long)message->msg.payloadlen); message->timestamp = mosquitto_time(); switch(message->msg.qos){ case 0: pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_message){ mosq->in_callback = true; mosq->on_message(mosq, mosq->userdata, &message->msg); mosq->in_callback = false; } if(mosq->on_message_v5){ mosq->in_callback = true; mosq->on_message_v5(mosq, mosq->userdata, &message->msg, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); message__cleanup(&message); mosquitto_property_free_all(&properties); return MOSQ_ERR_SUCCESS; case 1: util__decrement_receive_quota(mosq); rc = send__puback(mosq, message->msg.mid, 0); pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_message){ mosq->in_callback = true; mosq->on_message(mosq, mosq->userdata, &message->msg); mosq->in_callback = false; } if(mosq->on_message_v5){ mosq->in_callback = true; mosq->on_message_v5(mosq, mosq->userdata, &message->msg, properties); mosq->in_callback = false; } pthread_mutex_unlock(&mosq->callback_mutex); message__cleanup(&message); mosquitto_property_free_all(&properties); return rc; case 2: message->properties = properties; util__decrement_receive_quota(mosq); rc = send__pubrec(mosq, message->msg.mid, 0); pthread_mutex_lock(&mosq->msgs_in.mutex); message->state = mosq_ms_wait_for_pubrel; message__queue(mosq, message, mosq_md_in); pthread_mutex_unlock(&mosq->msgs_in.mutex); return rc; default: message__cleanup(&message); mosquitto_property_free_all(&properties); return MOSQ_ERR_PROTOCOL; } } mosquitto-1.6.9/lib/packet_datatypes.c0000664000175000017500000001317013626052637017066 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # ifdef WITH_WEBSOCKETS # include # endif #else # include "read_handle.h" #endif #include "memory_mosq.h" #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #ifdef WITH_BROKER # include "sys_tree.h" #else # define G_BYTES_RECEIVED_INC(A) # define G_BYTES_SENT_INC(A) # define G_MSGS_SENT_INC(A) # define G_PUB_MSGS_SENT_INC(A) #endif int packet__read_byte(struct mosquitto__packet *packet, uint8_t *byte) { assert(packet); if(packet->pos+1 > packet->remaining_length) return MOSQ_ERR_PROTOCOL; *byte = packet->payload[packet->pos]; packet->pos++; return MOSQ_ERR_SUCCESS; } void packet__write_byte(struct mosquitto__packet *packet, uint8_t byte) { assert(packet); assert(packet->pos+1 <= packet->packet_length); packet->payload[packet->pos] = byte; packet->pos++; } int packet__read_bytes(struct mosquitto__packet *packet, void *bytes, uint32_t count) { assert(packet); if(packet->pos+count > packet->remaining_length) return MOSQ_ERR_PROTOCOL; memcpy(bytes, &(packet->payload[packet->pos]), count); packet->pos += count; return MOSQ_ERR_SUCCESS; } void packet__write_bytes(struct mosquitto__packet *packet, const void *bytes, uint32_t count) { assert(packet); assert(packet->pos+count <= packet->packet_length); memcpy(&(packet->payload[packet->pos]), bytes, count); packet->pos += count; } int packet__read_binary(struct mosquitto__packet *packet, uint8_t **data, int *length) { uint16_t slen; int rc; assert(packet); rc = packet__read_uint16(packet, &slen); if(rc) return rc; if(slen == 0){ *data = NULL; *length = 0; return MOSQ_ERR_SUCCESS; } if(packet->pos+slen > packet->remaining_length) return MOSQ_ERR_PROTOCOL; *data = mosquitto__malloc(slen+1); if(*data){ memcpy(*data, &(packet->payload[packet->pos]), slen); ((uint8_t *)(*data))[slen] = '\0'; packet->pos += slen; }else{ return MOSQ_ERR_NOMEM; } *length = slen; return MOSQ_ERR_SUCCESS; } int packet__read_string(struct mosquitto__packet *packet, char **str, int *length) { int rc; rc = packet__read_binary(packet, (uint8_t **)str, length); if(rc) return rc; if(*length == 0) return MOSQ_ERR_SUCCESS; if(mosquitto_validate_utf8(*str, *length)){ mosquitto__free(*str); *str = NULL; *length = -1; return MOSQ_ERR_MALFORMED_UTF8; } return MOSQ_ERR_SUCCESS; } void packet__write_string(struct mosquitto__packet *packet, const char *str, uint16_t length) { assert(packet); packet__write_uint16(packet, length); packet__write_bytes(packet, str, length); } int packet__read_uint16(struct mosquitto__packet *packet, uint16_t *word) { uint8_t msb, lsb; assert(packet); if(packet->pos+2 > packet->remaining_length) return MOSQ_ERR_PROTOCOL; msb = packet->payload[packet->pos]; packet->pos++; lsb = packet->payload[packet->pos]; packet->pos++; *word = (msb<<8) + lsb; return MOSQ_ERR_SUCCESS; } void packet__write_uint16(struct mosquitto__packet *packet, uint16_t word) { packet__write_byte(packet, MOSQ_MSB(word)); packet__write_byte(packet, MOSQ_LSB(word)); } int packet__read_uint32(struct mosquitto__packet *packet, uint32_t *word) { uint32_t val = 0; int i; assert(packet); if(packet->pos+4 > packet->remaining_length) return MOSQ_ERR_PROTOCOL; for(i=0; i<4; i++){ val = (val << 8) + packet->payload[packet->pos]; packet->pos++; } *word = val; return MOSQ_ERR_SUCCESS; } void packet__write_uint32(struct mosquitto__packet *packet, uint32_t word) { packet__write_byte(packet, (word & 0xFF000000) >> 24); packet__write_byte(packet, (word & 0x00FF0000) >> 16); packet__write_byte(packet, (word & 0x0000FF00) >> 8); packet__write_byte(packet, (word & 0x000000FF)); } int packet__read_varint(struct mosquitto__packet *packet, int32_t *word, int8_t *bytes) { int i; uint8_t byte; int remaining_mult = 1; int32_t lword = 0; uint8_t lbytes = 0; for(i=0; i<4; i++){ if(packet->pos < packet->remaining_length){ lbytes++; byte = packet->payload[packet->pos]; lword += (byte & 127) * remaining_mult; remaining_mult *= 128; packet->pos++; if((byte & 128) == 0){ if(lbytes > 1 && byte == 0){ /* Catch overlong encodings */ return MOSQ_ERR_PROTOCOL; }else{ *word = lword; if(bytes) (*bytes) = lbytes; return MOSQ_ERR_SUCCESS; } } }else{ return MOSQ_ERR_PROTOCOL; } } return MOSQ_ERR_PROTOCOL; } int packet__write_varint(struct mosquitto__packet *packet, int32_t word) { uint8_t byte; int count = 0; do{ byte = word % 128; word = word / 128; /* If there are more digits to encode, set the top bit of this digit */ if(word > 0){ byte = byte | 0x80; } packet__write_byte(packet, byte); count++; }while(word > 0 && count < 5); if(count == 5){ return MOSQ_ERR_PROTOCOL; } return MOSQ_ERR_SUCCESS; } int packet__varint_bytes(int32_t word) { if(word < 128){ return 1; }else if(word < 16384){ return 2; }else if(word < 2097152){ return 3; }else if(word < 268435456){ return 4; }else{ return 5; } } mosquitto-1.6.9/lib/memory_mosq.h0000664000175000017500000000221713626052637016115 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MEMORY_MOSQ_H #define MEMORY_MOSQ_H #include #include #if defined(WITH_MEMORY_TRACKING) && defined(WITH_BROKER) && defined(__GLIBC__) #define REAL_WITH_MEMORY_TRACKING #endif void *mosquitto__calloc(size_t nmemb, size_t size); void mosquitto__free(void *mem); void *mosquitto__malloc(size_t size); #ifdef REAL_WITH_MEMORY_TRACKING unsigned long mosquitto__memory_used(void); unsigned long mosquitto__max_memory_used(void); #endif void *mosquitto__realloc(void *ptr, size_t size); char *mosquitto__strdup(const char *s); #ifdef WITH_BROKER void memory__set_limit(size_t lim); #endif #endif mosquitto-1.6.9/lib/messages_mosq.c0000664000175000017500000002136613626052637016415 0ustar rogerroger/* Copyright (c) 2010-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "mosquitto_internal.h" #include "mosquitto.h" #include "memory_mosq.h" #include "messages_mosq.h" #include "send_mosq.h" #include "time_mosq.h" #include "util_mosq.h" void message__cleanup(struct mosquitto_message_all **message) { struct mosquitto_message_all *msg; if(!message || !*message) return; msg = *message; mosquitto__free(msg->msg.topic); mosquitto__free(msg->msg.payload); mosquitto_property_free_all(&msg->properties); mosquitto__free(msg); } void message__cleanup_all(struct mosquitto *mosq) { struct mosquitto_message_all *tail, *tmp; assert(mosq); DL_FOREACH_SAFE(mosq->msgs_in.inflight, tail, tmp){ DL_DELETE(mosq->msgs_in.inflight, tail); message__cleanup(&tail); } DL_FOREACH_SAFE(mosq->msgs_out.inflight, tail, tmp){ DL_DELETE(mosq->msgs_out.inflight, tail); message__cleanup(&tail); } } int mosquitto_message_copy(struct mosquitto_message *dst, const struct mosquitto_message *src) { if(!dst || !src) return MOSQ_ERR_INVAL; dst->mid = src->mid; dst->topic = mosquitto__strdup(src->topic); if(!dst->topic) return MOSQ_ERR_NOMEM; dst->qos = src->qos; dst->retain = src->retain; if(src->payloadlen){ dst->payload = mosquitto__calloc(src->payloadlen+1, sizeof(uint8_t)); if(!dst->payload){ mosquitto__free(dst->topic); return MOSQ_ERR_NOMEM; } memcpy(dst->payload, src->payload, src->payloadlen); dst->payloadlen = src->payloadlen; }else{ dst->payloadlen = 0; dst->payload = NULL; } return MOSQ_ERR_SUCCESS; } int message__delete(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir, int qos) { struct mosquitto_message_all *message; int rc; assert(mosq); rc = message__remove(mosq, mid, dir, &message, qos); if(rc == MOSQ_ERR_SUCCESS){ message__cleanup(&message); } return rc; } void mosquitto_message_free(struct mosquitto_message **message) { struct mosquitto_message *msg; if(!message || !*message) return; msg = *message; mosquitto__free(msg->topic); mosquitto__free(msg->payload); mosquitto__free(msg); } void mosquitto_message_free_contents(struct mosquitto_message *message) { if(!message) return; mosquitto__free(message->topic); mosquitto__free(message->payload); } int message__queue(struct mosquitto *mosq, struct mosquitto_message_all *message, enum mosquitto_msg_direction dir) { /* mosq->*_message_mutex should be locked before entering this function */ assert(mosq); assert(message); assert(message->msg.qos != 0); if(dir == mosq_md_out){ DL_APPEND(mosq->msgs_out.inflight, message); mosq->msgs_out.queue_len++; }else{ DL_APPEND(mosq->msgs_in.inflight, message); mosq->msgs_in.queue_len++; } return message__release_to_inflight(mosq, dir); } void message__reconnect_reset(struct mosquitto *mosq) { struct mosquitto_message_all *message, *tmp; assert(mosq); pthread_mutex_lock(&mosq->msgs_in.mutex); mosq->msgs_in.inflight_quota = mosq->msgs_in.inflight_maximum; mosq->msgs_in.queue_len = 0; DL_FOREACH_SAFE(mosq->msgs_in.inflight, message, tmp){ mosq->msgs_in.queue_len++; message->timestamp = 0; if(message->msg.qos != 2){ DL_DELETE(mosq->msgs_in.inflight, message); message__cleanup(&message); }else{ /* Message state can be preserved here because it should match * whatever the client has got. */ util__decrement_receive_quota(mosq); } } pthread_mutex_unlock(&mosq->msgs_in.mutex); pthread_mutex_lock(&mosq->msgs_out.mutex); mosq->msgs_out.inflight_quota = mosq->msgs_out.inflight_maximum; mosq->msgs_out.queue_len = 0; DL_FOREACH_SAFE(mosq->msgs_out.inflight, message, tmp){ mosq->msgs_out.queue_len++; message->timestamp = 0; if(mosq->msgs_out.inflight_quota != 0){ util__decrement_send_quota(mosq); if(message->msg.qos == 1){ message->state = mosq_ms_publish_qos1; }else if(message->msg.qos == 2){ if(message->state == mosq_ms_wait_for_pubrec){ message->state = mosq_ms_publish_qos2; }else if(message->state == mosq_ms_wait_for_pubcomp){ message->state = mosq_ms_resend_pubrel; } /* Should be able to preserve state. */ } }else{ message->state = mosq_ms_invalid; } } pthread_mutex_unlock(&mosq->msgs_out.mutex); } int message__release_to_inflight(struct mosquitto *mosq, enum mosquitto_msg_direction dir) { /* mosq->*_message_mutex should be locked before entering this function */ struct mosquitto_message_all *cur, *tmp; int rc = MOSQ_ERR_SUCCESS; if(dir == mosq_md_out){ DL_FOREACH_SAFE(mosq->msgs_out.inflight, cur, tmp){ if(mosq->msgs_out.inflight_quota > 0){ if(cur->msg.qos > 0 && cur->state == mosq_ms_invalid){ if(cur->msg.qos == 1){ cur->state = mosq_ms_wait_for_puback; }else if(cur->msg.qos == 2){ cur->state = mosq_ms_wait_for_pubrec; } rc = send__publish(mosq, cur->msg.mid, cur->msg.topic, cur->msg.payloadlen, cur->msg.payload, cur->msg.qos, cur->msg.retain, cur->dup, cur->properties, NULL, 0); if(rc){ return rc; } util__decrement_send_quota(mosq); } }else{ return MOSQ_ERR_SUCCESS; } } } return rc; } int message__remove(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir, struct mosquitto_message_all **message, int qos) { struct mosquitto_message_all *cur, *tmp; bool found = false; assert(mosq); assert(message); if(dir == mosq_md_out){ pthread_mutex_lock(&mosq->msgs_out.mutex); DL_FOREACH_SAFE(mosq->msgs_out.inflight, cur, tmp){ if(found == false && cur->msg.mid == mid){ if(cur->msg.qos != qos){ pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_PROTOCOL; } DL_DELETE(mosq->msgs_out.inflight, cur); *message = cur; mosq->msgs_out.queue_len--; found = true; break; } } pthread_mutex_unlock(&mosq->msgs_out.mutex); if(found){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } }else{ pthread_mutex_lock(&mosq->msgs_in.mutex); DL_FOREACH_SAFE(mosq->msgs_in.inflight, cur, tmp){ if(cur->msg.mid == mid){ if(cur->msg.qos != qos){ pthread_mutex_unlock(&mosq->msgs_in.mutex); return MOSQ_ERR_PROTOCOL; } DL_DELETE(mosq->msgs_in.inflight, cur); *message = cur; mosq->msgs_in.queue_len--; found = true; break; } } pthread_mutex_unlock(&mosq->msgs_in.mutex); if(found){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } } } void message__retry_check(struct mosquitto *mosq) { struct mosquitto_message_all *msg; time_t now = mosquitto_time(); assert(mosq); #ifdef WITH_THREADING pthread_mutex_lock(&mosq->msgs_out.mutex); #endif DL_FOREACH(mosq->msgs_out.inflight, msg){ switch(msg->state){ case mosq_ms_publish_qos1: case mosq_ms_publish_qos2: msg->timestamp = now; msg->dup = true; send__publish(mosq, msg->msg.mid, msg->msg.topic, msg->msg.payloadlen, msg->msg.payload, msg->msg.qos, msg->msg.retain, msg->dup, msg->properties, NULL, 0); break; case mosq_ms_wait_for_pubrel: msg->timestamp = now; msg->dup = true; send__pubrec(mosq, msg->msg.mid, 0); break; case mosq_ms_resend_pubrel: case mosq_ms_wait_for_pubcomp: msg->timestamp = now; msg->dup = true; send__pubrel(mosq, msg->msg.mid); break; default: break; } } #ifdef WITH_THREADING pthread_mutex_unlock(&mosq->msgs_out.mutex); #endif } void mosquitto_message_retry_set(struct mosquitto *mosq, unsigned int message_retry) { UNUSED(mosq); UNUSED(message_retry); } int message__out_update(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_state state, int qos) { struct mosquitto_message_all *message, *tmp; assert(mosq); pthread_mutex_lock(&mosq->msgs_out.mutex); DL_FOREACH_SAFE(mosq->msgs_out.inflight, message, tmp){ if(message->msg.mid == mid){ if(message->msg.qos != qos){ pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_PROTOCOL; } message->state = state; message->timestamp = mosquitto_time(); pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_SUCCESS; } } pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_NOT_FOUND; } int mosquitto_max_inflight_messages_set(struct mosquitto *mosq, unsigned int max_inflight_messages) { return mosquitto_int_option(mosq, MOSQ_OPT_SEND_MAXIMUM, max_inflight_messages); } mosquitto-1.6.9/lib/Makefile0000664000175000017500000001600313626052637015033 0ustar rogerrogerinclude ../config.mk .PHONY : really clean install MOSQ_OBJS=mosquitto.o \ actions.o \ callbacks.o \ connect.o \ handle_auth.o \ handle_connack.o \ handle_disconnect.o \ handle_ping.o \ handle_pubackcomp.o \ handle_publish.o \ handle_pubrec.o \ handle_pubrel.o \ handle_suback.o \ handle_unsuback.o \ helpers.o \ logging_mosq.o \ loop.o \ memory_mosq.o \ messages_mosq.o \ misc_mosq.o \ net_mosq_ocsp.o \ net_mosq.o \ options.o \ packet_datatypes.o \ packet_mosq.o \ property_mosq.o \ read_handle.o \ send_connect.o \ send_disconnect.o \ send_mosq.o \ send_publish.o \ send_subscribe.o \ send_unsubscribe.o \ socks_mosq.o \ srv_mosq.o \ thread_mosq.o \ time_mosq.o \ tls_mosq.o \ utf8_mosq.o \ util_mosq.o \ util_topic.o \ will_mosq.o ALL_DEPS:= ifeq ($(WITH_SHARED_LIBRARIES),yes) ALL_DEPS+=libmosquitto.so.${SOVERSION} endif ifeq ($(WITH_STATIC_LIBRARIES),yes) ALL_DEPS+=libmosquitto.a endif all : ${ALL_DEPS} ifeq ($(WITH_SHARED_LIBRARIES),yes) $(MAKE) -C cpp endif install : all $(INSTALL) -d "${DESTDIR}${libdir}/" ifeq ($(WITH_SHARED_LIBRARIES),yes) $(INSTALL) ${STRIP_OPTS} libmosquitto.so.${SOVERSION} "${DESTDIR}${libdir}/libmosquitto.so.${SOVERSION}" ln -sf libmosquitto.so.${SOVERSION} "${DESTDIR}${libdir}/libmosquitto.so" endif ifeq ($(WITH_STATIC_LIBRARIES),yes) $(INSTALL) ${STRIP_OPTS} libmosquitto.a "${DESTDIR}${libdir}/libmosquitto.a" endif $(INSTALL) -d "${DESTDIR}${incdir}/" $(INSTALL) mosquitto.h "${DESTDIR}${incdir}/mosquitto.h" $(INSTALL) mqtt_protocol.h "${DESTDIR}${incdir}/mqtt_protocol.h" $(INSTALL) -d "${DESTDIR}${libdir}/pkgconfig" $(INSTALL) -m644 ../libmosquitto.pc.in "${DESTDIR}${libdir}/pkgconfig/libmosquitto.pc" sed -i -e "s#@CMAKE_INSTALL_PREFIX@#${prefix}#" -e "s#@VERSION@#${VERSION}#" "${DESTDIR}${libdir}/pkgconfig/libmosquitto.pc" ifeq ($(WITH_SHARED_LIBRARIES),yes) $(MAKE) -C cpp install endif uninstall : -rm -f "${DESTDIR}${libdir}/libmosquitto.so.${SOVERSION}" -rm -f "${DESTDIR}${libdir}/libmosquitto.so" -rm -f "${DESTDIR}${libdir}/libmosquitto.a" -rm -f "${DESTDIR}${incdir}/mosquitto.h" reallyclean : clean clean : -rm -f *.o libmosquitto.so.${SOVERSION} libmosquitto.so libmosquitto.a *.gcno *.gcda $(MAKE) -C cpp clean libmosquitto.so.${SOVERSION} : ${MOSQ_OBJS} ${CROSS_COMPILE}$(CC) -shared $(LIB_LDFLAGS) $^ -o $@ ${LIB_LIBADD} libmosquitto.a : ${MOSQ_OBJS} ${CROSS_COMPILE}$(AR) cr $@ $^ mosquitto.o : mosquitto.c mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ actions.o : actions.c mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ callbacks.o : callbacks.c mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ connect.o : connect.c mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_auth.o : handle_auth.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_connack.o : handle_connack.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_disconnect.o : handle_disconnect.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_publish.o : handle_publish.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_ping.o : handle_ping.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_pubackcomp.o : handle_pubackcomp.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_pubrec.o : handle_pubrec.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_pubrel.o : handle_pubrel.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_suback.o : handle_suback.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ handle_unsuback.o : handle_unsuback.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ helpers.o : helpers.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ logging_mosq.o : logging_mosq.c logging_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ loop.o : loop.c mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ messages_mosq.o : messages_mosq.c messages_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ memory_mosq.o : memory_mosq.c memory_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ misc_mosq.o : misc_mosq.c misc_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ net_mosq_ocsp.o : net_mosq_ocsp.c net_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ net_mosq.o : net_mosq.c net_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ options.o : options.c mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ packet_datatypes.o : packet_datatypes.c packet_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ packet_mosq.o : packet_mosq.c packet_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ property_mosq.o : property_mosq.c property_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ read_handle.o : read_handle.c read_handle.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ send_connect.o : send_connect.c send_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ send_disconnect.o : send_disconnect.c send_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ send_mosq.o : send_mosq.c send_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ send_publish.o : send_publish.c send_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ send_subscribe.o : send_subscribe.c send_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ send_unsubscribe.o : send_unsubscribe.c send_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ socks_mosq.o : socks_mosq.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ srv_mosq.o : srv_mosq.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ thread_mosq.o : thread_mosq.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ time_mosq.o : time_mosq.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ tls_mosq.o : tls_mosq.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ utf8_mosq.o : utf8_mosq.c ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ util_mosq.o : util_mosq.c util_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ util_topic.o : util_topic.c util_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ will_mosq.o : will_mosq.c will_mosq.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ mosquitto-1.6.9/lib/mqtt_protocol.h0000664000175000017500000001530013626052637016451 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MQTT_PROTOCOL_H #define MQTT_PROTOCOL_H #define PROTOCOL_NAME_v31 "MQIsdp" #define PROTOCOL_VERSION_v31 3 #define PROTOCOL_NAME "MQTT" #define PROTOCOL_VERSION_v311 4 #define PROTOCOL_VERSION_v5 5 /* Message types */ #define CMD_CONNECT 0x10 #define CMD_CONNACK 0x20 #define CMD_PUBLISH 0x30 #define CMD_PUBACK 0x40 #define CMD_PUBREC 0x50 #define CMD_PUBREL 0x60 #define CMD_PUBCOMP 0x70 #define CMD_SUBSCRIBE 0x80 #define CMD_SUBACK 0x90 #define CMD_UNSUBSCRIBE 0xA0 #define CMD_UNSUBACK 0xB0 #define CMD_PINGREQ 0xC0 #define CMD_PINGRESP 0xD0 #define CMD_DISCONNECT 0xE0 #define CMD_AUTH 0xF0 /* Mosquitto only: for distinguishing CONNECT and WILL properties */ #define CMD_WILL 0x100 enum mqtt311_connack_codes { CONNACK_ACCEPTED = 0, CONNACK_REFUSED_PROTOCOL_VERSION = 1, CONNACK_REFUSED_IDENTIFIER_REJECTED = 2, CONNACK_REFUSED_SERVER_UNAVAILABLE = 3, CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4, CONNACK_REFUSED_NOT_AUTHORIZED = 5, }; enum mqtt5_return_codes { MQTT_RC_SUCCESS = 0, /* CONNACK, PUBACK, PUBREC, PUBREL, PUBCOMP, UNSUBACK, AUTH */ MQTT_RC_NORMAL_DISCONNECTION = 0, /* DISCONNECT */ MQTT_RC_GRANTED_QOS0 = 0, /* SUBACK */ MQTT_RC_GRANTED_QOS1 = 1, /* SUBACK */ MQTT_RC_GRANTED_QOS2 = 2, /* SUBACK */ MQTT_RC_DISCONNECT_WITH_WILL_MSG = 4, /* DISCONNECT */ MQTT_RC_NO_MATCHING_SUBSCRIBERS = 16, /* PUBACK, PUBREC */ MQTT_RC_NO_SUBSCRIPTION_EXISTED = 17, /* UNSUBACK */ MQTT_RC_CONTINUE_AUTHENTICATION = 24, /* AUTH */ MQTT_RC_REAUTHENTICATE = 25, /* AUTH */ MQTT_RC_UNSPECIFIED = 128, /* CONNACK, PUBACK, PUBREC, SUBACK, UNSUBACK, DISCONNECT */ MQTT_RC_MALFORMED_PACKET = 129, /* CONNACK, DISCONNECT */ MQTT_RC_PROTOCOL_ERROR = 130, /* DISCONNECT */ MQTT_RC_IMPLEMENTATION_SPECIFIC = 131, /* CONNACK, PUBACK, PUBREC, SUBACK, UNSUBACK, DISCONNECT */ MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION = 132, /* CONNACK */ MQTT_RC_CLIENTID_NOT_VALID = 133, /* CONNACK */ MQTT_RC_BAD_USERNAME_OR_PASSWORD = 134, /* CONNACK */ MQTT_RC_NOT_AUTHORIZED = 135, /* CONNACK, PUBACK, PUBREC, SUBACK, UNSUBACK, DISCONNECT */ MQTT_RC_SERVER_UNAVAILABLE = 136, /* CONNACK */ MQTT_RC_SERVER_BUSY = 137, /* CONNACK, DISCONNECT */ MQTT_RC_BANNED = 138, /* CONNACK */ MQTT_RC_SERVER_SHUTTING_DOWN = 139, /* DISCONNECT */ MQTT_RC_BAD_AUTHENTICATION_METHOD = 140, /* CONNACK */ MQTT_RC_KEEP_ALIVE_TIMEOUT = 141, /* DISCONNECT */ MQTT_RC_SESSION_TAKEN_OVER = 142, /* DISCONNECT */ MQTT_RC_TOPIC_FILTER_INVALID = 143, /* SUBACK, UNSUBACK, DISCONNECT */ MQTT_RC_TOPIC_NAME_INVALID = 144, /* CONNACK, PUBACK, PUBREC, DISCONNECT */ MQTT_RC_PACKET_ID_IN_USE = 145, /* PUBACK, SUBACK, UNSUBACK */ MQTT_RC_PACKET_ID_NOT_FOUND = 146, /* PUBREL, PUBCOMP */ MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED = 147, /* DISCONNECT */ MQTT_RC_TOPIC_ALIAS_INVALID = 148, /* DISCONNECT */ MQTT_RC_PACKET_TOO_LARGE = 149, /* CONNACK, PUBACK, PUBREC, DISCONNECT */ MQTT_RC_MESSAGE_RATE_TOO_HIGH = 150, /* DISCONNECT */ MQTT_RC_QUOTA_EXCEEDED = 151, /* PUBACK, PUBREC, SUBACK, DISCONNECT */ MQTT_RC_ADMINISTRATIVE_ACTION = 152, /* DISCONNECT */ MQTT_RC_PAYLOAD_FORMAT_INVALID = 153, /* CONNACK, DISCONNECT */ MQTT_RC_RETAIN_NOT_SUPPORTED = 154, /* CONNACK, DISCONNECT */ MQTT_RC_QOS_NOT_SUPPORTED = 155, /* CONNACK, DISCONNECT */ MQTT_RC_USE_ANOTHER_SERVER = 156, /* CONNACK, DISCONNECT */ MQTT_RC_SERVER_MOVED = 157, /* CONNACK, DISCONNECT */ MQTT_RC_SHARED_SUBS_NOT_SUPPORTED = 158, /* SUBACK, DISCONNECT */ MQTT_RC_CONNECTION_RATE_EXCEEDED = 159, /* CONNACK, DISCONNECT */ MQTT_RC_MAXIMUM_CONNECT_TIME = 160, /* DISCONNECT */ MQTT_RC_SUBSCRIPTION_IDS_NOT_SUPPORTED = 161, /* SUBACK, DISCONNECT */ MQTT_RC_WILDCARD_SUBS_NOT_SUPPORTED = 162, /* SUBACK, DISCONNECT */ }; enum mqtt5_property { MQTT_PROP_PAYLOAD_FORMAT_INDICATOR = 1, /* Byte : PUBLISH, Will Properties */ MQTT_PROP_MESSAGE_EXPIRY_INTERVAL = 2, /* 4 byte int : PUBLISH, Will Properties */ MQTT_PROP_CONTENT_TYPE = 3, /* UTF-8 string : PUBLISH, Will Properties */ MQTT_PROP_RESPONSE_TOPIC = 8, /* UTF-8 string : PUBLISH, Will Properties */ MQTT_PROP_CORRELATION_DATA = 9, /* Binary Data : PUBLISH, Will Properties */ MQTT_PROP_SUBSCRIPTION_IDENTIFIER = 11, /* Variable byte int : PUBLISH, SUBSCRIBE */ MQTT_PROP_SESSION_EXPIRY_INTERVAL = 17, /* 4 byte int : CONNECT, CONNACK, DISCONNECT */ MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER = 18, /* UTF-8 string : CONNACK */ MQTT_PROP_SERVER_KEEP_ALIVE = 19, /* 2 byte int : CONNACK */ MQTT_PROP_AUTHENTICATION_METHOD = 21, /* UTF-8 string : CONNECT, CONNACK, AUTH */ MQTT_PROP_AUTHENTICATION_DATA = 22, /* Binary Data : CONNECT, CONNACK, AUTH */ MQTT_PROP_REQUEST_PROBLEM_INFORMATION = 23, /* Byte : CONNECT */ MQTT_PROP_WILL_DELAY_INTERVAL = 24, /* 4 byte int : Will properties */ MQTT_PROP_REQUEST_RESPONSE_INFORMATION = 25,/* Byte : CONNECT */ MQTT_PROP_RESPONSE_INFORMATION = 26, /* UTF-8 string : CONNACK */ MQTT_PROP_SERVER_REFERENCE = 28, /* UTF-8 string : CONNACK, DISCONNECT */ MQTT_PROP_REASON_STRING = 31, /* UTF-8 string : All except Will properties */ MQTT_PROP_RECEIVE_MAXIMUM = 33, /* 2 byte int : CONNECT, CONNACK */ MQTT_PROP_TOPIC_ALIAS_MAXIMUM = 34, /* 2 byte int : CONNECT, CONNACK */ MQTT_PROP_TOPIC_ALIAS = 35, /* 2 byte int : PUBLISH */ MQTT_PROP_MAXIMUM_QOS = 36, /* Byte : CONNACK */ MQTT_PROP_RETAIN_AVAILABLE = 37, /* Byte : CONNACK */ MQTT_PROP_USER_PROPERTY = 38, /* UTF-8 string pair : All */ MQTT_PROP_MAXIMUM_PACKET_SIZE = 39, /* 4 byte int : CONNECT, CONNACK */ MQTT_PROP_WILDCARD_SUB_AVAILABLE = 40, /* Byte : CONNACK */ MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE = 41, /* Byte : CONNACK */ MQTT_PROP_SHARED_SUB_AVAILABLE = 42, /* Byte : CONNACK */ }; enum mqtt5_property_type { MQTT_PROP_TYPE_BYTE = 1, MQTT_PROP_TYPE_INT16 = 2, MQTT_PROP_TYPE_INT32 = 3, MQTT_PROP_TYPE_VARINT = 4, MQTT_PROP_TYPE_BINARY = 5, MQTT_PROP_TYPE_STRING = 6, MQTT_PROP_TYPE_STRING_PAIR = 7 }; enum mqtt5_sub_options { MQTT_SUB_OPT_NO_LOCAL = 0x04, MQTT_SUB_OPT_RETAIN_AS_PUBLISHED = 0x08, MQTT_SUB_OPT_SEND_RETAIN_ALWAYS = 0x00, MQTT_SUB_OPT_SEND_RETAIN_NEW = 0x10, MQTT_SUB_OPT_SEND_RETAIN_NEVER = 0x20, }; #define MQTT_MAX_PAYLOAD 268435455U #endif mosquitto-1.6.9/client/0000775000175000017500000000000013626052637014103 5ustar rogerrogermosquitto-1.6.9/client/sub_client.c0000664000175000017500000003144013626052637016400 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #ifndef WIN32 #include #include #else #include #include #define snprintf sprintf_s #endif #include #include #include "client_shared.h" struct mosq_config cfg; bool process_messages = true; int msg_count = 0; struct mosquitto *mosq = NULL; int last_mid = 0; #ifndef WIN32 void my_signal_handler(int signum) { if(signum == SIGALRM || signum == SIGTERM || signum == SIGINT){ process_messages = false; mosquitto_disconnect_v5(mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); } } #endif void print_message(struct mosq_config *cfg, const struct mosquitto_message *message); void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { UNUSED(obj); UNUSED(reason_code); UNUSED(properties); if(process_messages == false && (mid == last_mid || last_mid == 0)){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } } void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, const mosquitto_property *properties) { int i; bool res; UNUSED(obj); UNUSED(properties); if(process_messages == false) return; if(cfg.retained_only && !message->retain && process_messages){ process_messages = false; if(last_mid == 0){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } return; } if(message->retain && cfg.no_retain) return; if(cfg.filter_outs){ for(i=0; itopic, &res); if(res) return; } } if(cfg.remove_retained && message->retain){ mosquitto_publish(mosq, &last_mid, message->topic, 0, NULL, 1, true); } print_message(&cfg, message); if(cfg.msg_count>0){ msg_count++; if(cfg.msg_count == msg_count){ process_messages = false; if(last_mid == 0){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } } } } void my_connect_callback(struct mosquitto *mosq, void *obj, int result, int flags, const mosquitto_property *properties) { int i; UNUSED(obj); UNUSED(flags); UNUSED(properties); if(!result){ mosquitto_subscribe_multiple(mosq, NULL, cfg.topic_count, cfg.topics, cfg.qos, cfg.sub_opts, cfg.subscribe_props); for(i=0; i0 && rc == MOSQ_ERR_NO_CONN){ rc = 0; } client_config_cleanup(&cfg); if(rc){ err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc)); } return rc; cleanup: mosquitto_destroy(mosq); mosquitto_lib_cleanup(); client_config_cleanup(&cfg); return 1; } mosquitto-1.6.9/client/CMakeLists.txt0000664000175000017500000000246113626052637016646 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/lib ${STDBOOL_H_PATH} ${STDINT_H_PATH} ${PTHREAD_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR}) link_directories(${mosquitto_BINARY_DIR}/lib) set(shared_src client_shared.c client_shared.h client_props.c) if (WITH_SRV) add_definitions("-DWITH_SRV") endif (WITH_SRV) add_executable(mosquitto_pub pub_client.c pub_shared.c ${shared_src}) add_executable(mosquitto_sub sub_client.c sub_client_output.c ${shared_src}) add_executable(mosquitto_rr rr_client.c pub_shared.c sub_client_output.c ${shared_src}) if (WITH_STATIC_LIBRARIES) target_link_libraries(mosquitto_pub libmosquitto_static) target_link_libraries(mosquitto_sub libmosquitto_static) target_link_libraries(mosquitto_rr libmosquitto_static) else() target_link_libraries(mosquitto_pub libmosquitto) target_link_libraries(mosquitto_sub libmosquitto) target_link_libraries(mosquitto_rr libmosquitto) endif() if (QNX) target_link_libraries(mosquitto_pub socket) target_link_libraries(mosquitto_sub socket) target_link_libraries(mosquitto_rr socket) endif() install(TARGETS mosquitto_pub RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") install(TARGETS mosquitto_sub RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") install(TARGETS mosquitto_rr RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") mosquitto-1.6.9/client/client_shared.c0000664000175000017500000011536413626052637017065 0ustar rogerroger/* Copyright (c) 2014-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #ifndef WIN32 #include #include #else #include #include #define snprintf sprintf_s #define strncasecmp _strnicmp #endif #include #include #include "client_shared.h" #ifdef WITH_SOCKS static int mosquitto__parse_socks_url(struct mosq_config *cfg, char *url); #endif static int client_config_line_proc(struct mosq_config *cfg, int pub_or_sub, int argc, char *argv[]); static int check_format(const char *str) { int i; int len; len = strlen(str); for(i=0; iport = -1; cfg->max_inflight = 20; cfg->keepalive = 60; cfg->clean_session = true; cfg->eol = true; cfg->repeat_count = 1; cfg->repeat_delay.tv_sec = 0; cfg->repeat_delay.tv_usec = 0; if(pub_or_sub == CLIENT_RR){ cfg->protocol_version = MQTT_PROTOCOL_V5; cfg->msg_count = 1; }else{ cfg->protocol_version = MQTT_PROTOCOL_V311; } cfg->session_expiry_interval = -1; /* -1 means unset here, the user can't set it to -1. */ } void client_config_cleanup(struct mosq_config *cfg) { int i; free(cfg->id); free(cfg->id_prefix); free(cfg->host); free(cfg->file_input); free(cfg->message); free(cfg->topic); free(cfg->bind_address); free(cfg->username); free(cfg->password); free(cfg->will_topic); free(cfg->will_payload); free(cfg->format); free(cfg->response_topic); #ifdef WITH_TLS free(cfg->cafile); free(cfg->capath); free(cfg->certfile); free(cfg->keyfile); free(cfg->ciphers); free(cfg->tls_alpn); free(cfg->tls_version); free(cfg->tls_engine); free(cfg->tls_engine_kpass_sha1); free(cfg->keyform); # ifdef FINAL_WITH_TLS_PSK free(cfg->psk); free(cfg->psk_identity); # endif #endif if(cfg->topics){ for(i=0; itopic_count; i++){ free(cfg->topics[i]); } free(cfg->topics); } if(cfg->filter_outs){ for(i=0; ifilter_out_count; i++){ free(cfg->filter_outs[i]); } free(cfg->filter_outs); } if(cfg->unsub_topics){ for(i=0; iunsub_topic_count; i++){ free(cfg->unsub_topics[i]); } free(cfg->unsub_topics); } #ifdef WITH_SOCKS free(cfg->socks5_host); free(cfg->socks5_username); free(cfg->socks5_password); #endif mosquitto_property_free_all(&cfg->connect_props); mosquitto_property_free_all(&cfg->publish_props); mosquitto_property_free_all(&cfg->subscribe_props); mosquitto_property_free_all(&cfg->unsubscribe_props); mosquitto_property_free_all(&cfg->disconnect_props); mosquitto_property_free_all(&cfg->will_props); } int client_config_load(struct mosq_config *cfg, int pub_or_sub, int argc, char *argv[]) { int rc; FILE *fptr; char line[1024]; int count; char *loc = NULL; int len; char *args[3]; #ifndef WIN32 char *env; #else char env[1024]; #endif args[0] = NULL; init_config(cfg, pub_or_sub); /* Default config file */ #ifndef WIN32 env = getenv("XDG_CONFIG_HOME"); if(env){ len = strlen(env) + strlen("/mosquitto_pub") + 1; loc = malloc(len); if(!loc){ err_printf(cfg, "Error: Out of memory.\n"); return 1; } if(pub_or_sub == CLIENT_PUB){ snprintf(loc, len, "%s/mosquitto_pub", env); }else if(pub_or_sub == CLIENT_SUB){ snprintf(loc, len, "%s/mosquitto_sub", env); }else{ snprintf(loc, len, "%s/mosquitto_rr", env); } loc[len-1] = '\0'; }else{ env = getenv("HOME"); if(env){ len = strlen(env) + strlen("/.config/mosquitto_pub") + 1; loc = malloc(len); if(!loc){ err_printf(cfg, "Error: Out of memory.\n"); return 1; } if(pub_or_sub == CLIENT_PUB){ snprintf(loc, len, "%s/.config/mosquitto_pub", env); }else if(pub_or_sub == CLIENT_SUB){ snprintf(loc, len, "%s/.config/mosquitto_sub", env); }else{ snprintf(loc, len, "%s/.config/mosquitto_rr", env); } loc[len-1] = '\0'; } } #else rc = GetEnvironmentVariable("USERPROFILE", env, 1024); if(rc > 0 && rc < 1024){ len = strlen(env) + strlen("\\mosquitto_pub.conf") + 1; loc = malloc(len); if(!loc){ err_printf(cfg, "Error: Out of memory.\n"); return 1; } if(pub_or_sub == CLIENT_PUB){ snprintf(loc, len, "%s\\mosquitto_pub.conf", env); }else if(pub_or_sub == CLIENT_SUB){ snprintf(loc, len, "%s\\mosquitto_sub.conf", env); }else{ snprintf(loc, len, "%s\\mosquitto_rr.conf", env); } loc[len-1] = '\0'; } #endif if(loc){ fptr = fopen(loc, "rt"); if(fptr){ while(fgets(line, 1024, fptr)){ if(line[0] == '#') continue; /* Comments */ while(line[strlen(line)-1] == 10 || line[strlen(line)-1] == 13){ line[strlen(line)-1] = 0; } /* All offset by one "args" here, because real argc/argv has * program name as the first entry. */ args[1] = strtok(line, " "); if(args[1]){ args[2] = strtok(NULL, " "); if(args[2]){ count = 3; }else{ count = 2; } rc = client_config_line_proc(cfg, pub_or_sub, count, args); if(rc){ fclose(fptr); free(loc); return rc; } } } fclose(fptr); } free(loc); } /* Deal with real argc/argv */ rc = client_config_line_proc(cfg, pub_or_sub, argc, argv); if(rc) return rc; if(cfg->will_payload && !cfg->will_topic){ fprintf(stderr, "Error: Will payload given, but no will topic given.\n"); return 1; } if(cfg->will_retain && !cfg->will_topic){ fprintf(stderr, "Error: Will retain given, but no will topic given.\n"); return 1; } #ifdef WITH_TLS if((cfg->certfile && !cfg->keyfile) || (cfg->keyfile && !cfg->certfile)){ fprintf(stderr, "Error: Both certfile and keyfile must be provided if one of them is set.\n"); return 1; } if((cfg->keyform && !cfg->keyfile)){ fprintf(stderr, "Error: If keyform is set, keyfile must be also specified.\n"); return 1; } if((cfg->tls_engine_kpass_sha1 && (!cfg->keyform || !cfg->tls_engine))){ fprintf(stderr, "Error: when using tls-engine-kpass-sha1, both tls-engine and keyform must also be provided.\n"); return 1; } #endif #ifdef FINAL_WITH_TLS_PSK if((cfg->cafile || cfg->capath) && cfg->psk){ fprintf(stderr, "Error: Only one of --psk or --cafile/--capath may be used at once.\n"); return 1; } if(cfg->psk && !cfg->psk_identity){ fprintf(stderr, "Error: --psk-identity required if --psk used.\n"); return 1; } #endif if(cfg->protocol_version == 5){ if(cfg->clean_session == false && cfg->session_expiry_interval == -1){ /* User hasn't set session-expiry-interval, but has cleared clean * session so default to persistent session. */ cfg->session_expiry_interval = UINT32_MAX; } if(cfg->session_expiry_interval > 0){ if(cfg->session_expiry_interval == UINT32_MAX && (cfg->id_prefix || !cfg->id)){ fprintf(stderr, "Error: You must provide a client id if you are using an infinite session expiry interval.\n"); return 1; } rc = mosquitto_property_add_int32(&cfg->connect_props, MQTT_PROP_SESSION_EXPIRY_INTERVAL, cfg->session_expiry_interval); if(rc){ fprintf(stderr, "Error adding property session-expiry-interval\n"); } } }else{ if(cfg->clean_session == false && (cfg->id_prefix || !cfg->id)){ fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n"); return 1; } } if(pub_or_sub == CLIENT_SUB){ if(cfg->topic_count == 0){ fprintf(stderr, "Error: You must specify a topic to subscribe to.\n"); return 1; } } if(!cfg->host){ cfg->host = strdup("localhost"); if(!cfg->host){ err_printf(cfg, "Error: Out of memory.\n"); return 1; } } rc = mosquitto_property_check_all(CMD_CONNECT, cfg->connect_props); if(rc){ err_printf(cfg, "Error in CONNECT properties: %s\n", mosquitto_strerror(rc)); return 1; } rc = mosquitto_property_check_all(CMD_PUBLISH, cfg->publish_props); if(rc){ err_printf(cfg, "Error in PUBLISH properties: %s\n", mosquitto_strerror(rc)); return 1; } rc = mosquitto_property_check_all(CMD_SUBSCRIBE, cfg->subscribe_props); if(rc){ err_printf(cfg, "Error in SUBSCRIBE properties: %s\n", mosquitto_strerror(rc)); return 1; } rc = mosquitto_property_check_all(CMD_UNSUBSCRIBE, cfg->unsubscribe_props); if(rc){ err_printf(cfg, "Error in UNSUBSCRIBE properties: %s\n", mosquitto_strerror(rc)); return 1; } rc = mosquitto_property_check_all(CMD_DISCONNECT, cfg->disconnect_props); if(rc){ err_printf(cfg, "Error in DISCONNECT properties: %s\n", mosquitto_strerror(rc)); return 1; } rc = mosquitto_property_check_all(CMD_WILL, cfg->will_props); if(rc){ err_printf(cfg, "Error in Will properties: %s\n", mosquitto_strerror(rc)); return 1; } return MOSQ_ERR_SUCCESS; } int cfg_add_topic(struct mosq_config *cfg, int type, char *topic, const char *arg) { if(mosquitto_validate_utf8(topic, strlen(topic))){ fprintf(stderr, "Error: Malformed UTF-8 in %s argument.\n\n", arg); return 1; } if(type == CLIENT_PUB || type == CLIENT_RR){ if(mosquitto_pub_topic_check(topic) == MOSQ_ERR_INVAL){ fprintf(stderr, "Error: Invalid publish topic '%s', does it contain '+' or '#'?\n", topic); return 1; } cfg->topic = strdup(topic); }else if(type == CLIENT_RESPONSE_TOPIC){ if(mosquitto_pub_topic_check(topic) == MOSQ_ERR_INVAL){ fprintf(stderr, "Error: Invalid response topic '%s', does it contain '+' or '#'?\n", topic); return 1; } cfg->response_topic = strdup(topic); }else{ if(mosquitto_sub_topic_check(topic) == MOSQ_ERR_INVAL){ fprintf(stderr, "Error: Invalid subscription topic '%s', are all '+' and '#' wildcards correct?\n", topic); return 1; } cfg->topic_count++; cfg->topics = realloc(cfg->topics, cfg->topic_count*sizeof(char *)); if(!cfg->topics){ err_printf(cfg, "Error: Out of memory.\n"); return 1; } cfg->topics[cfg->topic_count-1] = strdup(topic); } return 0; } /* Process a tokenised single line from a file or set of real argc/argv */ int client_config_line_proc(struct mosq_config *cfg, int pub_or_sub, int argc, char *argv[]) { int i; float f; for(i=1; ibind_address = strdup(argv[i+1]); } i++; #ifdef WITH_TLS }else if(!strcmp(argv[i], "--cafile")){ if(i==argc-1){ fprintf(stderr, "Error: --cafile argument given but no file specified.\n\n"); return 1; }else{ cfg->cafile = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--capath")){ if(i==argc-1){ fprintf(stderr, "Error: --capath argument given but no directory specified.\n\n"); return 1; }else{ cfg->capath = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--cert")){ if(i==argc-1){ fprintf(stderr, "Error: --cert argument given but no file specified.\n\n"); return 1; }else{ cfg->certfile = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--ciphers")){ if(i==argc-1){ fprintf(stderr, "Error: --ciphers argument given but no ciphers specified.\n\n"); return 1; }else{ cfg->ciphers = strdup(argv[i+1]); } i++; #endif }else if(!strcmp(argv[i], "-C")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; }else{ if(i==argc-1){ fprintf(stderr, "Error: -C argument given but no count specified.\n\n"); return 1; }else{ cfg->msg_count = atoi(argv[i+1]); if(cfg->msg_count < 1){ fprintf(stderr, "Error: Invalid message count \"%d\".\n\n", cfg->msg_count); return 1; } } i++; } }else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){ cfg->clean_session = false; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){ cfg->debug = true; }else if(!strcmp(argv[i], "-D") || !strcmp(argv[i], "--property")){ i++; if(cfg_parse_property(cfg, argc, argv, &i)){ return 1; } cfg->protocol_version = MQTT_PROTOCOL_V5; }else if(!strcmp(argv[i], "-e")){ if(pub_or_sub != CLIENT_RR){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: -e argument given but no response topic specified.\n\n"); return 1; }else{ if(cfg_add_topic(cfg, CLIENT_RESPONSE_TOPIC, argv[i+1], "-e")){ return 1; } } i++; }else if(!strcmp(argv[i], "-E")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } cfg->exit_after_sub = true; }else if(!strcmp(argv[i], "-f") || !strcmp(argv[i], "--file")){ if(pub_or_sub == CLIENT_SUB){ goto unknown_option; } if(cfg->pub_mode != MSGMODE_NONE){ fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n"); return 1; }else if(i==argc-1){ fprintf(stderr, "Error: -f argument given but no file specified.\n\n"); return 1; }else{ cfg->pub_mode = MSGMODE_FILE; cfg->file_input = strdup(argv[i+1]); if(!cfg->file_input){ err_printf(cfg, "Error: Out of memory.\n"); return 1; } } i++; }else if(!strcmp(argv[i], "-F")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: -F argument given but no format specified.\n\n"); return 1; }else{ cfg->format = strdup(argv[i+1]); if(!cfg->format){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } if(check_format(cfg->format)){ return 1; } } i++; }else if(!strcmp(argv[i], "--help")){ return 2; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){ if(i==argc-1){ fprintf(stderr, "Error: -h argument given but no host specified.\n\n"); return 1; }else{ cfg->host = strdup(argv[i+1]); } i++; #ifdef WITH_TLS }else if(!strcmp(argv[i], "--insecure")){ cfg->insecure = true; #endif }else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){ if(cfg->id_prefix){ fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n"); return 1; } if(i==argc-1){ fprintf(stderr, "Error: -i argument given but no id specified.\n\n"); return 1; }else{ cfg->id = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){ if(cfg->id){ fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n"); return 1; } if(i==argc-1){ fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n"); return 1; }else{ cfg->id_prefix = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){ if(i==argc-1){ fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n"); return 1; }else{ cfg->keepalive = atoi(argv[i+1]); if(cfg->keepalive>65535){ fprintf(stderr, "Error: Invalid keepalive given: %d\n", cfg->keepalive); return 1; } } i++; #ifdef WITH_TLS }else if(!strcmp(argv[i], "--key")){ if(i==argc-1){ fprintf(stderr, "Error: --key argument given but no file specified.\n\n"); return 1; }else{ cfg->keyfile = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--keyform")){ if(i==argc-1){ fprintf(stderr, "Error: --keyform argument given but no keyform specified.\n\n"); return 1; }else{ cfg->keyform = strdup(argv[i+1]); } i++; #endif }else if(!strcmp(argv[i], "-L") || !strcmp(argv[i], "--url")){ if(i==argc-1){ fprintf(stderr, "Error: -L argument given but no URL specified.\n\n"); return 1; } else { char *url = argv[i+1]; char *topic; char *tmp; if(!strncasecmp(url, "mqtt://", 7)) { url += 7; cfg->port = 1883; } else if(!strncasecmp(url, "mqtts://", 8)) { url += 8; cfg->port = 8883; } else { fprintf(stderr, "Error: unsupported URL scheme.\n\n"); return 1; } topic = strchr(url, '/'); if(!topic){ fprintf(stderr, "Error: Invalid URL for -L argument specified - topic missing.\n"); return 1; } *topic++ = 0; if(cfg_add_topic(cfg, pub_or_sub, topic, "-L topic")) return 1; tmp = strchr(url, '@'); if(tmp) { *tmp++ = 0; char *colon = strchr(url, ':'); if(colon) { *colon = 0; cfg->password = strdup(colon + 1); } cfg->username = strdup(url); url = tmp; } cfg->host = url; tmp = strchr(url, ':'); if(tmp) { *tmp++ = 0; cfg->port = atoi(tmp); } /* Now we've removed the port, time to get the host on the heap */ cfg->host = strdup(cfg->host); } i++; }else if(!strcmp(argv[i], "-l") || !strcmp(argv[i], "--stdin-line")){ if(pub_or_sub != CLIENT_PUB){ goto unknown_option; } if(cfg->pub_mode != MSGMODE_NONE){ fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n"); return 1; }else{ cfg->pub_mode = MSGMODE_STDIN_LINE; } }else if(!strcmp(argv[i], "-m") || !strcmp(argv[i], "--message")){ if(pub_or_sub == CLIENT_SUB){ goto unknown_option; } if(cfg->pub_mode != MSGMODE_NONE){ fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n"); return 1; }else if(i==argc-1){ fprintf(stderr, "Error: -m argument given but no message specified.\n\n"); return 1; }else{ cfg->message = strdup(argv[i+1]); cfg->msglen = strlen(cfg->message); cfg->pub_mode = MSGMODE_CMD; } i++; }else if(!strcmp(argv[i], "-M")){ if(i==argc-1){ fprintf(stderr, "Error: -M argument given but max_inflight not specified.\n\n"); return 1; }else{ cfg->max_inflight = atoi(argv[i+1]); } i++; }else if(!strcmp(argv[i], "-n") || !strcmp(argv[i], "--null-message")){ if(pub_or_sub == CLIENT_SUB){ goto unknown_option; } if(cfg->pub_mode != MSGMODE_NONE){ fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n"); return 1; }else{ cfg->pub_mode = MSGMODE_NULL; } }else if(!strcmp(argv[i], "-N")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } cfg->eol = false; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i==argc-1){ fprintf(stderr, "Error: -p argument given but no port specified.\n\n"); return 1; }else{ cfg->port = atoi(argv[i+1]); if(cfg->port<1 || cfg->port>65535){ fprintf(stderr, "Error: Invalid port given: %d\n", cfg->port); return 1; } } i++; }else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){ if(i==argc-1){ fprintf(stderr, "Error: -P argument given but no password specified.\n\n"); return 1; }else{ cfg->password = strdup(argv[i+1]); } i++; #ifdef WITH_SOCKS }else if(!strcmp(argv[i], "--proxy")){ if(i==argc-1){ fprintf(stderr, "Error: --proxy argument given but no proxy url specified.\n\n"); return 1; }else{ if(mosquitto__parse_socks_url(cfg, argv[i+1])){ return 1; } i++; } #endif #ifdef FINAL_WITH_TLS_PSK }else if(!strcmp(argv[i], "--psk")){ if(i==argc-1){ fprintf(stderr, "Error: --psk argument given but no key specified.\n\n"); return 1; }else{ cfg->psk = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--psk-identity")){ if(i==argc-1){ fprintf(stderr, "Error: --psk-identity argument given but no identity specified.\n\n"); return 1; }else{ cfg->psk_identity = strdup(argv[i+1]); } i++; #endif }else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){ if(i==argc-1){ fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n"); return 1; }else{ cfg->qos = atoi(argv[i+1]); if(cfg->qos<0 || cfg->qos>2){ fprintf(stderr, "Error: Invalid QoS given: %d\n", cfg->qos); return 1; } } i++; }else if(!strcmp(argv[i], "--quiet")){ cfg->quiet = true; }else if(!strcmp(argv[i], "-r") || !strcmp(argv[i], "--retain")){ if(pub_or_sub != CLIENT_PUB){ goto unknown_option; } cfg->retain = 1; }else if(!strcmp(argv[i], "-R")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } cfg->no_retain = true; cfg->sub_opts |= MQTT_SUB_OPT_SEND_RETAIN_NEVER; }else if(!strcmp(argv[i], "--remove-retained")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } cfg->remove_retained = true; }else if(!strcmp(argv[i], "--repeat")){ if(pub_or_sub != CLIENT_PUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: --repeat argument given but no count specified.\n\n"); return 1; }else{ cfg->repeat_count = atoi(argv[i+1]); if(cfg->repeat_count < 1){ fprintf(stderr, "Error: --repeat argument must be >0.\n\n"); return 1; } } i++; }else if(!strcmp(argv[i], "--repeat-delay")){ if(pub_or_sub != CLIENT_PUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: --repeat-delay argument given but no time specified.\n\n"); return 1; }else{ f = atof(argv[i+1]); if(f < 0.0f){ fprintf(stderr, "Error: --repeat-delay argument must be >=0.0.\n\n"); return 1; } f *= 1.0e6; cfg->repeat_delay.tv_sec = (int)f/1e6; cfg->repeat_delay.tv_usec = (int)f%1000000; } i++; }else if(!strcmp(argv[i], "--retain-as-published")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } cfg->sub_opts |= MQTT_SUB_OPT_RETAIN_AS_PUBLISHED; }else if(!strcmp(argv[i], "--retained-only")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } cfg->retained_only = true; }else if(!strcmp(argv[i], "-s") || !strcmp(argv[i], "--stdin-file")){ if(pub_or_sub == CLIENT_SUB){ goto unknown_option; } if(cfg->pub_mode != MSGMODE_NONE){ fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n"); return 1; }else{ cfg->pub_mode = MSGMODE_STDIN_FILE; } #ifdef WITH_SRV }else if(!strcmp(argv[i], "-S")){ cfg->use_srv = true; #endif }else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){ if(i==argc-1){ fprintf(stderr, "Error: -t argument given but no topic specified.\n\n"); return 1; }else{ if(cfg_add_topic(cfg, pub_or_sub, argv[i + 1], "-t")) return 1; i++; } }else if(!strcmp(argv[i], "-T") || !strcmp(argv[i], "--filter-out")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: -T argument given but no topic filter specified.\n\n"); return 1; }else{ if(mosquitto_validate_utf8(argv[i+1], strlen(argv[i+1]))){ fprintf(stderr, "Error: Malformed UTF-8 in -T argument.\n\n"); return 1; } if(mosquitto_sub_topic_check(argv[i+1]) == MOSQ_ERR_INVAL){ fprintf(stderr, "Error: Invalid filter topic '%s', are all '+' and '#' wildcards correct?\n", argv[i+1]); return 1; } cfg->filter_out_count++; cfg->filter_outs = realloc(cfg->filter_outs, cfg->filter_out_count*sizeof(char *)); if(!cfg->filter_outs){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } cfg->filter_outs[cfg->filter_out_count-1] = strdup(argv[i+1]); } i++; #ifdef WITH_TLS }else if(!strcmp(argv[i], "--tls-alpn")){ if(i==argc-1){ fprintf(stderr, "Error: --tls-alpn argument given but no protocol specified.\n\n"); return 1; }else{ cfg->tls_alpn = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--tls-engine")){ if(i==argc-1){ fprintf(stderr, "Error: --tls-engine argument given but no engine_id specified.\n\n"); return 1; }else{ cfg->tls_engine = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--tls-engine-kpass-sha1")){ if(i==argc-1){ fprintf(stderr, "Error: --tls-engine-kpass-sha1 argument given but no kpass sha1 specified.\n\n"); return 1; }else{ cfg->tls_engine_kpass_sha1 = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "--tls-version")){ if(i==argc-1){ fprintf(stderr, "Error: --tls-version argument given but no version specified.\n\n"); return 1; }else{ cfg->tls_version = strdup(argv[i+1]); } i++; #endif }else if(!strcmp(argv[i], "-U") || !strcmp(argv[i], "--unsubscribe")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: -U argument given but no unsubscribe topic specified.\n\n"); return 1; }else{ if(mosquitto_validate_utf8(argv[i+1], strlen(argv[i+1]))){ fprintf(stderr, "Error: Malformed UTF-8 in -U argument.\n\n"); return 1; } if(mosquitto_sub_topic_check(argv[i+1]) == MOSQ_ERR_INVAL){ fprintf(stderr, "Error: Invalid unsubscribe topic '%s', are all '+' and '#' wildcards correct?\n", argv[i+1]); return 1; } cfg->unsub_topic_count++; cfg->unsub_topics = realloc(cfg->unsub_topics, cfg->unsub_topic_count*sizeof(char *)); if(!cfg->unsub_topics){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } cfg->unsub_topics[cfg->unsub_topic_count-1] = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){ if(i==argc-1){ fprintf(stderr, "Error: -u argument given but no username specified.\n\n"); return 1; }else{ cfg->username = strdup(argv[i+1]); } i++; }else if(!strcmp(argv[i], "-V") || !strcmp(argv[i], "--protocol-version")){ if(i==argc-1){ fprintf(stderr, "Error: --protocol-version argument given but no version specified.\n\n"); return 1; }else{ if(!strcmp(argv[i+1], "mqttv31") || !strcmp(argv[i+1], "31")){ cfg->protocol_version = MQTT_PROTOCOL_V31; }else if(!strcmp(argv[i+1], "mqttv311") || !strcmp(argv[i+1], "311")){ cfg->protocol_version = MQTT_PROTOCOL_V311; }else if(!strcmp(argv[i+1], "mqttv5") || !strcmp(argv[i+1], "5")){ cfg->protocol_version = MQTT_PROTOCOL_V5; }else{ fprintf(stderr, "Error: Invalid protocol version argument given.\n\n"); return 1; } i++; } }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } cfg->verbose = 1; }else if(!strcmp(argv[i], "-W")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; }else{ if(i==argc-1){ fprintf(stderr, "Error: -W argument given but no timeout specified.\n\n"); return 1; }else{ cfg->timeout = atoi(argv[i+1]); if(cfg->timeout < 1){ fprintf(stderr, "Error: Invalid timeout \"%d\".\n\n", cfg->msg_count); return 1; } } i++; } }else if(!strcmp(argv[i], "--will-payload")){ if(i==argc-1){ fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n"); return 1; }else{ cfg->will_payload = strdup(argv[i+1]); cfg->will_payloadlen = strlen(cfg->will_payload); } i++; }else if(!strcmp(argv[i], "--will-qos")){ if(i==argc-1){ fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n"); return 1; }else{ cfg->will_qos = atoi(argv[i+1]); if(cfg->will_qos < 0 || cfg->will_qos > 2){ fprintf(stderr, "Error: Invalid will QoS %d.\n\n", cfg->will_qos); return 1; } } i++; }else if(!strcmp(argv[i], "--will-retain")){ cfg->will_retain = true; }else if(!strcmp(argv[i], "--will-topic")){ if(i==argc-1){ fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n"); return 1; }else{ if(mosquitto_validate_utf8(argv[i+1], strlen(argv[i+1]))){ fprintf(stderr, "Error: Malformed UTF-8 in --will-topic argument.\n\n"); return 1; } if(mosquitto_pub_topic_check(argv[i+1]) == MOSQ_ERR_INVAL){ fprintf(stderr, "Error: Invalid will topic '%s', does it contain '+' or '#'?\n", argv[i+1]); return 1; } cfg->will_topic = strdup(argv[i+1]); } i++; }else{ goto unknown_option; } } return MOSQ_ERR_SUCCESS; unknown_option: fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); return 1; } int client_opts_set(struct mosquitto *mosq, struct mosq_config *cfg) { #if defined(WITH_TLS) || defined(WITH_SOCKS) int rc; #endif mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, cfg->protocol_version); if(cfg->will_topic && mosquitto_will_set_v5(mosq, cfg->will_topic, cfg->will_payloadlen, cfg->will_payload, cfg->will_qos, cfg->will_retain, cfg->will_props)){ err_printf(cfg, "Error: Problem setting will.\n"); mosquitto_lib_cleanup(); return 1; } cfg->will_props = NULL; if((cfg->username || cfg->password) && mosquitto_username_pw_set(mosq, cfg->username, cfg->password)){ err_printf(cfg, "Error: Problem setting username and/or password.\n"); mosquitto_lib_cleanup(); return 1; } #ifdef WITH_TLS if(cfg->cafile || cfg->capath){ rc = mosquitto_tls_set(mosq, cfg->cafile, cfg->capath, cfg->certfile, cfg->keyfile, NULL); if(rc){ if(rc == MOSQ_ERR_INVAL){ err_printf(cfg, "Error: Problem setting TLS options: File not found.\n"); }else{ err_printf(cfg, "Error: Problem setting TLS options: %s.\n", mosquitto_strerror(rc)); } mosquitto_lib_cleanup(); return 1; } } if(cfg->insecure && mosquitto_tls_insecure_set(mosq, true)){ err_printf(cfg, "Error: Problem setting TLS insecure option.\n"); mosquitto_lib_cleanup(); return 1; } if(cfg->tls_engine && mosquitto_string_option(mosq, MOSQ_OPT_TLS_ENGINE, cfg->tls_engine)){ err_printf(cfg, "Error: Problem setting TLS engine, is %s a valid engine?\n", cfg->tls_engine); mosquitto_lib_cleanup(); return 1; } if(cfg->keyform && mosquitto_string_option(mosq, MOSQ_OPT_TLS_KEYFORM, cfg->keyform)){ err_printf(cfg, "Error: Problem setting key form, it must be one of 'pem' or 'engine'.\n"); mosquitto_lib_cleanup(); return 1; } if(cfg->tls_engine_kpass_sha1 && mosquitto_string_option(mosq, MOSQ_OPT_TLS_ENGINE_KPASS_SHA1, cfg->tls_engine_kpass_sha1)){ err_printf(cfg, "Error: Problem setting TLS engine key pass sha, is it a 40 character hex string?\n"); mosquitto_lib_cleanup(); return 1; } if(cfg->tls_alpn && mosquitto_string_option(mosq, MOSQ_OPT_TLS_ALPN, cfg->tls_alpn)){ err_printf(cfg, "Error: Problem setting TLS ALPN protocol.\n"); mosquitto_lib_cleanup(); return 1; } # ifdef FINAL_WITH_TLS_PSK if(cfg->psk && mosquitto_tls_psk_set(mosq, cfg->psk, cfg->psk_identity, NULL)){ err_printf(cfg, "Error: Problem setting TLS-PSK options.\n"); mosquitto_lib_cleanup(); return 1; } # endif if((cfg->tls_version || cfg->ciphers) && mosquitto_tls_opts_set(mosq, 1, cfg->tls_version, cfg->ciphers)){ err_printf(cfg, "Error: Problem setting TLS options, check the options are valid.\n"); mosquitto_lib_cleanup(); return 1; } #endif mosquitto_max_inflight_messages_set(mosq, cfg->max_inflight); #ifdef WITH_SOCKS if(cfg->socks5_host){ rc = mosquitto_socks5_set(mosq, cfg->socks5_host, cfg->socks5_port, cfg->socks5_username, cfg->socks5_password); if(rc){ mosquitto_lib_cleanup(); return rc; } } #endif return MOSQ_ERR_SUCCESS; } int client_id_generate(struct mosq_config *cfg) { if(cfg->id_prefix){ cfg->id = malloc(strlen(cfg->id_prefix)+10); if(!cfg->id){ err_printf(cfg, "Error: Out of memory.\n"); mosquitto_lib_cleanup(); return 1; } snprintf(cfg->id, strlen(cfg->id_prefix)+10, "%s%d", cfg->id_prefix, getpid()); } return MOSQ_ERR_SUCCESS; } int client_connect(struct mosquitto *mosq, struct mosq_config *cfg) { #ifndef WIN32 char *err; #else char err[1024]; #endif int rc; int port; if(cfg->port < 0){ #ifdef WITH_TLS if(cfg->cafile || cfg->capath # ifdef FINAL_WITH_TLS_PSK || cfg->psk # endif ){ port = 8883; }else #endif { port = 1883; } }else{ port = cfg->port; } #ifdef WITH_SRV if(cfg->use_srv){ rc = mosquitto_connect_srv(mosq, cfg->host, cfg->keepalive, cfg->bind_address); }else{ rc = mosquitto_connect_bind_v5(mosq, cfg->host, port, cfg->keepalive, cfg->bind_address, cfg->connect_props); } #else rc = mosquitto_connect_bind_v5(mosq, cfg->host, port, cfg->keepalive, cfg->bind_address, cfg->connect_props); #endif if(rc>0){ if(rc == MOSQ_ERR_ERRNO){ #ifndef WIN32 err = strerror(errno); #else FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, 1024, NULL); #endif err_printf(cfg, "Error: %s\n", err); }else{ err_printf(cfg, "Unable to connect (%s).\n", mosquitto_strerror(rc)); } mosquitto_lib_cleanup(); return rc; } return MOSQ_ERR_SUCCESS; } #ifdef WITH_SOCKS /* Convert %25 -> %, %3a, %3A -> :, %40 -> @ */ static int mosquitto__urldecode(char *str) { int i, j; int len; if(!str) return 0; if(!strchr(str, '%')) return 0; len = strlen(str); for(i=0; i= len){ return 1; } if(str[i+1] == '2' && str[i+2] == '5'){ str[i] = '%'; len -= 2; for(j=i+1; j start){ len = i-start; if(host){ /* Have already seen a @ , so this must be of form * socks5h://username[:password]@host:port */ port = malloc(len + 1); if(!port){ err_printf(cfg, "Error: Out of memory.\n"); goto cleanup; } memcpy(port, &(str[start]), len); port[len] = '\0'; }else if(username_or_host){ /* Haven't seen a @ before, so must be of form * socks5h://host:port */ host = username_or_host; username_or_host = NULL; port = malloc(len + 1); if(!port){ err_printf(cfg, "Error: Out of memory.\n"); goto cleanup; } memcpy(port, &(str[start]), len); port[len] = '\0'; }else{ host = malloc(len + 1); if(!host){ err_printf(cfg, "Error: Out of memory.\n"); goto cleanup; } memcpy(host, &(str[start]), len); host[len] = '\0'; } } if(!host){ err_printf(cfg, "Error: Invalid proxy.\n"); goto cleanup; } if(mosquitto__urldecode(username)){ goto cleanup; } if(mosquitto__urldecode(password)){ goto cleanup; } if(port){ port_int = atoi(port); if(port_int < 1 || port_int > 65535){ err_printf(cfg, "Error: Invalid proxy port %d\n", port_int); goto cleanup; } free(port); }else{ port_int = 1080; } cfg->socks5_username = username; cfg->socks5_password = password; cfg->socks5_host = host; cfg->socks5_port = port_int; return 0; cleanup: free(username_or_host); free(username); free(password); free(host); free(port); return 1; } #endif void err_printf(const struct mosq_config *cfg, const char *fmt, ...) { va_list va; if(cfg->quiet) return; va_start(va, fmt); vfprintf(stderr, fmt, va); va_end(va); } mosquitto-1.6.9/client/client_shared.h0000664000175000017500000000625713626052637017072 0ustar rogerroger/* Copyright (c) 2014-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef CLIENT_CONFIG_H #define CLIENT_CONFIG_H #include #ifdef WIN32 # include #else # include #endif /* pub_client.c modes */ #define MSGMODE_NONE 0 #define MSGMODE_CMD 1 #define MSGMODE_STDIN_LINE 2 #define MSGMODE_STDIN_FILE 3 #define MSGMODE_FILE 4 #define MSGMODE_NULL 5 #define CLIENT_PUB 1 #define CLIENT_SUB 2 #define CLIENT_RR 3 #define CLIENT_RESPONSE_TOPIC 4 struct mosq_config { char *id; char *id_prefix; int protocol_version; int keepalive; char *host; int port; int qos; bool retain; int pub_mode; /* pub, rr */ char *file_input; /* pub, rr */ char *message; /* pub, rr */ long msglen; /* pub, rr */ char *topic; /* pub, rr */ char *bind_address; int repeat_count; /* pub */ struct timeval repeat_delay; /* pub */ #ifdef WITH_SRV bool use_srv; #endif bool debug; bool quiet; unsigned int max_inflight; char *username; char *password; char *will_topic; char *will_payload; long will_payloadlen; int will_qos; bool will_retain; #ifdef WITH_TLS char *cafile; char *capath; char *certfile; char *keyfile; char *ciphers; bool insecure; char *tls_alpn; char *tls_version; char *tls_engine; char *tls_engine_kpass_sha1; char *keyform; # ifdef FINAL_WITH_TLS_PSK char *psk; char *psk_identity; # endif #endif bool clean_session; char **topics; /* sub */ int topic_count; /* sub */ bool exit_after_sub; /* sub */ bool no_retain; /* sub */ bool retained_only; /* sub */ bool remove_retained; /* sub */ char **filter_outs; /* sub */ int filter_out_count; /* sub */ char **unsub_topics; /* sub */ int unsub_topic_count; /* sub */ bool verbose; /* sub */ bool eol; /* sub */ int msg_count; /* sub */ char *format; /* sub */ int timeout; /* sub */ int sub_opts; /* sub */ long session_expiry_interval; #ifdef WITH_SOCKS char *socks5_host; int socks5_port; char *socks5_username; char *socks5_password; #endif mosquitto_property *connect_props; mosquitto_property *publish_props; mosquitto_property *subscribe_props; mosquitto_property *unsubscribe_props; mosquitto_property *disconnect_props; mosquitto_property *will_props; bool have_topic_alias; /* pub */ char *response_topic; /* rr */ }; int client_config_load(struct mosq_config *config, int pub_or_sub, int argc, char *argv[]); void client_config_cleanup(struct mosq_config *cfg); int client_opts_set(struct mosquitto *mosq, struct mosq_config *cfg); int client_id_generate(struct mosq_config *cfg); int client_connect(struct mosquitto *mosq, struct mosq_config *cfg); int cfg_parse_property(struct mosq_config *cfg, int argc, char *argv[], int *idx); void err_printf(const struct mosq_config *cfg, const char *fmt, ...); #endif mosquitto-1.6.9/client/sub_test_properties0000775000175000017500000000202113626052637020130 0ustar rogerrogerLD_LIBRARY_PATH=../lib ./mosquitto_sub \ \ -V mqttv5 -C 10 -t \$SYS/# -v -U unsub --will-topic will --will-payload '{"key":"value"}' \ \ -D connect authentication-data password \ -D connect authentication-method something \ -D connect maximum-packet-size 0191 \ -D connect receive-maximum 1000 \ -D connect request-problem-information 1 \ -D connect request-response-information 1 \ -D connect session-expiry-interval 39 \ -D connect topic-alias-maximum 123 \ -D connect user-property connect up \ \ -D will content-type application/json \ -D will correlation-data some-data \ -D will message-expiry-interval 59 \ -D will payload-format-indicator 1 \ -D will response-topic /dev/null \ -D will user-property will up \ -D will will-delay-interval 100 \ \ -D subscribe subscription-identifier 1 \ -D subscribe user-property subscribe up \ \ -D unsubscribe user-property unsubscribe up \ \ -D disconnect reason-string "reason" \ -D disconnect session-expiry-interval 40 \ -D disconnect user-property disconnect up mosquitto-1.6.9/client/client_props.c0000664000175000017500000001171013626052637016750 0ustar rogerroger/* Copyright (c) 2018-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #ifndef WIN32 #include #include #else #include #include #define snprintf sprintf_s #define strncasecmp _strnicmp #endif #include "mosquitto.h" #include "mqtt_protocol.h" #include "client_shared.h" enum prop_type { PROP_TYPE_BYTE, PROP_TYPE_INT16, PROP_TYPE_INT32, PROP_TYPE_BINARY, PROP_TYPE_STRING, PROP_TYPE_STRING_PAIR }; /* This parses property inputs. It should work for any command type, but is limited at the moment. * * Format: * * command property value * command property key value * * Example: * * publish message-expiry-interval 32 * connect user-property key value */ int cfg_parse_property(struct mosq_config *cfg, int argc, char *argv[], int *idx) { char *cmdname = NULL, *propname = NULL; char *key = NULL, *value = NULL; int cmd, identifier, type; mosquitto_property **proplist; int rc; /* idx now points to "command" */ if((*idx)+2 > argc-1){ /* Not enough args */ fprintf(stderr, "Error: --property argument given but not enough arguments specified.\n\n"); return MOSQ_ERR_INVAL; } cmdname = argv[*idx]; if(mosquitto_string_to_command(cmdname, &cmd)){ fprintf(stderr, "Error: Invalid command given in --property argument.\n\n"); return MOSQ_ERR_INVAL; } propname = argv[(*idx)+1]; if(mosquitto_string_to_property_info(propname, &identifier, &type)){ fprintf(stderr, "Error: Invalid property name given in --property argument.\n\n"); return MOSQ_ERR_INVAL; } if(mosquitto_property_check_command(cmd, identifier)){ fprintf(stderr, "Error: %s property not allow for %s in --property argument.\n\n", propname, cmdname); return MOSQ_ERR_INVAL; } if(identifier == MQTT_PROP_USER_PROPERTY){ if((*idx)+3 > argc-1){ /* Not enough args */ fprintf(stderr, "Error: --property argument given but not enough arguments specified.\n\n"); return MOSQ_ERR_INVAL; } key = argv[(*idx)+2]; value = argv[(*idx)+3]; (*idx) += 3; }else{ value = argv[(*idx)+2]; (*idx) += 2; } switch(cmd){ case CMD_CONNECT: proplist = &cfg->connect_props; break; case CMD_PUBLISH: if(identifier == MQTT_PROP_TOPIC_ALIAS){ cfg->have_topic_alias = true; } if(identifier == MQTT_PROP_SUBSCRIPTION_IDENTIFIER){ fprintf(stderr, "Error: %s property not supported for %s in --property argument.\n\n", propname, cmdname); return MOSQ_ERR_INVAL; } proplist = &cfg->publish_props; break; case CMD_SUBSCRIBE: if(identifier != MQTT_PROP_SUBSCRIPTION_IDENTIFIER && identifier != MQTT_PROP_USER_PROPERTY){ fprintf(stderr, "Error: %s property not supported for %s in --property argument.\n\n", propname, cmdname); return MOSQ_ERR_NOT_SUPPORTED; } proplist = &cfg->subscribe_props; break; case CMD_UNSUBSCRIBE: proplist = &cfg->unsubscribe_props; break; case CMD_DISCONNECT: proplist = &cfg->disconnect_props; break; case CMD_AUTH: fprintf(stderr, "Error: %s property not supported for %s in --property argument.\n\n", propname, cmdname); return MOSQ_ERR_NOT_SUPPORTED; case CMD_WILL: proplist = &cfg->will_props; break; case CMD_PUBACK: case CMD_PUBREC: case CMD_PUBREL: case CMD_PUBCOMP: case CMD_SUBACK: case CMD_UNSUBACK: fprintf(stderr, "Error: %s property not supported for %s in --property argument.\n\n", propname, cmdname); return MOSQ_ERR_NOT_SUPPORTED; default: return MOSQ_ERR_INVAL; } switch(type){ case MQTT_PROP_TYPE_BYTE: rc = mosquitto_property_add_byte(proplist, identifier, atoi(value)); break; case MQTT_PROP_TYPE_INT16: rc = mosquitto_property_add_int16(proplist, identifier, atoi(value)); break; case MQTT_PROP_TYPE_INT32: rc = mosquitto_property_add_int32(proplist, identifier, atoi(value)); break; case MQTT_PROP_TYPE_VARINT: rc = mosquitto_property_add_varint(proplist, identifier, atoi(value)); break; case MQTT_PROP_TYPE_BINARY: rc = mosquitto_property_add_binary(proplist, identifier, value, strlen(value)); break; case MQTT_PROP_TYPE_STRING: rc = mosquitto_property_add_string(proplist, identifier, value); break; case MQTT_PROP_TYPE_STRING_PAIR: rc = mosquitto_property_add_string_pair(proplist, identifier, key, value); break; default: return MOSQ_ERR_INVAL; } if(rc){ fprintf(stderr, "Error adding property %s %d\n", propname, type); return rc; } return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/client/rr_client.c0000664000175000017500000003035013626052637016231 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #ifndef WIN32 #include #include #else #include #include #define snprintf sprintf_s #endif #include #include #include "client_shared.h" #include "pub_shared.h" enum rr__state { rr_s_new, rr_s_connected, rr_s_subscribed, rr_s_ready_to_publish, rr_s_wait_for_response, rr_s_disconnect }; static enum rr__state client_state = rr_s_new; extern struct mosq_config cfg; bool process_messages = true; int msg_count = 0; struct mosquitto *mosq = NULL; #ifndef WIN32 void my_signal_handler(int signum) { if(signum == SIGALRM){ process_messages = false; mosquitto_disconnect_v5(mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); } } #endif void print_message(struct mosq_config *cfg, const struct mosquitto_message *message); int my_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, void *payload, int qos, bool retain) { return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, cfg.publish_props); } void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, const mosquitto_property *properties) { print_message(&cfg, message); switch(cfg.pub_mode){ case MSGMODE_CMD: case MSGMODE_FILE: case MSGMODE_STDIN_FILE: case MSGMODE_NULL: client_state = rr_s_disconnect; break; case MSGMODE_STDIN_LINE: client_state = rr_s_ready_to_publish; break; } /* FIXME - check all below if(process_messages == false) return; if(cfg.retained_only && !message->retain && process_messages){ process_messages = false; mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); return; } if(message->retain && cfg.no_retain) return; if(cfg.filter_outs){ for(i=0; itopic, &res); if(res) return; } } //print_message(&cfg, message); if(cfg.msg_count>0){ msg_count++; if(cfg.msg_count == msg_count){ process_messages = false; mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } } */ } void my_connect_callback(struct mosquitto *mosq, void *obj, int result, int flags, const mosquitto_property *properties) { if(!result){ client_state = rr_s_connected; mosquitto_subscribe_v5(mosq, NULL, cfg.response_topic, cfg.qos, 0, cfg.subscribe_props); }else{ client_state = rr_s_disconnect; if(result){ if(result == MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION){ err_printf(&cfg, "Connection error: %s. mosquitto_rr only supports connecting to an MQTT v5 broker\n", mosquitto_reason_string(result)); }else{ err_printf(&cfg, "Connection error: %s\n", mosquitto_reason_string(result)); } } mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } } void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { if(granted_qos[0] < 128){ client_state = rr_s_ready_to_publish; }else{ client_state = rr_s_disconnect; err_printf(&cfg, "%s\n", mosquitto_reason_string(granted_qos[0])); mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } } void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { client_state = rr_s_wait_for_response; } void print_usage(void) { int major, minor, revision; mosquitto_lib_version(&major, &minor, &revision); printf("mosquitto_rr is an mqtt client that can be used to publish a request message and wait for a response.\n"); printf(" Defaults to MQTT v5, where the Request-Response feature will be used, but v3.1.1 can also be used\n"); printf(" with v3.1.1 brokers.\n"); printf("mosquitto_rr version %s running on libmosquitto %d.%d.%d.\n\n", VERSION, major, minor, revision); printf("Usage: mosquitto_rr {[-h host] [-p port] [-u username] [-P password] -t topic | -L URL} -e response-topic\n"); printf(" [-c] [-k keepalive] [-q qos] [-R]\n"); printf(" [-F format]\n"); #ifndef WIN32 printf(" [-W timeout_secs]\n"); #endif #ifdef WITH_SRV printf(" [-A bind_address] [-S]\n"); #else printf(" [-A bind_address]\n"); #endif printf(" [-i id] [-I id_prefix]\n"); printf(" [-d] [-N] [--quiet] [-v]\n"); printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n"); #ifdef WITH_TLS printf(" [{--cafile file | --capath dir} [--cert file] [--key file]\n"); printf(" [--ciphers ciphers] [--insecure]\n"); printf(" [--tls-alpn protocol]\n"); printf(" [--tls-engine engine] [--keyform keyform] [--tls-engine-kpass-sha1]]\n"); #ifdef FINAL_WITH_TLS_PSK printf(" [--psk hex-key --psk-identity identity [--ciphers ciphers]]\n"); #endif #endif #ifdef WITH_SOCKS printf(" [--proxy socks-url]\n"); #endif printf(" [-D command identifier value]\n"); printf(" mosquitto_rr --help\n\n"); printf(" -A : bind the outgoing socket to this host/ip address. Use to control which interface\n"); printf(" the client communicates over.\n"); printf(" -c : disable 'clean session' (store subscription and pending messages when client disconnects).\n"); printf(" -d : enable debug messages.\n"); printf(" -D : Define MQTT v5 properties. See the documentation for more details.\n"); printf(" -F : output format.\n"); printf(" -h : mqtt host to connect to. Defaults to localhost.\n"); printf(" -i : id to use for this client. Defaults to mosquitto_rr_ appended with the process id.\n"); printf(" -k : keep alive in seconds for this client. Defaults to 60.\n"); printf(" -L : specify user, password, hostname, port and topic as a URL in the form:\n"); printf(" mqtt(s)://[username[:password]@]host[:port]/topic\n"); printf(" -N : do not add an end of line character when printing the payload.\n"); printf(" -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.\n"); printf(" -P : provide a password\n"); printf(" -q : quality of service level to use for communications. Defaults to 0.\n"); printf(" -R : do not print stale messages (those with retain set).\n"); #ifdef WITH_SRV printf(" -S : use SRV lookups to determine which host to connect to.\n"); #endif printf(" -t : mqtt response topic to subscribe to. May be repeated multiple times.\n"); printf(" -u : provide a username\n"); printf(" -v : print received messages verbosely.\n"); printf(" -V : specify the version of the MQTT protocol to use when connecting.\n"); printf(" Defaults to 5.\n"); #ifndef WIN32 printf(" -W : Specifies a timeout in seconds how long to wait for a response.\n"); #endif printf(" --help : display this message.\n"); printf(" --quiet : don't print error messages.\n"); printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n"); printf(" unexpected disconnection. If not given and will-topic is set, a zero\n"); printf(" length message will be sent.\n"); printf(" --will-qos : QoS level for the client Will.\n"); printf(" --will-retain : if given, make the client Will retained.\n"); printf(" --will-topic : the topic on which to publish the client Will.\n"); #ifdef WITH_TLS printf(" --cafile : path to a file containing trusted CA certificates to enable encrypted\n"); printf(" certificate based communication.\n"); printf(" --capath : path to a directory containing trusted CA certificates to enable encrypted\n"); printf(" communication.\n"); printf(" --cert : client certificate for authentication, if required by server.\n"); printf(" --key : client private key for authentication, if required by server.\n"); printf(" --ciphers : openssl compatible list of TLS ciphers to support.\n"); printf(" --tls-version : TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1.\n"); printf(" Defaults to tlsv1.2 if available.\n"); printf(" --insecure : do not check that the server certificate hostname matches the remote\n"); printf(" hostname. Using this option means that you cannot be sure that the\n"); printf(" remote host is the server you wish to connect to and so is insecure.\n"); printf(" Do not use this option in a production environment.\n"); #ifdef WITH_TLS_PSK printf(" --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.\n"); printf(" --psk-identity : client identity string for TLS-PSK mode.\n"); #endif #endif #ifdef WITH_SOCKS printf(" --proxy : SOCKS5 proxy URL of the form:\n"); printf(" socks5h://[username[:password]@]hostname[:port]\n"); printf(" Only \"none\" and \"username\" authentication is supported.\n"); #endif printf("\nSee https://mosquitto.org/ for more information.\n\n"); } int main(int argc, char *argv[]) { int rc; #ifndef WIN32 struct sigaction sigact; #endif mosquitto_lib_init(); rc = client_config_load(&cfg, CLIENT_RR, argc, argv); if(rc){ if(rc == 2){ /* --help */ print_usage(); }else{ fprintf(stderr, "\nUse 'mosquitto_rr --help' to see usage.\n"); } goto cleanup; } if(!cfg.topic || cfg.pub_mode == MSGMODE_NONE || !cfg.response_topic){ fprintf(stderr, "Error: All of topic, message, and response topic must be supplied.\n"); fprintf(stderr, "\nUse 'mosquitto_rr --help' to see usage.\n"); goto cleanup; } rc = mosquitto_property_add_string(&cfg.publish_props, MQTT_PROP_RESPONSE_TOPIC, cfg.response_topic); if(rc){ fprintf(stderr, "Error adding property RESPONSE_TOPIC.\n"); goto cleanup; } rc = mosquitto_property_check_all(CMD_PUBLISH, cfg.publish_props); if(rc){ err_printf(&cfg, "Error in PUBLISH properties: Duplicate response topic.\n"); goto cleanup; } if(client_id_generate(&cfg)){ goto cleanup; } mosq = mosquitto_new(cfg.id, cfg.clean_session, &cfg); if(!mosq){ switch(errno){ case ENOMEM: err_printf(&cfg, "Error: Out of memory.\n"); break; case EINVAL: err_printf(&cfg, "Error: Invalid id and/or clean_session.\n"); break; } goto cleanup; } if(client_opts_set(mosq, &cfg)){ goto cleanup; } if(cfg.debug){ mosquitto_log_callback_set(mosq, my_log_callback); } mosquitto_connect_v5_callback_set(mosq, my_connect_callback); mosquitto_subscribe_callback_set(mosq, my_subscribe_callback); mosquitto_message_v5_callback_set(mosq, my_message_callback); rc = client_connect(mosq, &cfg); if(rc){ goto cleanup; } #ifndef WIN32 sigact.sa_handler = my_signal_handler; sigemptyset(&sigact.sa_mask); sigact.sa_flags = 0; if(sigaction(SIGALRM, &sigact, NULL) == -1){ perror("sigaction"); goto cleanup; } if(cfg.timeout){ alarm(cfg.timeout); } #endif do{ rc = mosquitto_loop(mosq, -1, 1); if(client_state == rr_s_ready_to_publish){ client_state = rr_s_wait_for_response; switch(cfg.pub_mode){ case MSGMODE_CMD: case MSGMODE_FILE: case MSGMODE_STDIN_FILE: rc = my_publish(mosq, &mid_sent, cfg.topic, cfg.msglen, cfg.message, cfg.qos, cfg.retain); break; case MSGMODE_NULL: rc = my_publish(mosq, &mid_sent, cfg.topic, 0, NULL, cfg.qos, cfg.retain); break; case MSGMODE_STDIN_LINE: /* FIXME */ break; } } }while(rc == MOSQ_ERR_SUCCESS && client_state != rr_s_disconnect); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){ rc = 0; } client_config_cleanup(&cfg); if(rc){ err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc)); } return rc; cleanup: mosquitto_lib_cleanup(); client_config_cleanup(&cfg); return 1; } mosquitto-1.6.9/client/pub_client.c0000664000175000017500000004245513626052637016405 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #ifndef WIN32 #include #include #else #include #include #define snprintf sprintf_s #endif #include #include #include "client_shared.h" #include "pub_shared.h" /* Global variables for use in callbacks. See sub_client.c for an example of * using a struct to hold variables for use in callbacks. */ static bool first_publish = true; static int last_mid = -1; static int last_mid_sent = -1; static char *line_buf = NULL; static int line_buf_len = 1024; static bool disconnect_sent = false; static int publish_count = 0; static bool ready_for_repeat = false; static volatile int status = STATUS_CONNECTING; #ifdef WIN32 static uint64_t next_publish_tv; static void set_repeat_time(void) { uint64_t ticks = GetTickCount64(); next_publish_tv = ticks + cfg.repeat_delay.tv_sec*1000 + cfg.repeat_delay.tv_usec/1000; } static int check_repeat_time(void) { uint64_t ticks = GetTickCount64(); if(ticks > next_publish_tv){ return 1; }else{ return 0; } } #else static struct timeval next_publish_tv; static void set_repeat_time(void) { gettimeofday(&next_publish_tv, NULL); next_publish_tv.tv_sec += cfg.repeat_delay.tv_sec; next_publish_tv.tv_usec += cfg.repeat_delay.tv_usec; next_publish_tv.tv_sec += next_publish_tv.tv_usec/1e6; next_publish_tv.tv_usec = next_publish_tv.tv_usec%1000000; } static int check_repeat_time(void) { struct timeval tv; gettimeofday(&tv, NULL); if(tv.tv_sec > next_publish_tv.tv_sec){ return 1; }else if(tv.tv_sec == next_publish_tv.tv_sec && tv.tv_usec > next_publish_tv.tv_usec){ return 1; } return 0; } #endif void my_disconnect_callback(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(obj); UNUSED(rc); UNUSED(properties); if(rc == 0){ status = STATUS_DISCONNECTED; } } int my_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, void *payload, int qos, bool retain) { ready_for_repeat = false; if(cfg.protocol_version == MQTT_PROTOCOL_V5 && cfg.have_topic_alias && first_publish == false){ return mosquitto_publish_v5(mosq, mid, NULL, payloadlen, payload, qos, retain, cfg.publish_props); }else{ first_publish = false; return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, cfg.publish_props); } } void my_connect_callback(struct mosquitto *mosq, void *obj, int result, int flags, const mosquitto_property *properties) { int rc = MOSQ_ERR_SUCCESS; UNUSED(obj); UNUSED(flags); UNUSED(properties); if(!result){ switch(cfg.pub_mode){ case MSGMODE_CMD: case MSGMODE_FILE: case MSGMODE_STDIN_FILE: rc = my_publish(mosq, &mid_sent, cfg.topic, cfg.msglen, cfg.message, cfg.qos, cfg.retain); break; case MSGMODE_NULL: rc = my_publish(mosq, &mid_sent, cfg.topic, 0, NULL, cfg.qos, cfg.retain); break; case MSGMODE_STDIN_LINE: status = STATUS_CONNACK_RECVD; break; } if(rc){ switch(rc){ case MOSQ_ERR_INVAL: err_printf(&cfg, "Error: Invalid input. Does your topic contain '+' or '#'?\n"); break; case MOSQ_ERR_NOMEM: err_printf(&cfg, "Error: Out of memory when trying to publish message.\n"); break; case MOSQ_ERR_NO_CONN: err_printf(&cfg, "Error: Client not connected when trying to publish.\n"); break; case MOSQ_ERR_PROTOCOL: err_printf(&cfg, "Error: Protocol error when communicating with broker.\n"); break; case MOSQ_ERR_PAYLOAD_SIZE: err_printf(&cfg, "Error: Message payload is too large.\n"); break; case MOSQ_ERR_QOS_NOT_SUPPORTED: err_printf(&cfg, "Error: Message QoS not supported on broker, try a lower QoS.\n"); break; } mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } }else{ if(result){ if(cfg.protocol_version == MQTT_PROTOCOL_V5){ if(result == MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION){ err_printf(&cfg, "Connection error: %s. Try connecting to an MQTT v5 broker, or use MQTT v3.x mode.\n", mosquitto_reason_string(result)); }else{ err_printf(&cfg, "Connection error: %s\n", mosquitto_reason_string(result)); } }else{ err_printf(&cfg, "Connection error: %s\n", mosquitto_connack_string(result)); } mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } } } void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { UNUSED(obj); UNUSED(properties); last_mid_sent = mid; if(reason_code > 127){ err_printf(&cfg, "Warning: Publish %d failed: %s.\n", mid, mosquitto_reason_string(reason_code)); } publish_count++; if(cfg.pub_mode == MSGMODE_STDIN_LINE){ if(mid == last_mid){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); disconnect_sent = true; } }else if(publish_count < cfg.repeat_count){ ready_for_repeat = true; set_repeat_time(); }else if(disconnect_sent == false){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); disconnect_sent = true; } } int pub_shared_init(void) { line_buf = malloc(line_buf_len); if(!line_buf){ err_printf(&cfg, "Error: Out of memory.\n"); return 1; } return 0; } int pub_stdin_line_loop(struct mosquitto *mosq) { char *buf2; int buf_len_actual = 0; int pos; int rc = MOSQ_ERR_SUCCESS; int read_len; bool stdin_finished = false; mosquitto_loop_start(mosq); stdin_finished = false; do{ if(status == STATUS_CONNACK_RECVD){ pos = 0; read_len = line_buf_len; while(status == STATUS_CONNACK_RECVD && fgets(&line_buf[pos], read_len, stdin)){ buf_len_actual = strlen(line_buf); if(line_buf[buf_len_actual-1] == '\n'){ line_buf[buf_len_actual-1] = '\0'; rc = my_publish(mosq, &mid_sent, cfg.topic, buf_len_actual-1, line_buf, cfg.qos, cfg.retain); pos = 0; if(rc){ err_printf(&cfg, "Error: Publish returned %d, disconnecting.\n", rc); mosquitto_disconnect_v5(mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); } break; }else{ line_buf_len += 1024; pos += 1023; read_len = 1024; buf2 = realloc(line_buf, line_buf_len); if(!buf2){ err_printf(&cfg, "Error: Out of memory.\n"); return MOSQ_ERR_NOMEM; } line_buf = buf2; } } if(pos != 0){ rc = my_publish(mosq, &mid_sent, cfg.topic, buf_len_actual, line_buf, cfg.qos, cfg.retain); if(rc){ err_printf(&cfg, "Error: Publish returned %d, disconnecting.\n", rc); mosquitto_disconnect_v5(mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); } } if(feof(stdin)){ if(mid_sent == -1){ /* Empty file */ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); disconnect_sent = true; status = STATUS_DISCONNECTING; }else{ last_mid = mid_sent; status = STATUS_WAITING; } stdin_finished = true; }else if(status == STATUS_DISCONNECTED){ /* Not end of stdin, so we've lost our connection and must * reconnect */ } } if(status == STATUS_WAITING){ if(last_mid_sent == last_mid && disconnect_sent == false){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); disconnect_sent = true; } #ifdef WIN32 Sleep(100); #else struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 100000000; nanosleep(&ts, NULL); #endif } }while(stdin_finished == false); mosquitto_loop_stop(mosq, false); if(status == STATUS_DISCONNECTED){ return MOSQ_ERR_SUCCESS; }else{ return rc; } } int pub_other_loop(struct mosquitto *mosq) { int rc; int loop_delay = 1000; if(cfg.repeat_count > 1 && (cfg.repeat_delay.tv_sec == 0 || cfg.repeat_delay.tv_usec != 0)){ loop_delay = cfg.repeat_delay.tv_usec / 2000; } do{ rc = mosquitto_loop(mosq, loop_delay, 1); if(ready_for_repeat && check_repeat_time()){ rc = MOSQ_ERR_SUCCESS; switch(cfg.pub_mode){ case MSGMODE_CMD: case MSGMODE_FILE: case MSGMODE_STDIN_FILE: rc = my_publish(mosq, &mid_sent, cfg.topic, cfg.msglen, cfg.message, cfg.qos, cfg.retain); break; case MSGMODE_NULL: rc = my_publish(mosq, &mid_sent, cfg.topic, 0, NULL, cfg.qos, cfg.retain); break; } if(rc){ err_printf(&cfg, "Error sending repeat publish: %s", mosquitto_strerror(rc)); } } }while(rc == MOSQ_ERR_SUCCESS); if(status == STATUS_DISCONNECTED){ return MOSQ_ERR_SUCCESS; }else{ return rc; } } int pub_shared_loop(struct mosquitto *mosq) { if(cfg.pub_mode == MSGMODE_STDIN_LINE){ return pub_stdin_line_loop(mosq); }else{ return pub_other_loop(mosq); } } void pub_shared_cleanup(void) { free(line_buf); } void print_usage(void) { int major, minor, revision; mosquitto_lib_version(&major, &minor, &revision); printf("mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit.\n"); printf("mosquitto_pub version %s running on libmosquitto %d.%d.%d.\n\n", VERSION, major, minor, revision); printf("Usage: mosquitto_pub {[-h host] [-p port] [-u username] [-P password] -t topic | -L URL}\n"); printf(" {-f file | -l | -n | -m message}\n"); printf(" [-c] [-k keepalive] [-q qos] [-r] [--repeat N] [--repeat-delay time]\n"); #ifdef WITH_SRV printf(" [-A bind_address] [-S]\n"); #else printf(" [-A bind_address]\n"); #endif printf(" [-i id] [-I id_prefix]\n"); printf(" [-d] [--quiet]\n"); printf(" [-M max_inflight]\n"); printf(" [-u username [-P password]]\n"); printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n"); #ifdef WITH_TLS printf(" [{--cafile file | --capath dir} [--cert file] [--key file]\n"); printf(" [--ciphers ciphers] [--insecure]\n"); printf(" [--tls-alpn protocol]\n"); printf(" [--tls-engine engine] [--keyform keyform] [--tls-engine-kpass-sha1]]\n"); #ifdef FINAL_WITH_TLS_PSK printf(" [--psk hex-key --psk-identity identity [--ciphers ciphers]]\n"); #endif #endif #ifdef WITH_SOCKS printf(" [--proxy socks-url]\n"); #endif printf(" [--property command identifier value]\n"); printf(" [-D command identifier value]\n"); printf(" mosquitto_pub --help\n\n"); printf(" -A : bind the outgoing socket to this host/ip address. Use to control which interface\n"); printf(" the client communicates over.\n"); printf(" -d : enable debug messages.\n"); printf(" -D : Define MQTT v5 properties. See the documentation for more details.\n"); printf(" -f : send the contents of a file as the message.\n"); printf(" -h : mqtt host to connect to. Defaults to localhost.\n"); printf(" -i : id to use for this client. Defaults to mosquitto_pub_ appended with the process id.\n"); printf(" -I : define the client id as id_prefix appended with the process id. Useful for when the\n"); printf(" broker is using the clientid_prefixes option.\n"); printf(" -k : keep alive in seconds for this client. Defaults to 60.\n"); printf(" -L : specify user, password, hostname, port and topic as a URL in the form:\n"); printf(" mqtt(s)://[username[:password]@]host[:port]/topic\n"); printf(" -l : read messages from stdin, sending a separate message for each line.\n"); printf(" -m : message payload to send.\n"); printf(" -M : the maximum inflight messages for QoS 1/2..\n"); printf(" -n : send a null (zero length) message.\n"); printf(" -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.\n"); printf(" -P : provide a password\n"); printf(" -q : quality of service level to use for all messages. Defaults to 0.\n"); printf(" -r : message should be retained.\n"); printf(" -s : read message from stdin, sending the entire input as a message.\n"); #ifdef WITH_SRV printf(" -S : use SRV lookups to determine which host to connect to.\n"); #endif printf(" -t : mqtt topic to publish to.\n"); printf(" -u : provide a username\n"); printf(" -V : specify the version of the MQTT protocol to use when connecting.\n"); printf(" Can be mqttv5, mqttv311 or mqttv31. Defaults to mqttv311.\n"); printf(" --help : display this message.\n"); printf(" --repeat : if publish mode is -f, -m, or -s, then repeat the publish N times.\n"); printf(" --repeat-delay : if using --repeat, wait time seconds between publishes. Defaults to 0.\n"); printf(" --quiet : don't print error messages.\n"); printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n"); printf(" unexpected disconnection. If not given and will-topic is set, a zero\n"); printf(" length message will be sent.\n"); printf(" --will-qos : QoS level for the client Will.\n"); printf(" --will-retain : if given, make the client Will retained.\n"); printf(" --will-topic : the topic on which to publish the client Will.\n"); #ifdef WITH_TLS printf(" --cafile : path to a file containing trusted CA certificates to enable encrypted\n"); printf(" communication.\n"); printf(" --capath : path to a directory containing trusted CA certificates to enable encrypted\n"); printf(" communication.\n"); printf(" --cert : client certificate for authentication, if required by server.\n"); printf(" --key : client private key for authentication, if required by server.\n"); printf(" --keyform : keyfile type, can be either \"pem\" or \"engine\".\n"); printf(" --ciphers : openssl compatible list of TLS ciphers to support.\n"); printf(" --tls-version : TLS protocol version, can be one of tlsv1.3 tlsv1.2 or tlsv1.1.\n"); printf(" Defaults to tlsv1.2 if available.\n"); printf(" --insecure : do not check that the server certificate hostname matches the remote\n"); printf(" hostname. Using this option means that you cannot be sure that the\n"); printf(" remote host is the server you wish to connect to and so is insecure.\n"); printf(" Do not use this option in a production environment.\n"); printf(" --tls-engine : If set, enables the use of a TLS engine device.\n"); printf(" --tls-engine-kpass-sha1 : SHA1 of the key password to be used with the selected SSL engine.\n"); # ifdef FINAL_WITH_TLS_PSK printf(" --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.\n"); printf(" --psk-identity : client identity string for TLS-PSK mode.\n"); # endif #endif #ifdef WITH_SOCKS printf(" --proxy : SOCKS5 proxy URL of the form:\n"); printf(" socks5h://[username[:password]@]hostname[:port]\n"); printf(" Only \"none\" and \"username\" authentication is supported.\n"); #endif printf("\nSee https://mosquitto.org/ for more information.\n\n"); } int main(int argc, char *argv[]) { struct mosquitto *mosq = NULL; int rc; mosquitto_lib_init(); if(pub_shared_init()) return 1; rc = client_config_load(&cfg, CLIENT_PUB, argc, argv); if(rc){ if(rc == 2){ /* --help */ print_usage(); }else{ fprintf(stderr, "\nUse 'mosquitto_pub --help' to see usage.\n"); } goto cleanup; } #ifndef WITH_THREADING if(cfg.pub_mode == MSGMODE_STDIN_LINE){ fprintf(stderr, "Error: '-l' mode not available, threading support has not been compiled in.\n"); goto cleanup; } #endif if(cfg.pub_mode == MSGMODE_STDIN_FILE){ if(load_stdin()){ err_printf(&cfg, "Error loading input from stdin.\n"); goto cleanup; } }else if(cfg.file_input){ if(load_file(cfg.file_input)){ err_printf(&cfg, "Error loading input file \"%s\".\n", cfg.file_input); goto cleanup; } } if(!cfg.topic || cfg.pub_mode == MSGMODE_NONE){ fprintf(stderr, "Error: Both topic and message must be supplied.\n"); print_usage(); goto cleanup; } if(client_id_generate(&cfg)){ goto cleanup; } mosq = mosquitto_new(cfg.id, cfg.clean_session, NULL); if(!mosq){ switch(errno){ case ENOMEM: err_printf(&cfg, "Error: Out of memory.\n"); break; case EINVAL: err_printf(&cfg, "Error: Invalid id.\n"); break; } goto cleanup; } if(cfg.debug){ mosquitto_log_callback_set(mosq, my_log_callback); } mosquitto_connect_v5_callback_set(mosq, my_connect_callback); mosquitto_disconnect_v5_callback_set(mosq, my_disconnect_callback); mosquitto_publish_v5_callback_set(mosq, my_publish_callback); if(client_opts_set(mosq, &cfg)){ goto cleanup; } rc = client_connect(mosq, &cfg); if(rc){ goto cleanup; } rc = pub_shared_loop(mosq); if(cfg.message && cfg.pub_mode == MSGMODE_FILE){ free(cfg.message); cfg.message = NULL; } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); client_config_cleanup(&cfg); pub_shared_cleanup(); if(rc){ err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc)); } return rc; cleanup: mosquitto_lib_cleanup(); client_config_cleanup(&cfg); pub_shared_cleanup(); return 1; } mosquitto-1.6.9/client/sub_client_output.c0000664000175000017500000001466013626052637020025 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #ifndef WIN32 #include #else #include #include #define snprintf sprintf_s #endif #ifdef __APPLE__ # include #endif #include #include "client_shared.h" extern struct mosq_config cfg; static int get_time(struct tm **ti, long *ns) { #ifdef WIN32 SYSTEMTIME st; #elif defined(__APPLE__) struct timeval tv; #else struct timespec ts; #endif time_t s; #ifdef WIN32 s = time(NULL); GetLocalTime(&st); *ns = st.wMilliseconds*1000000L; #elif defined(__APPLE__) gettimeofday(&tv, NULL); s = tv.tv_sec; *ns = tv.tv_usec*1000; #else if(clock_gettime(CLOCK_REALTIME, &ts) != 0){ err_printf(&cfg, "Error obtaining system time.\n"); return 1; } s = ts.tv_sec; *ns = ts.tv_nsec; #endif *ti = localtime(&s); if(!(*ti)){ err_printf(&cfg, "Error obtaining system time.\n"); return 1; } return 0; } static void write_payload(const unsigned char *payload, int payloadlen, int hex) { int i; if(hex == 0){ (void)fwrite(payload, 1, payloadlen, stdout); }else if(hex == 1){ for(i=0; i=0 && payload[i] < 32)){ printf("\\u%04x", payload[i]); }else{ fputc(payload[i], stdout); } } } static void json_print(const struct mosquitto_message *message, const struct tm *ti, bool escaped) { char buf[100]; strftime(buf, 100, "%s", ti); printf("{\"tst\":%s,\"topic\":\"%s\",\"qos\":%d,\"retain\":%d,\"payloadlen\":%d,", buf, message->topic, message->qos, message->retain, message->payloadlen); if(message->qos > 0){ printf("\"mid\":%d,", message->mid); } if(escaped){ fputs("\"payload\":\"", stdout); write_json_payload(message->payload, message->payloadlen); fputs("\"}", stdout); }else{ fputs("\"payload\":", stdout); write_payload(message->payload, message->payloadlen, 0); fputs("}", stdout); } } static void formatted_print(const struct mosq_config *lcfg, const struct mosquitto_message *message) { int len; int i; struct tm *ti = NULL; long ns; char strf[3]; char buf[100]; len = strlen(lcfg->format); for(i=0; iformat[i] == '%'){ if(i < len-1){ i++; switch(lcfg->format[i]){ case '%': fputc('%', stdout); break; case 'I': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } if(strftime(buf, 100, "%FT%T%z", ti) != 0){ fputs(buf, stdout); } break; case 'j': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } json_print(message, ti, true); break; case 'J': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } json_print(message, ti, false); break; case 'l': printf("%d", message->payloadlen); break; case 'm': printf("%d", message->mid); break; case 'p': write_payload(message->payload, message->payloadlen, 0); break; case 'q': fputc(message->qos + 48, stdout); break; case 'r': if(message->retain){ fputc('1', stdout); }else{ fputc('0', stdout); } break; case 't': fputs(message->topic, stdout); break; case 'U': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } if(strftime(buf, 100, "%s", ti) != 0){ printf("%s.%09ld", buf, ns); } break; case 'x': write_payload(message->payload, message->payloadlen, 1); break; case 'X': write_payload(message->payload, message->payloadlen, 2); break; } } }else if(lcfg->format[i] == '@'){ if(i < len-1){ i++; if(lcfg->format[i] == '@'){ fputc('@', stdout); }else{ if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } strf[0] = '%'; strf[1] = lcfg->format[i]; strf[2] = 0; if(lcfg->format[i] == 'N'){ printf("%09ld", ns); }else{ if(strftime(buf, 100, strf, ti) != 0){ fputs(buf, stdout); } } } } }else if(lcfg->format[i] == '\\'){ if(i < len-1){ i++; switch(lcfg->format[i]){ case '\\': fputc('\\', stdout); break; case '0': fputc('\0', stdout); break; case 'a': fputc('\a', stdout); break; case 'e': fputc('\033', stdout); break; case 'n': fputc('\n', stdout); break; case 'r': fputc('\r', stdout); break; case 't': fputc('\t', stdout); break; case 'v': fputc('\v', stdout); break; } } }else{ fputc(lcfg->format[i], stdout); } } if(lcfg->eol){ fputc('\n', stdout); } fflush(stdout); } void print_message(struct mosq_config *cfg, const struct mosquitto_message *message) { if(cfg->format){ formatted_print(cfg, message); }else if(cfg->verbose){ if(message->payloadlen){ printf("%s ", message->topic); write_payload(message->payload, message->payloadlen, false); if(cfg->eol){ printf("\n"); } }else{ if(cfg->eol){ printf("%s (null)\n", message->topic); } } fflush(stdout); }else{ if(message->payloadlen){ write_payload(message->payload, message->payloadlen, false); if(cfg->eol){ printf("\n"); } fflush(stdout); } } } mosquitto-1.6.9/client/pub_shared.c0000664000175000017500000000534513626052637016372 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #ifndef WIN32 #include #else #include #include #define snprintf sprintf_s #endif #include #include #include "client_shared.h" #include "pub_shared.h" /* Global variables for use in callbacks. See sub_client.c for an example of * using a struct to hold variables for use in callbacks. */ int mid_sent = -1; struct mosq_config cfg; void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str) { UNUSED(mosq); UNUSED(obj); UNUSED(level); printf("%s\n", str); } int load_stdin(void) { long pos = 0, rlen; char buf[1024]; char *aux_message = NULL; cfg.pub_mode = MSGMODE_STDIN_FILE; while(!feof(stdin)){ rlen = fread(buf, 1, 1024, stdin); aux_message = realloc(cfg.message, pos+rlen); if(!aux_message){ err_printf(&cfg, "Error: Out of memory.\n"); free(cfg.message); return 1; } else { cfg.message = aux_message; } memcpy(&(cfg.message[pos]), buf, rlen); pos += rlen; } cfg.msglen = pos; if(!cfg.msglen){ err_printf(&cfg, "Error: Zero length input.\n"); return 1; } return 0; } int load_file(const char *filename) { long pos, rlen; FILE *fptr = NULL; fptr = fopen(filename, "rb"); if(!fptr){ err_printf(&cfg, "Error: Unable to open file \"%s\".\n", filename); return 1; } cfg.pub_mode = MSGMODE_FILE; fseek(fptr, 0, SEEK_END); cfg.msglen = ftell(fptr); if(cfg.msglen > 268435455){ fclose(fptr); err_printf(&cfg, "Error: File \"%s\" is too large (>268,435,455 bytes).\n", filename); return 1; }else if(cfg.msglen == 0){ fclose(fptr); err_printf(&cfg, "Error: File \"%s\" is empty.\n", filename); return 1; }else if(cfg.msglen < 0){ fclose(fptr); err_printf(&cfg, "Error: Unable to determine size of file \"%s\".\n", filename); return 1; } fseek(fptr, 0, SEEK_SET); cfg.message = malloc(cfg.msglen); if(!cfg.message){ fclose(fptr); err_printf(&cfg, "Error: Out of memory.\n"); return 1; } pos = 0; while(pos < cfg.msglen){ rlen = fread(&(cfg.message[pos]), sizeof(char), cfg.msglen-pos, fptr); pos += rlen; } fclose(fptr); return 0; } mosquitto-1.6.9/client/Makefile0000664000175000017500000000655413626052637015555 0ustar rogerrogerinclude ../config.mk .PHONY: all install uninstall reallyclean clean static static_pub static_sub static_rr ifeq ($(WITH_SHARED_LIBRARIES),yes) SHARED_DEP:=../lib/libmosquitto.so.${SOVERSION} endif ifeq ($(WITH_SHARED_LIBRARIES),yes) ALL_DEPS:= mosquitto_pub mosquitto_sub mosquitto_rr else ifeq ($(WITH_STATIC_LIBRARIES),yes) ALL_DEPS:= static_pub static_sub static_rr endif endif all : ${ALL_DEPS} static : static_pub static_sub static_rr # This makes mosquitto_pub/sub/rr versions that are statically linked with # libmosquitto only. static_pub : pub_client.o pub_shared.o client_props.o client_shared.o ../lib/libmosquitto.a ${CROSS_COMPILE}${CC} $^ -o mosquitto_pub ${CLIENT_LDFLAGS} ${STATIC_LIB_DEPS} ${CLIENT_STATIC_LDADD} static_sub : sub_client.o sub_client_output.o client_props.o client_shared.o ../lib/libmosquitto.a ${CROSS_COMPILE}${CC} $^ -o mosquitto_sub ${CLIENT_LDFLAGS} ${STATIC_LIB_DEPS} ${CLIENT_STATIC_LDADD} static_rr : rr_client.o client_props.o client_shared.o pub_shared.o sub_client_output.o ../lib/libmosquitto.a ${CROSS_COMPILE}${CC} $^ -o mosquitto_rr ${CLIENT_LDFLAGS} ${STATIC_LIB_DEPS} ${CLIENT_STATIC_LDADD} mosquitto_pub : pub_client.o pub_shared.o client_shared.o client_props.o ${CROSS_COMPILE}${CC} $(CLIENT_LDFLAGS) $^ -o $@ $(CLIENT_LDADD) mosquitto_sub : sub_client.o sub_client_output.o client_shared.o client_props.o ${CROSS_COMPILE}${CC} $(CLIENT_LDFLAGS) $^ -o $@ $(CLIENT_LDADD) mosquitto_rr : rr_client.o client_shared.o client_props.o pub_shared.o sub_client_output.o ${CROSS_COMPILE}${CC} $(CLIENT_LDFLAGS) $^ -o $@ $(CLIENT_LDADD) pub_client.o : pub_client.c ${SHARED_DEP} ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ pub_shared.o : pub_shared.c ${SHARED_DEP} ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ sub_client.o : sub_client.c ${SHARED_DEP} ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ sub_client_output.o : sub_client_output.c ${SHARED_DEP} ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ rr_client.o : rr_client.c ${SHARED_DEP} ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ client_shared.o : client_shared.c client_shared.h ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ client_props.o : client_props.c client_shared.h ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ # The "testing" target is intended to make it easy to compile a quick client # for testing purposes. testing.c should not be committed as a file. testing : testing.o ${CROSS_COMPILE}${CC} $(CLIENT_LDFLAGS) $^ -o $@ $(CLIENT_LDADD) $(CLIENT_LDFLAGS) testing.o : testing.c ${CROSS_COMPILE}${CC} $(CLIENT_CPPFLAGS) $(CLIENT_CFLAGS) -c $< -o $@ ../lib/libmosquitto.so.${SOVERSION} : $(MAKE) -C ../lib ../lib/libmosquitto.a : $(MAKE) -C ../lib libmosquitto.a install : all $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_pub "${DESTDIR}${prefix}/bin/mosquitto_pub" $(INSTALL) ${STRIP_OPTS} mosquitto_sub "${DESTDIR}${prefix}/bin/mosquitto_sub" $(INSTALL) ${STRIP_OPTS} mosquitto_rr "${DESTDIR}${prefix}/bin/mosquitto_rr" uninstall : -rm -f "${DESTDIR}${prefix}/bin/mosquitto_pub" -rm -f "${DESTDIR}${prefix}/bin/mosquitto_sub" -rm -f "${DESTDIR}${prefix}/bin/mosquitto_rr" reallyclean : clean clean : -rm -f *.o mosquitto_pub mosquitto_sub mosquitto_rr *.gcda *.gcno mosquitto-1.6.9/client/pub_shared.h0000664000175000017500000000275713626052637016403 0ustar rogerroger/* Copyright (c) 2009-2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef PUB_SHARED_H #define PUB_SHARED_H #define STATUS_CONNECTING 0 #define STATUS_CONNACK_RECVD 1 #define STATUS_WAITING 2 #define STATUS_DISCONNECTING 3 #define STATUS_DISCONNECTED 4 extern int mid_sent; extern struct mosq_config cfg; void my_connect_callback(struct mosquitto *mosq, void *obj, int result, int flags, const mosquitto_property *properties); void my_disconnect_callback(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties); void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties); void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str); int load_stdin(void); int load_file(const char *filename); int my_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, void *payload, int qos, bool retain); int pub_shared_init(void); int pub_shared_loop(struct mosquitto *mosq); void pub_shared_cleanup(void); #endif mosquitto-1.6.9/client/pub_test_properties0000775000175000017500000000154213626052637020134 0ustar rogerrogerLD_LIBRARY_PATH=../lib ./mosquitto_pub \ \ -t asdf -V mqttv5 -m '{"key":"value"}' \ \ -D connect authentication-data password \ -D connect authentication-method something \ -D connect maximum-packet-size 0191 \ -D connect receive-maximum 1000 \ -D connect request-problem-information 1 \ -D connect request-response-information 1 \ -D connect session-expiry-interval 39 \ -D connect topic-alias-maximum 123 \ -D connect user-property connect up \ \ -D publish content-type application/json \ -D publish correlation-data some-data \ -D publish message-expiry-interval 59 \ -D publish payload-format-indicator 1 \ -D publish response-topic /dev/null \ -D publish topic-alias 4 \ -D publish user-property publish up \ \ -D disconnect reason-string "reason" \ -D disconnect session-expiry-interval 40 \ -D disconnect user-property disconnect up mosquitto-1.6.9/libmosquitto.pc.in0000664000175000017500000000036613626052637016316 0ustar rogerrogerprefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/lib Name: mosquitto Description: mosquitto MQTT library (C bindings) Version: @VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lmosquitto mosquitto-1.6.9/test/0000775000175000017500000000000013626052637013604 5ustar rogerrogermosquitto-1.6.9/test/mqtt5_rc.py0000664000175000017500000000273113626052637015717 0ustar rogerrogerMQTT_RC_SUCCESS = 0 MQTT_RC_NORMAL_DISCONNECTION = 0 MQTT_RC_GRANTED_QOS0 = 0 MQTT_RC_GRANTED_QOS1 = 1 MQTT_RC_GRANTED_QOS2 = 2 MQTT_RC_DISCONNECT_WITH_WILL_MSG = 4 MQTT_RC_NO_MATCHING_SUBSCRIBERS = 16 MQTT_RC_NO_SUBSCRIPTION_EXISTED = 17 MQTT_RC_CONTINUE_AUTHENTICATION = 24 MQTT_RC_REAUTHENTICATE = 25 MQTT_RC_UNSPECIFIED = 128 MQTT_RC_MALFORMED_PACKET = 129 MQTT_RC_PROTOCOL_ERROR = 130 MQTT_RC_IMPLEMENTATION_SPECIFIC = 131 MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION = 132 MQTT_RC_CLIENTID_NOT_VALID = 133 MQTT_RC_BAD_USERNAME_OR_PASSWORD = 134 MQTT_RC_NOT_AUTHORIZED = 135 MQTT_RC_SERVER_UNAVAILABLE = 136 MQTT_RC_SERVER_BUSY = 137 MQTT_RC_BANNED = 138 MQTT_RC_SERVER_SHUTTING_DOWN = 139 MQTT_RC_BAD_AUTHENTICATION_METHOD = 140 MQTT_RC_KEEP_ALIVE_TIMEOUT = 141 MQTT_RC_SESSION_TAKEN_OVER = 142 MQTT_RC_TOPIC_FILTER_INVALID = 143 MQTT_RC_TOPIC_NAME_INVALID = 144 MQTT_RC_PACKET_ID_IN_USE = 145 MQTT_RC_PACKET_ID_NOT_FOUND = 146 MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED = 147 MQTT_RC_TOPIC_ALIAS_INVALID = 148 MQTT_RC_PACKET_TOO_LARGE = 149 MQTT_RC_MESSAGE_RATE_TOO_HIGH = 150 MQTT_RC_QUOTA_EXCEEDED = 151 MQTT_RC_ADMINISTRATIVE_ACTION = 152 MQTT_RC_PAYLOAD_FORMAT_INVALID = 153 MQTT_RC_RETAIN_NOT_SUPPORTED = 154 MQTT_RC_QOS_NOT_SUPPORTED = 155 MQTT_RC_USE_ANOTHER_SERVER = 156 MQTT_RC_SERVER_MOVED = 157 MQTT_RC_SHARED_SUBS_NOT_SUPPORTED = 158 MQTT_RC_CONNECTION_RATE_EXCEEDED = 159 MQTT_RC_MAXIMUM_CONNECT_TIME = 160 MQTT_RC_SUBSCRIPTION_IDS_NOT_SUPPORTED = 161 MQTT_RC_WILDCARD_SUBS_NOT_SUPPORTED = 162 mosquitto-1.6.9/test/ptest.py0000775000175000017500000000433313626052637015323 0ustar rogerroger#!/usr/bin/env python3 import subprocess import time import sys def next_test(tests, ports): if len(tests) == 0 or len(ports) == 0: return test = tests.pop() proc_ports = () if len(ports) < test[0]: tests.insert(0, test) return None else: if isinstance(test[1], (list,)): args = test[1] else: args = [test[1]] for i in range(0, test[0]): proc_port = ports.pop() proc_ports = proc_ports + (proc_port,) args.append(str(proc_port)) proc = subprocess.Popen(args) proc.start_time = time.time() proc.mosq_port = proc_ports return proc def run_tests(tests, minport=1888, max_running=20): ports = list(range(minport, minport+max_running+1)) start_time = time.time() passed = 0 failed = 0 failed_tests = [] running_tests = [] while len(tests) > 0 or len(running_tests) > 0: if len(running_tests) <= max_running: t = next_test(tests, ports) if t is None: time.sleep(0.1) else: running_tests.append(t) for t in running_tests: t.poll() if t.returncode is not None: running_tests.remove(t) if isinstance(t.mosq_port, tuple): for portret in t.mosq_port: ports.append(portret) else: ports.append(t.mosq_port) t.terminate() t.wait() runtime = time.time() - t.start_time #(stdo, stde) = t.communicate() if t.returncode == 1: print("%0.3fs : \033[31m%s\033[0m" % (runtime, t.args[0])) failed = failed + 1 failed_tests.append(t.args[0]) else: passed = passed + 1 print("%0.3fs : \033[32m%s\033[0m" % (runtime, t.args[0])) print("Passed: %d\nFailed: %d\nTotal: %d\nTotal time: %0.2f" % (passed, failed, passed+failed, time.time()-start_time)) if failed > 0: print("Failing tests:") for f in failed_tests: print(f) sys.exit(1) mosquitto-1.6.9/test/mosq_test.py0000664000175000017500000005320013626052637016174 0ustar rogerrogerimport errno import os import socket import subprocess import struct import sys import time import mqtt5_props import __main__ import atexit vg_index = 1 vg_logfiles = [] def start_broker(filename, cmd=None, port=0, use_conf=False, expect_fail=False): global vg_index global vg_logfiles delay = 0.1 if use_conf == True: cmd = ['../../src/mosquitto', '-v', '-c', filename.replace('.py', '.conf')] if port == 0: port = 1888 else: if cmd is None and port != 0: cmd = ['../../src/mosquitto', '-v', '-p', str(port)] elif cmd is None and port == 0: port = 1888 cmd = ['../../src/mosquitto', '-v', '-c', filename.replace('.py', '.conf')] elif cmd is not None and port == 0: port = 1888 if os.environ.get('MOSQ_USE_VALGRIND') is not None: logfile = filename+'.'+str(vg_index)+'.vglog' cmd = ['valgrind', '-q', '--trace-children=yes', '--leak-check=full', '--show-leak-kinds=all', '--log-file='+logfile] + cmd vg_logfiles.append(logfile) vg_index += 1 delay = 1 #print(port) #print(cmd) broker = subprocess.Popen(cmd, stderr=subprocess.PIPE) for i in range(0, 20): time.sleep(delay) c = None try: c = socket.create_connection(("localhost", port)) except socket.error as err: if err.errno != errno.ECONNREFUSED: raise if c is not None: c.close() time.sleep(delay) return broker if expect_fail == False: raise IOError else: return None def start_client(filename, cmd, env, port=1888): if cmd is None: raise ValueError if os.environ.get('MOSQ_USE_VALGRIND') is not None: cmd = ['valgrind', '-q', '--log-file='+filename+'.vglog'] + cmd cmd = cmd + [str(port)] return subprocess.Popen(cmd, env=env) def expect_packet(sock, name, expected): if len(expected) > 0: rlen = len(expected) else: rlen = 1 packet_recvd = sock.recv(rlen) return packet_matches(name, packet_recvd, expected) def packet_matches(name, recvd, expected): if recvd != expected: print("FAIL: Received incorrect "+name+".") try: print("Received: "+to_string(recvd)) except struct.error: print("Received (not decoded, len=%d): %s" % (len(recvd), recvd)) for i in range(0, len(recvd)): print('%c'%(recvd[i]),) try: print("Expected: "+to_string(expected)) except struct.error: print("Expected (not decoded, len=%d): %s" % (len(expected), expected)) for i in range(0, len(expected)): print('%c'%(expected[i]),) return 0 else: return 1 def do_send_receive(sock, send_packet, receive_packet, error_string="send receive error"): size = len(send_packet) total_sent = 0 while total_sent < size: sent = sock.send(send_packet[total_sent:]) if sent == 0: raise RuntimeError("socket connection broken") total_sent += sent if expect_packet(sock, error_string, receive_packet): return sock else: sock.close() raise ValueError def do_client_connect(connect_packet, connack_packet, hostname="localhost", port=1888, timeout=60, connack_error="connack"): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((hostname, port)) return do_send_receive(sock, connect_packet, connack_packet, connack_error) def remaining_length(packet): l = min(5, len(packet)) all_bytes = struct.unpack("!"+"B"*l, packet[:l]) mult = 1 rl = 0 for i in range(1,l-1): byte = all_bytes[i] rl += (byte & 127) * mult mult *= 128 if byte & 128 == 0: packet = packet[i+1:] break return (packet, rl) def to_hex_string(packet): if len(packet) == 0: return "" s = "" while len(packet) > 0: packet0 = struct.unpack("!B", packet[0]) s = s+hex(packet0[0]) + " " packet = packet[1:] return s def to_string(packet): if len(packet) == 0: return "" packet0 = struct.unpack("!B", bytes(packet[0])) packet0 = packet0[0] cmd = packet0 & 0xF0 if cmd == 0x00: # Reserved return "0x00" elif cmd == 0x10: # CONNECT (packet, rl) = remaining_length(packet) pack_format = "!H" + str(len(packet)-2) + 's' (slen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(slen)+'sBBH' + str(len(packet)-slen-4) + 's' (protocol, proto_ver, flags, keepalive, packet) = struct.unpack(pack_format, packet) s = "CONNECT, proto="+protocol+str(proto_ver)+", keepalive="+str(keepalive) if flags&2: s = s+", clean-session" else: s = s+", durable" pack_format = "!H" + str(len(packet)-2) + 's' (slen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(slen)+'s' + str(len(packet)-slen) + 's' (client_id, packet) = struct.unpack(pack_format, packet) s = s+", id="+client_id if flags&4: pack_format = "!H" + str(len(packet)-2) + 's' (slen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(slen)+'s' + str(len(packet)-slen) + 's' (will_topic, packet) = struct.unpack(pack_format, packet) s = s+", will-topic="+will_topic pack_format = "!H" + str(len(packet)-2) + 's' (slen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(slen)+'s' + str(len(packet)-slen) + 's' (will_message, packet) = struct.unpack(pack_format, packet) s = s+", will-message="+will_message s = s+", will-qos="+str((flags&24)>>3) s = s+", will-retain="+str((flags&32)>>5) if flags&128: pack_format = "!H" + str(len(packet)-2) + 's' (slen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(slen)+'s' + str(len(packet)-slen) + 's' (username, packet) = struct.unpack(pack_format, packet) s = s+", username="+username if flags&64: pack_format = "!H" + str(len(packet)-2) + 's' (slen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(slen)+'s' + str(len(packet)-slen) + 's' (password, packet) = struct.unpack(pack_format, packet) s = s+", password="+password if flags&1: s = s+", reserved=1" return s elif cmd == 0x20: # CONNACK (cmd, rl, resv, rc) = struct.unpack('!BBBB', packet) return "CONNACK, rl="+str(rl)+", res="+str(resv)+", rc="+str(rc) elif cmd == 0x30: # PUBLISH dup = (packet0 & 0x08)>>3 qos = (packet0 & 0x06)>>1 retain = (packet0 & 0x01) (packet, rl) = remaining_length(packet) pack_format = "!H" + str(len(packet)-2) + 's' (tlen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(tlen)+'s' + str(len(packet)-tlen) + 's' (topic, packet) = struct.unpack(pack_format, packet) s = "PUBLISH, rl="+str(rl)+", topic="+topic+", qos="+str(qos)+", retain="+str(retain)+", dup="+str(dup) if qos > 0: pack_format = "!H" + str(len(packet)-2) + 's' (mid, packet) = struct.unpack(pack_format, packet) s = s + ", mid="+str(mid) s = s + ", payload="+packet return s elif cmd == 0x40: # PUBACK (cmd, rl, mid) = struct.unpack('!BBH', packet) return "PUBACK, rl="+str(rl)+", mid="+str(mid) elif cmd == 0x50: # PUBREC (cmd, rl, mid) = struct.unpack('!BBH', packet) return "PUBREC, rl="+str(rl)+", mid="+str(mid) elif cmd == 0x60: # PUBREL dup = (packet0 & 0x08)>>3 (cmd, rl, mid) = struct.unpack('!BBH', packet) return "PUBREL, rl="+str(rl)+", mid="+str(mid)+", dup="+str(dup) elif cmd == 0x70: # PUBCOMP (cmd, rl, mid) = struct.unpack('!BBH', packet) return "PUBCOMP, rl="+str(rl)+", mid="+str(mid) elif cmd == 0x80: # SUBSCRIBE (packet, rl) = remaining_length(packet) pack_format = "!H" + str(len(packet)-2) + 's' (mid, packet) = struct.unpack(pack_format, packet) s = "SUBSCRIBE, rl="+str(rl)+", mid="+str(mid) topic_index = 0 while len(packet) > 0: pack_format = "!H" + str(len(packet)-2) + 's' (tlen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(tlen)+'sB' + str(len(packet)-tlen-1) + 's' (topic, qos, packet) = struct.unpack(pack_format, packet) s = s + ", topic"+str(topic_index)+"="+topic+","+str(qos) return s elif cmd == 0x90: # SUBACK (packet, rl) = remaining_length(packet) pack_format = "!H" + str(len(packet)-2) + 's' (mid, packet) = struct.unpack(pack_format, packet) pack_format = "!" + "B"*len(packet) granted_qos = struct.unpack(pack_format, packet) s = "SUBACK, rl="+str(rl)+", mid="+str(mid)+", granted_qos="+str(granted_qos[0]) for i in range(1, len(granted_qos)-1): s = s+", "+str(granted_qos[i]) return s elif cmd == 0xA0: # UNSUBSCRIBE (packet, rl) = remaining_length(packet) pack_format = "!H" + str(len(packet)-2) + 's' (mid, packet) = struct.unpack(pack_format, packet) s = "UNSUBSCRIBE, rl="+str(rl)+", mid="+str(mid) topic_index = 0 while len(packet) > 0: pack_format = "!H" + str(len(packet)-2) + 's' (tlen, packet) = struct.unpack(pack_format, packet) pack_format = "!" + str(tlen)+'s' + str(len(packet)-tlen) + 's' (topic, packet) = struct.unpack(pack_format, packet) s = s + ", topic"+str(topic_index)+"="+topic return s elif cmd == 0xB0: # UNSUBACK (cmd, rl, mid) = struct.unpack('!BBH', packet) return "UNSUBACK, rl="+str(rl)+", mid="+str(mid) elif cmd == 0xC0: # PINGREQ (cmd, rl) = struct.unpack('!BB', packet) return "PINGREQ, rl="+str(rl) elif cmd == 0xD0: # PINGRESP (cmd, rl) = struct.unpack('!BB', packet) return "PINGRESP, rl="+str(rl) elif cmd == 0xE0: # DISCONNECT (cmd, rl) = struct.unpack('!BB', packet) return "DISCONNECT, rl="+str(rl) elif cmd == 0xF0: # AUTH (cmd, rl) = struct.unpack('!BB', packet) return "AUTH, rl="+str(rl) def gen_connect(client_id, clean_session=True, keepalive=60, username=None, password=None, will_topic=None, will_qos=0, will_retain=False, will_payload=b"", proto_ver=4, connect_reserved=False, properties=b"", will_properties=b""): if (proto_ver&0x7F) == 3 or proto_ver == 0: remaining_length = 12 elif (proto_ver&0x7F) == 4 or proto_ver == 5: remaining_length = 10 else: raise ValueError if client_id != None: client_id = client_id.encode("utf-8") remaining_length = remaining_length + 2+len(client_id) else: remaining_length = remaining_length + 2 connect_flags = 0 if connect_reserved: connect_flags = connect_flags | 0x01 if clean_session: connect_flags = connect_flags | 0x02 if proto_ver == 5: if properties == b"": properties += mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 20) properties = mqtt5_props.prop_finalise(properties) remaining_length += len(properties) if will_topic != None: will_topic = will_topic.encode("utf-8") remaining_length = remaining_length + 2+len(will_topic) + 2+len(will_payload) connect_flags = connect_flags | 0x04 | ((will_qos&0x03) << 3) if will_retain: connect_flags = connect_flags | 32 if proto_ver == 5: will_properties = mqtt5_props.prop_finalise(will_properties) remaining_length += len(will_properties) if username != None: username = username.encode("utf-8") remaining_length = remaining_length + 2+len(username) connect_flags = connect_flags | 0x80 if password != None: password = password.encode("utf-8") connect_flags = connect_flags | 0x40 remaining_length = remaining_length + 2+len(password) rl = pack_remaining_length(remaining_length) packet = struct.pack("!B"+str(len(rl))+"s", 0x10, rl) if (proto_ver&0x7F) == 3 or proto_ver == 0: packet = packet + struct.pack("!H6sBBH", len(b"MQIsdp"), b"MQIsdp", proto_ver, connect_flags, keepalive) elif (proto_ver&0x7F) == 4 or proto_ver == 5: packet = packet + struct.pack("!H4sBBH", len(b"MQTT"), b"MQTT", proto_ver, connect_flags, keepalive) if proto_ver == 5: packet += properties if client_id != None: packet = packet + struct.pack("!H"+str(len(client_id))+"s", len(client_id), bytes(client_id)) else: packet = packet + struct.pack("!H", 0) if will_topic != None: packet += will_properties packet = packet + struct.pack("!H"+str(len(will_topic))+"s", len(will_topic), will_topic) if len(will_payload) > 0: packet = packet + struct.pack("!H"+str(len(will_payload))+"s", len(will_payload), will_payload) else: packet = packet + struct.pack("!H", 0) if username != None: packet = packet + struct.pack("!H"+str(len(username))+"s", len(username), username) if password != None: packet = packet + struct.pack("!H"+str(len(password))+"s", len(password), password) return packet def gen_connack(flags=0, rc=0, proto_ver=4, properties=b""): if proto_ver == 5: if properties is not None: properties = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) + properties else: properties = b"" properties = mqtt5_props.prop_finalise(properties) packet = struct.pack('!BBBB', 32, 2+len(properties), flags, rc) + properties else: packet = struct.pack('!BBBB', 32, 2, flags, rc); return packet def gen_publish(topic, qos, payload=None, retain=False, dup=False, mid=0, proto_ver=4, properties=b""): topic = topic.encode("utf-8") rl = 2+len(topic) pack_format = "H"+str(len(topic))+"s" if qos > 0: rl = rl + 2 pack_format = pack_format + "H" if proto_ver == 5: properties = mqtt5_props.prop_finalise(properties) rl += len(properties) # This will break if len(properties) > 127 pack_format = pack_format + "%ds"%(len(properties)) if payload != None: payload = payload.encode("utf-8") rl = rl + len(payload) pack_format = pack_format + str(len(payload))+"s" else: payload = b"" pack_format = pack_format + "0s" rlpacked = pack_remaining_length(rl) cmd = 48 | (qos<<1) if retain: cmd = cmd + 1 if dup: cmd = cmd + 8 if proto_ver == 5: if qos > 0: return struct.pack("!B" + str(len(rlpacked))+"s" + pack_format, cmd, rlpacked, len(topic), topic, mid, properties, payload) else: return struct.pack("!B" + str(len(rlpacked))+"s" + pack_format, cmd, rlpacked, len(topic), topic, properties, payload) else: if qos > 0: return struct.pack("!B" + str(len(rlpacked))+"s" + pack_format, cmd, rlpacked, len(topic), topic, mid, payload) else: return struct.pack("!B" + str(len(rlpacked))+"s" + pack_format, cmd, rlpacked, len(topic), topic, payload) def _gen_command_with_mid(cmd, mid, proto_ver=4, reason_code=-1, properties=None): if proto_ver == 5 and (reason_code != -1 or properties is not None): if reason_code == -1: reason_code = 0 if properties is None: return struct.pack('!BBHB', cmd, 3, mid, reason_code) elif properties == "": return struct.pack('!BBHBB', cmd, 4, mid, reason_code, 0) else: properties = mqtt5_props.prop_finalise(properties) pack_format = "!BBHB"+str(len(properties))+"s" return struct.pack(pack_format, cmd, 2+1+len(properties), mid, reason_code, properties) else: return struct.pack('!BBH', cmd, 2, mid) def gen_puback(mid, proto_ver=4, reason_code=-1, properties=None): return _gen_command_with_mid(64, mid, proto_ver, reason_code, properties) def gen_pubrec(mid, proto_ver=4, reason_code=-1, properties=None): return _gen_command_with_mid(80, mid, proto_ver, reason_code, properties) def gen_pubrel(mid, dup=False, proto_ver=4, reason_code=-1, properties=None): if dup: cmd = 96+8+2 else: cmd = 96+2 return _gen_command_with_mid(cmd, mid, proto_ver, reason_code, properties) def gen_pubcomp(mid, proto_ver=4, reason_code=-1, properties=None): return _gen_command_with_mid(112, mid, proto_ver, reason_code, properties) def gen_subscribe(mid, topic, qos, proto_ver=4, properties=b""): topic = topic.encode("utf-8") packet = struct.pack("!B", 130) if proto_ver == 5: if properties == b"": packet += pack_remaining_length(2+1+2+len(topic)+1) pack_format = "!HBH"+str(len(topic))+"sB" return packet + struct.pack(pack_format, mid, 0, len(topic), topic, qos) else: properties = mqtt5_props.prop_finalise(properties) packet += pack_remaining_length(2+1+2+len(topic)+len(properties)) pack_format = "!H"+str(len(properties))+"s"+"H"+str(len(topic))+"sB" return packet + struct.pack(pack_format, mid, properties, len(topic), topic, qos) else: packet += pack_remaining_length(2+2+len(topic)+1) pack_format = "!HH"+str(len(topic))+"sB" return packet + struct.pack(pack_format, mid, len(topic), topic, qos) def gen_suback(mid, qos, proto_ver=4): if proto_ver == 5: return struct.pack('!BBHBB', 144, 2+1+1, mid, 0, qos) else: return struct.pack('!BBHB', 144, 2+1, mid, qos) def gen_unsubscribe(mid, topic, proto_ver=4): topic = topic.encode("utf-8") if proto_ver == 5: pack_format = "!BBHBH"+str(len(topic))+"s" return struct.pack(pack_format, 162, 2+2+len(topic)+1, mid, 0, len(topic), topic) else: pack_format = "!BBHH"+str(len(topic))+"s" return struct.pack(pack_format, 162, 2+2+len(topic), mid, len(topic), topic) def gen_unsubscribe_multiple(mid, topics, proto_ver=4): packet = b"" remaining_length = 0 for t in topics: t = t.encode("utf-8") remaining_length += 2+len(t) packet += struct.pack("!H"+str(len(t))+"s", len(t), t) if proto_ver == 5: remaining_length += 2+1 return struct.pack("!BBHB", 162, remaining_length, mid, 0) + packet else: remaining_length += 2 return struct.pack("!BBH", 162, remaining_length, mid) + packet def gen_unsuback(mid, proto_ver=4, reason_code=0): if proto_ver == 5: if isinstance(reason_code, list): reason_code_count = len(reason_code) p = struct.pack('!BBHB', 176, 3+reason_code_count, mid, 0) for r in reason_code: p += struct.pack('B', r) return p else: return struct.pack('!BBHBB', 176, 4, mid, 0, reason_code) else: return struct.pack('!BBH', 176, 2, mid) def gen_pingreq(): return struct.pack('!BB', 192, 0) def gen_pingresp(): return struct.pack('!BB', 208, 0) def _gen_short(cmd, reason_code=-1, proto_ver=5, properties=None): if proto_ver == 5 and (reason_code != -1 or properties is not None): if reason_code == -1: reason_code = 0 if properties is None: return struct.pack('!BBB', cmd, 1, reason_code) elif properties == "": return struct.pack('!BBBB', cmd, 2, reason_code, 0) else: properties = mqtt5_props.prop_finalise(properties) return struct.pack("!BBB", cmd, 1+len(properties), reason_code) + properties else: return struct.pack('!BB', cmd, 0) def gen_disconnect(reason_code=-1, proto_ver=4, properties=None): return _gen_short(0xE0, reason_code, proto_ver, properties) def gen_auth(reason_code=-1, properties=None): return _gen_short(0xF0, reason_code, 5, properties) def pack_remaining_length(remaining_length): s = b"" while True: byte = remaining_length % 128 remaining_length = remaining_length // 128 # If there are more digits to encode, set the top bit of this digit if remaining_length > 0: byte = byte | 0x80 s = s + struct.pack("!B", byte) if remaining_length == 0: return s def get_port(count=1): if count == 1: if len(sys.argv) == 2: return int(sys.argv[1]) else: return 1888 else: if len(sys.argv) == 1+count: p = () for i in range(0, count): p = p + (int(sys.argv[1+i]),) return p else: return tuple(range(1888, 1888+count)) def get_lib_port(): if len(sys.argv) == 3: return int(sys.argv[2]) else: return 1888 def do_ping(sock, error_string="pingresp"): do_send_receive(sock, gen_pingreq(), gen_pingresp(), error_string) @atexit.register def test_cleanup(): global vg_logfiles if os.environ.get('MOSQ_USE_VALGRIND') is not None: for f in vg_logfiles: try: if os.stat(f).st_size == 0: os.remove(f) except OSError: pass mosquitto-1.6.9/test/random/0000775000175000017500000000000013626052637015064 5ustar rogerrogermosquitto-1.6.9/test/random/random_client.py0000775000175000017500000001200113626052637020251 0ustar rogerroger#!/usr/bin/env python3 import paho.mqtt.client as paho import random import sys import time # This is a client that carries out randomised behaviour. It is intended for # use with the local config file. This file has multiple listeners configured: # * 1883 - unencrypted MQTT over TCP with no authentication # * 1884 - unencrypted MQTT over TCP with password authentication # * 1885 - unencrypted MQTT over TCP with plugin authentication # * 1886 - unencrypted MQTT over TCP with password and plugin authentication # # * 8883 - encrypted MQTT over TCP with no authentication # * 8884 - encrypted MQTT over TCP with password authentication # * 8885 - encrypted MQTT over TCP with plugin authentication # * 8886 - encrypted MQTT over TCP with password and plugin authentication # # * 8000 - unencrypted MQTT over WebSockets with no authentication # * 8001 - unencrypted MQTT over WebSockets with password authentication # * 8002 - unencrypted MQTT over WebSockets with plugin authentication # * 8003 - unencrypted MQTT over WebSockets with password and plugin authentication # # * 4430 - encrypted MQTT over WebSockets with no authentication # * 4431 - encrypted MQTT over WebSockets with password authentication # * 4432 - encrypted MQTT over WebSockets with plugin authentication # * 4433 - encrypted MQTT over WebSockets with password and plugin authentication # # The client randomly picks: # * A port out of the list # * Whether to use encryption # * Whether to use WebSockets # * Clean start or not # * Session expiry interval or not # * QoS to use when subscribing - topics "outgoing/[client id]/message" and "response/#" # * Lifetime of connection # On a per publish message basis it chooses: # * QoS of message # * Topic of message "outgoing/[0-max client]/message" # * Retain # * Interval until next outgoing message ports = [ {"port":1883, "tls":False, "transport":"tcp", "auth":False}, {"port":1884, "tls":False, "transport":"tcp", "auth":True}, {"port":1885, "tls":False, "transport":"tcp", "auth":True}, {"port":1886, "tls":False, "transport":"tcp", "auth":True}, {"port":8883, "tls":True, "transport":"tcp", "auth":False}, {"port":8884, "tls":True, "transport":"tcp", "auth":True}, {"port":8885, "tls":True, "transport":"tcp", "auth":True}, {"port":8886, "tls":True, "transport":"tcp", "auth":True}, {"port":8000, "tls":False, "transport":"websockets", "auth":False}, {"port":8001, "tls":False, "transport":"websockets", "auth":True}, {"port":8002, "tls":False, "transport":"websockets", "auth":True}, {"port":8003, "tls":False, "transport":"websockets", "auth":True}, {"port":4430, "tls":True, "transport":"websockets", "auth":False}, {"port":4431, "tls":True, "transport":"websockets", "auth":True}, {"port":4432, "tls":True, "transport":"websockets", "auth":True}, {"port":4433, "tls":True, "transport":"websockets", "auth":True}, ] booleans = [True, False] qos_values = [0, 1, 2] def on_connect(client, userdata, flags, rc): global running if rc == 0: client.subscribe("response/#", subscribe_qos) client.subscribe("outgoing/%s/message" % (client_id), subscribe_qos) else: running = False def on_message(client, userdata, msg): pass def on_publish(client, userdata, mid): pass def on_disconnect(client, userdata, rc): running = False def do_publish(client): retain = random.choice(booleans) qos = random.choice(qos_values) topic = "outgoing/%d/message" % (random.uniform(1, 1000)) payload = "message" client.publish(topic, payload, qos, retain) next_publish_time = time.time() + random.uniform(0.1, 2.0) def main(): global running global lifetime mqttc = paho.Client(client_id, clean_session=clean_start, protocol=protocol, transport=transport) mqttc.on_message = on_message mqttc.on_publish = on_publish mqttc.on_connect = on_connect mqttc.on_disconnect = on_disconnect if auth and random.choice(booleans): if random.choice(booleans): mqttc.username_pw_set("test", "password") else: mqttc.username_pw_set("bad", "bad") if use_tls: mqttc.tls_set(ca_certs="../ssl/all-ca.crt") mqttc.connect("localhost", port) mqttc.loop_start() while running: time.sleep(0.1) now = time.time() if now > next_publish_time: do_publish(mqttc) if now > lifetime: if random.choice(booleans): mqttc.disconnect() lifetime += 5.0 else: running = False p = random.choice(ports) port = p["port"] use_tls = p["tls"] transport = p["transport"] auth = p["auth"] client_id = "cid"+sys.argv[1] clean_start = random.choice(booleans) subscribe_qos = random.choice(qos_values) protocol = paho.MQTTv311 next_publish_time = time.time() + random.uniform(0.1, 2.0) lifetime = time.time() + random.uniform(5.0, 10.0) running = True main() mosquitto-1.6.9/test/random/auth_plugin.c0000664000175000017500000000257413626052637017557 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { srandom(time(NULL)); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { if(random() % 2 == 0){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { if(random() % 2 == 0){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/random/pwfile0000664000175000017500000000016213626052637016274 0ustar rogerrogertest:$6$cBP7e6sUriMSh8yf$+Z3E9P1g+Hui8zDJA+XJpTHl6+0eym0MtWokmOY4j1svAR5RtjZoXB4OQuHYzrGrdp1e8gXoqcKlcP+1lmepmg== mosquitto-1.6.9/test/random/test.py0000775000175000017500000000203513626052637016420 0ustar rogerroger#!/usr/bin/env python3 import subprocess import time import sys def next_client(clients): if len(clients) == 0: return c = clients.pop() args = ["./random_client.py", str(c)] proc = subprocess.Popen(args, stderr=subprocess.DEVNULL) proc.cid = c return proc def run_clients(max_clients): clients = list(range(1, max_clients)) start_time = time.time() running_clients = [] while True: print(len(running_clients)) if len(running_clients) < max_clients: c = next_client(clients) if c is not None: running_clients.append(c) else: time.sleep(0.1) for c in running_clients: c.poll() if c.returncode is not None: running_clients.remove(c) clients.append(c.cid) c.terminate() c.wait() env = {} env["LD_LIBRARY_PATH"] = "../../lib" #broker = subprocess.Popen(["../../src/mosquitto", "-c", "random.conf"], env=env) run_clients(1000) mosquitto-1.6.9/test/random/random.conf0000664000175000017500000000312513626052637017214 0ustar rogerrogerper_listener_settings true # Unencrypted MQTT over TCP listener 1883 listener 1884 password_file pwfile listener 1885 auth_plugin ./auth_plugin.so listener 1886 password_file pwfile auth_plugin ./auth_plugin.so # Encrypted MQTT over TCP listener 8883 cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key listener 8884 cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key password_file pwfile listener 8885 cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key auth_plugin ./auth_plugin.so listener 8886 cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key password_file pwfile auth_plugin ./auth_plugin.so # Unencrypted MQTT over WebSockets listener 8000 protocol websockets listener 8001 protocol websockets password_file pwfile listener 8002 protocol websockets auth_plugin ./auth_plugin.so listener 8003 protocol websockets password_file pwfile auth_plugin ./auth_plugin.so # Encrypted MQTT over WebSockets listener 4430 protocol websockets cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key listener 4431 protocol websockets cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key password_file pwfile listener 4432 protocol websockets cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key auth_plugin ./auth_plugin.so listener 4433 protocol websockets cafile ../ssl/all-ca.crt certfile ../ssl/server.crt keyfile ../ssl/server.key password_file pwfile auth_plugin ./auth_plugin.so #log_dest file mosquitto.log #log_type all mosquitto-1.6.9/test/random/Makefile0000664000175000017500000000074613626052637016533 0ustar rogerrogerinclude ../../config.mk .PHONY: all test ifeq ($(WITH_SHARED_LIBRARIES),yes) LIB_DEP:=../../lib/libmosquitto.so.${SOVERSION} else LIB_DEP:=../../lib/libmosquitto.a endif all : auth_plugin.so auth_plugin.so : auth_plugin.c $(CC) ${CFLAGS} -fPIC -shared $< -o $@ -I../../lib -I../../src ../lib/libmosquitto.so.${SOVERSION} : $(MAKE) -C ../../lib ../lib/libmosquitto.a : $(MAKE) -C ../../lib libmosquitto.a clean : -rm -f *.o random_client *.gcda *.gcno test : all ./test.py mosquitto-1.6.9/test/old/0000775000175000017500000000000013626052637014362 5ustar rogerrogermosquitto-1.6.9/test/old/msgsps_sub.c0000664000175000017500000000372213626052637016717 0ustar rogerroger/* This provides a crude manner of testing the performance of a broker in messages/s. */ #include #include #include #include #include #include #include static bool run = true; static int message_count = 0; static struct timeval start, stop; FILE *fptr = NULL; void my_connect_callback(struct mosquitto *mosq, void *obj, int rc) { printf("rc: %d\n", rc); } void my_disconnect_callback(struct mosquitto *mosq, void *obj, int result) { run = false; } void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { if(message_count == 0){ gettimeofday(&start, NULL); } //fwrite(msg->payload, sizeof(uint8_t), msg->payloadlen, fptr); message_count++; if(message_count == MESSAGE_COUNT){ gettimeofday(&stop, NULL); mosquitto_disconnect((struct mosquitto *)obj); } } int main(int argc, char *argv[]) { struct mosquitto *mosq; double dstart, dstop, diff; int mid = 0; char id[50]; start.tv_sec = 0; start.tv_usec = 0; stop.tv_sec = 0; stop.tv_usec = 0; fptr = fopen("msgsps_sub.dat", "wb"); if(!fptr){ printf("Error: Unable to write to msgsps_sub.dat.\n"); return 1; } mosquitto_lib_init(); snprintf(id, 50, "msgps_sub_%d", getpid()); mosq = mosquitto_new(id, true, NULL); mosquitto_connect_callback_set(mosq, my_connect_callback); mosquitto_disconnect_callback_set(mosq, my_disconnect_callback); mosquitto_message_callback_set(mosq, my_message_callback); mosquitto_connect(mosq, HOST, PORT, 600); mosquitto_subscribe(mosq, &mid, "perf/test", SUB_QOS); mosquitto_loop_forever(mosq, 10, 1); dstart = (double)start.tv_sec*1.0e6 + (double)start.tv_usec; dstop = (double)stop.tv_sec*1.0e6 + (double)stop.tv_usec; diff = (dstop-dstart)/1.0e6; printf("Start: %g\nStop: %g\nDiff: %g\nMessages/s: %g\n", dstart, dstop, diff, (double)MESSAGE_COUNT/diff); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); fclose(fptr); return 0; } mosquitto-1.6.9/test/old/msgsps_common.h0000664000175000017500000000021313626052637017413 0ustar rogerroger#define HOST "127.0.0.1" #define PORT 1888 #define PUB_QOS 1 #define SUB_QOS 1 #define MESSAGE_COUNT 100000L #define MESSAGE_SIZE 1024L mosquitto-1.6.9/test/old/msgsps_pub.c0000664000175000017500000000355313626052637016716 0ustar rogerroger/* This provides a crude manner of testing the performance of a broker in messages/s. */ #include #include #include #include #include #include #include static bool run = true; static int message_count = 0; static struct timeval start, stop; void my_connect_callback(struct mosquitto *mosq, void *obj, int rc) { printf("rc: %d\n", rc); gettimeofday(&start, NULL); } void my_disconnect_callback(struct mosquitto *mosq, void *obj, int result) { run = false; } void my_publish_callback(struct mosquitto *mosq, void *obj, int mid) { message_count++; if(message_count == MESSAGE_COUNT){ gettimeofday(&stop, NULL); mosquitto_disconnect((struct mosquitto *)obj); } } int main(int argc, char *argv[]) { struct mosquitto *mosq; int i; double dstart, dstop, diff; uint8_t *buf; buf = malloc(MESSAGE_SIZE*MESSAGE_COUNT); if(!buf){ printf("Error: Out of memory.\n"); return 1; } start.tv_sec = 0; start.tv_usec = 0; stop.tv_sec = 0; stop.tv_usec = 0; mosquitto_lib_init(); mosq = mosquitto_new("perftest", true, NULL); mosquitto_connect_callback_set(mosq, my_connect_callback); mosquitto_disconnect_callback_set(mosq, my_disconnect_callback); mosquitto_publish_callback_set(mosq, my_publish_callback); mosquitto_connect(mosq, HOST, PORT, 600); mosquitto_loop_start(mosq); i=0; for(i=0; i5", pubrec_packet, pubcomp_packet) mosquitto-1.6.9/test/lib/11-prop-recv-qos0.py0000775000175000017500000000317413626052637017750 0ustar rogerroger#!/usr/bin/env python3 # Check whether the v5 message callback gets the properties from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("prop-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "msg/123") publish_packet = mosq_test.gen_publish("prop/test", qos=0, payload="message", proto_ver=5, properties=props) ok_packet = mosq_test.gen_publish("ok", qos=0, payload="ok", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) conn.send(publish_packet) if mosq_test.expect_packet(conn, "ok", ok_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/08-ssl-connect-no-auth.py0000775000175000017500000000351713626052637020763 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect when using SSL. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id 08-ssl-connect-no-auth # It should use the CA certificate ssl/test-ca.crt for verifying the server. # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a DISCONNECT # message. If rc!=0, the client should exit with an error. from mosq_test_helper import * port = mosq_test.get_lib_port() if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("08-ssl-connect-no-auth", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/all-ca.crt", keyfile="../ssl/server.key", certfile="../ssl/server.crt", server_side=True) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = ssock.accept() conn.settimeout(100) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() ssock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos1-timeout.py0000775000175000017500000000501213626052637021624 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 1 and responds to a delay. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos1-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK the client should verify that rc==0. If not, it should exit with # return code=1. # On a successful CONNACK, the client should send a PUBLISH message with topic # "pub/qos1/test", payload "message" and QoS=1. # The test will not respond to the first PUBLISH message, so the client must # resend the PUBLISH message with dup=1. Note that to keep test durations low, a # message retry timeout of less than 10 seconds is required for this test. # On receiving the second PUBLISH message, the test will send the correct # PUBACK response. On receiving the correct PUBACK response, the client should # send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message") publish_packet_dup = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", dup=True) puback_packet = mosq_test.gen_puback(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): # Delay for > 3 seconds (message retry time) if mosq_test.expect_packet(conn, "dup publish", publish_packet_dup): conn.send(puback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-receive-maximum-2.py0000775000175000017500000001050313626052637023374 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client responds correctly to multiple PUBLISH with QoS 2, with # receive maximum set to 2. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 2) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 publish_1_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_1_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_1_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_1_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 2 publish_2_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_2_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_2_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_2_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 3 publish_3_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_3_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_3_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_3_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 4 publish_4_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_4_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_4_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_4_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 5 publish_5_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_5_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_5_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_5_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish 1", publish_1_packet): if mosq_test.expect_packet(conn, "publish 2", publish_2_packet): conn.send(pubrec_1_packet) conn.send(pubrec_2_packet) if mosq_test.expect_packet(conn, "pubrel 1", pubrel_1_packet): if mosq_test.expect_packet(conn, "pubrel 2", pubrel_2_packet): conn.send(pubcomp_1_packet) conn.send(pubcomp_2_packet) if mosq_test.expect_packet(conn, "publish 3", publish_3_packet): if mosq_test.expect_packet(conn, "publish 4", publish_4_packet): conn.send(pubrec_3_packet) conn.send(pubrec_4_packet) if mosq_test.expect_packet(conn, "pubrel 3", pubrel_3_packet): if mosq_test.expect_packet(conn, "pubrel 4", pubrel_4_packet): conn.send(pubcomp_3_packet) conn.send(pubcomp_4_packet) if mosq_test.expect_packet(conn, "publish 5", publish_5_packet): conn.send(pubrec_5_packet) if mosq_test.expect_packet(conn, "pubrel 5", pubrel_5_packet): conn.send(pubcomp_5_packet) rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/03-publish-qos0-no-payload.py0000775000175000017500000000347613626052637021550 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 0 and no payload. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos0-test-np # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a PUBLISH message # to topic "pub/qos0/no-payload/test" with zero length payload and QoS=0. If # rc!=0, the client should exit with an error. # After sending the PUBLISH message, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos0-test-np", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("pub/qos0/no-payload/test", qos=0) disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-b2c-qos2.py0000775000175000017500000000513413626052637020146 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client responds correctly to a PUBLISH with QoS 1. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos2-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK the client should verify that rc==0. # The test will send the client a PUBLISH message with topic # "pub/qos2/receive", payload of "message", QoS=2 and mid=13423. The client # should handle this as per the spec by sending a PUBREC message. # The test will not respond to the first PUBREC message, so the client must # resend the PUBREC message with dup=1. Note that to keep test durations low, a # message retry timeout of less than 10 seconds is required for this test. # On receiving the second PUBREC with dup==1, the test will send the correct # PUBREL message. The client should respond to this with the correct PUBCOMP # message and then exit with return code=0. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 13423 publish_packet = mosq_test.gen_publish("pub/qos2/receive", qos=2, mid=mid, payload="message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) conn.send(publish_packet) if mosq_test.expect_packet(conn, "pubrec", pubrec_packet): conn.send(pubrel_packet) if mosq_test.expect_packet(conn, "pubcomp", pubcomp_packet): rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/08-ssl-bad-cacert.py0000775000175000017500000000077313626052637017747 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) rc = 1 client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env) client.wait() rc = client.returncode exit(rc) mosquitto-1.6.9/test/lib/03-request-response.py0000775000175000017500000000520513626052637020475 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_lib_port() resp_topic = "response/topic" pub_topic = "request/topic" rc = 1 keepalive = 60 connect1_packet = mosq_test.gen_connect("request-test", keepalive=keepalive, proto_ver=5) connect2_packet = mosq_test.gen_connect("response-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, resp_topic, 0, proto_ver=5) subscribe2_packet = mosq_test.gen_subscribe(mid, pub_topic, 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, resp_topic) publish1_packet = mosq_test.gen_publish(pub_topic, qos=0, payload="action", proto_ver=5, properties=props) publish2_packet = mosq_test.gen_publish(resp_topic, qos=0, payload="a response", proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client1 = mosq_test.start_client(filename="03-request-response-1.log", cmd=["c/03-request-response-1.test"], env=env, port=port) try: (conn1, address) = sock.accept() conn1.settimeout(10) client2 = mosq_test.start_client(filename="03-request-response-2.log", cmd=["c/03-request-response-2.test"], env=env, port=port) (conn2, address) = sock.accept() conn2.settimeout(10) if mosq_test.expect_packet(conn1, "connect1", connect1_packet): conn1.send(connack_packet) if mosq_test.expect_packet(conn2, "connect2", connect2_packet): conn2.send(connack_packet) if mosq_test.expect_packet(conn1, "subscribe1", subscribe1_packet): conn1.send(suback_packet) if mosq_test.expect_packet(conn2, "subscribe2", subscribe2_packet): conn2.send(suback_packet) if mosq_test.expect_packet(conn1, "publish1", publish1_packet): conn2.send(publish1_packet) if mosq_test.expect_packet(conn2, "publish2", publish2_packet): rc = 0 conn1.close() conn2.close() finally: client1.terminate() client1.wait() client2.terminate() client2.wait() if rc: (stdo, stde) = client1.communicate() print(stde) (stdo, stde) = client2.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/09-util-topic-tokenise.py0000775000175000017500000000062613626052637021071 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * rc = 1 client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env) client.wait() exit(client.returncode) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2.py0000775000175000017500000000552013626052637020145 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 2. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos2-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK the client should verify that rc==0. If not, it should exit with # return code=1. # On a successful CONNACK, the client should send a PUBLISH message with topic # "pub/qos2/test", payload "message" and QoS=2. # The test will not respond to the first PUBLISH message, so the client must # resend the PUBLISH message with dup=1. Note that to keep test durations low, a # message retry timeout of less than 10 seconds is required for this test. # On receiving the second PUBLISH message, the test will send the correct # PUBREC response. On receiving the correct PUBREC response, the client should # send a PUBREL message. # The test will not respond to the first PUBREL message, so the client must # resend the PUBREL message with dup=1. On receiving the second PUBREL message, # the test will send the correct PUBCOMP response. On receiving the correct # PUBCOMP response, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message") publish_dup_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): conn.send(pubrec_packet) if mosq_test.expect_packet(conn, "pubrel", pubrel_packet): conn.send(pubcomp_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/11-prop-send-content-type.py0000775000175000017500000000274413626052637021513 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("prop-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "application/json") publish_packet = mosq_test.gen_publish("prop/qos0", qos=0, payload="message", proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/02-subscribe-qos1.py0000775000175000017500000000374613626052637020022 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct SUBSCRIBE to a topic with QoS 1. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id subscribe-qos1-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a SUBSCRIBE # message to subscribe to topic "qos1/test" with QoS=1. If rc!=0, the client # should exit with an error. # Upon receiving the correct SUBSCRIBE message, the test will reply with a # SUBACK message with the accepted QoS set to 1. On receiving the SUBACK # message, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "subscribe", subscribe_packet): conn.send(suback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/02-subscribe-qos2.py0000775000175000017500000000374613626052637020023 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct SUBSCRIBE to a topic with QoS 2. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id subscribe-qos2-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a SUBSCRIBE # message to subscribe to topic "qos2/test" with QoS=2. If rc!=0, the client # should exit with an error. # Upon receiving the correct SUBSCRIBE message, the test will reply with a # SUBACK message with the accepted QoS set to 2. On receiving the SUBACK # message, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/test", 2) suback_packet = mosq_test.gen_suback(mid, 2) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "subscribe", subscribe_packet): conn.send(suback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/08-ssl-connect-cert-auth-enc.py0000775000175000017500000000365313626052637022050 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect when using SSL. # Client must provide a certificate. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id 08-ssl-connect-crt-auth # It should use the CA certificate ssl/test-root-ca.crt for verifying the server. # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a DISCONNECT # message. If rc!=0, the client should exit with an error. from mosq_test_helper import * port = mosq_test.get_lib_port() if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("08-ssl-connect-crt-auth-enc", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/all-ca.crt", keyfile="../ssl/server.key", certfile="../ssl/server.crt", server_side=True, cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = ssock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() ssock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos1-len.py0000775000175000017500000000452613626052637020725 0ustar rogerroger#!/usr/bin/env python3 # Check whether a v5 client handles a v5 PUBACK with all combinations # of with/without reason code and properties. from mosq_test_helper import * def len_test(test, puback_packet): port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos1-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(15) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): conn.send(puback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() if rc != 0: print(test) exit(rc) # No reason code, no properties puback_packet = mosq_test.gen_puback(1) len_test("qos1 len 2", puback_packet) # Reason code, no properties puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00) len_test("qos1 len 3", puback_packet) # Reason code, empty properties puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00, properties="") len_test("qos1 len 4", puback_packet) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00, properties=props) len_test("qos1 len >5", puback_packet) mosquitto-1.6.9/test/lib/02-unsubscribe-v5.py0000775000175000017500000000276713626052637020036 0ustar rogerroger#!/usr/bin/env python3 # Test whether a v5 client sends a correct UNSUBSCRIBE packet, and handles the UNSUBACK. from mosq_test_helper import * port = mosq_test.get_lib_port() keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "unsubscribe/test", proto_ver=5) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "unsubscribe", unsubscribe_packet): conn.send(unsuback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/01-con-discon-success.py0000775000175000017500000000301313626052637020644 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id 01-con-discon-success # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a DISCONNECT # message. If rc!=0, the client should exit with an error. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("01-con-discon-success", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: #client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/08-ssl-connect-cert-auth.py0000775000175000017500000000364713626052637021310 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect when using SSL. # Client must provide a certificate. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id 08-ssl-connect-crt-auth # It should use the CA certificate ssl/test-root-ca.crt for verifying the server. # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a DISCONNECT # message. If rc!=0, the client should exit with an error. from mosq_test_helper import * port = mosq_test.get_lib_port() if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("08-ssl-connect-crt-auth", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/all-ca.crt", keyfile="../ssl/server.key", certfile="../ssl/server.crt", server_side=True, cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = ssock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() ssock.close() exit(rc) mosquitto-1.6.9/test/lib/c/0000775000175000017500000000000013626052637014574 5ustar rogerrogermosquitto-1.6.9/test/lib/c/02-unsubscribe-v5.c0000664000175000017500000000175313626052637020041 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_unsubscribe(mosq, NULL, "unsubscribe/test"); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("unsubscribe-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-len.c0000664000175000017500000000216613626052637020735 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "pub/qos2/test", strlen("message"), "message", 2, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { mosquitto_disconnect(mosq); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_v5_callback_set(mosq, on_publish); mosquitto_message_retry_set(mosq, 3); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-b2c-qos2.c0000664000175000017500000000250113626052637020152 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); } } void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { if(msg->mid != 13423){ printf("Invalid mid (%d)\n", msg->mid); exit(1); } if(msg->qos != 2){ printf("Invalid qos (%d)\n", msg->qos); exit(1); } if(strcmp(msg->topic, "pub/qos2/receive")){ printf("Invalid topic (%s)\n", msg->topic); exit(1); } if(strcmp(msg->payload, "message")){ printf("Invalid payload (%s)\n", (char *)msg->payload); exit(1); } if(msg->payloadlen != 7){ printf("Invalid payloadlen (%d)\n", msg->payloadlen); exit(1); } if(msg->retain != false){ printf("Invalid retain (%d)\n", msg->retain); exit(1); } run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, &run); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_message_callback_set(mosq, on_message); mosquitto_message_retry_set(mosq, 5); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2.c0000664000175000017500000000171313626052637020156 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "pub/qos2/test", strlen("message"), "message", 2, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-keepalive-pingreq.c0000664000175000017500000000113113626052637020562 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-keepalive-pingreq", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 5); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-pubrec-error.c0000664000175000017500000000221313626052637022557 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { if(rc){ exit(1); } mosquitto_publish_v5(mosq, NULL, "topic", strlen("rejected"), "rejected", 2, false, NULL); mosquitto_publish_v5(mosq, NULL, "topic", strlen("accepted"), "accepted", 2, false, NULL); } void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { if(mid == 2){ run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; mosquitto_property *props = NULL; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, &run); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_publish_v5_callback_set(mosq, on_publish); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); while(run == -1){ mosquitto_loop(mosq, 100, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos1-disconnect.c0000664000175000017500000000220013626052637022274 0ustar rogerroger#include #include #include #include #include static int run = -1; static int first_connection = 1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ if(first_connection == 1){ mosquitto_publish(mosq, NULL, "pub/qos1/test", strlen("message"), "message", 1, false); first_connection = 0; } } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ mosquitto_reconnect(mosq); }else{ run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos1-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); mosquitto_message_retry_set(mosq, 3); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-subscribe-qos1-async2.c0000664000175000017500000000266413626052637021226 0ustar rogerroger#include #include #include #include #include /* mosquitto_connect_async() test, with mosquitto_loop_start() called after mosquitto_connect_async(). */ static int run = -1; static bool should_run = true; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos1/test", 1); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { //mosquitto_disconnect(mosq); should_run = false; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("subscribe-qos1-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_subscribe_callback_set(mosq, on_subscribe); rc = mosquitto_connect_async(mosq, "localhost", port, 60); if(rc){ printf("connect_async failed: %s\n", mosquitto_strerror(rc)); } rc = mosquitto_loop_start(mosq); if(rc){ printf("loop_start failed: %s\n", mosquitto_strerror(rc)); } /* 50 millis to be system polite */ struct timespec tv = { 0, 50e6 }; while(should_run){ nanosleep(&tv, NULL); } mosquitto_disconnect(mosq); mosquitto_loop_stop(mosq, false); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-unsubscribe.c0000664000175000017500000000164113626052637017505 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_unsubscribe(mosq, NULL, "unsubscribe/test"); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("unsubscribe-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-unpwd-set.c0000664000175000017500000000077113626052637017111 0ustar rogerroger#include #include #include #include #include static int run = -1; int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-unpwd-set", true, NULL); mosquitto_username_pw_set(mosq, "uname", ";'[08gn=#"); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-b2c-qos2-len.c0000664000175000017500000000276713626052637020744 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); } } void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { if(msg->mid != 56){ printf("Invalid mid (%d)\n", msg->mid); exit(1); } if(msg->qos != 2){ printf("Invalid qos (%d)\n", msg->qos); exit(1); } if(strcmp(msg->topic, "len/qos2/test")){ printf("Invalid topic (%s)\n", msg->topic); exit(1); } if(strcmp(msg->payload, "message")){ printf("Invalid payload (%s)\n", (char *)msg->payload); exit(1); } if(msg->payloadlen != 7){ printf("Invalid payloadlen (%d)\n", msg->payloadlen); exit(1); } if(msg->retain != false){ printf("Invalid retain (%d)\n", msg->retain); exit(1); } mosquitto_disconnect(mosq); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, &run); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_message_callback_set(mosq, on_message); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 100, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-no-clean-session.c0000664000175000017500000000071113626052637020332 0ustar rogerroger#include #include #include #include #include static int run = -1; int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-no-clean-session", false, NULL); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-maximum-qos-1.c0000664000175000017500000000261513626052637022571 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ rc = mosquitto_publish(mosq, NULL, "maximum/qos/qos2", strlen("message"), "message", 2, false); if(rc != MOSQ_ERR_QOS_NOT_SUPPORTED) run = 1; rc = mosquitto_publish(mosq, NULL, "maximum/qos/qos1", strlen("message"), "message", 1, false); if(rc != MOSQ_ERR_SUCCESS) run = 1; rc = mosquitto_publish(mosq, NULL, "maximum/qos/qos0", strlen("message"), "message", 0, false); if(rc != MOSQ_ERR_SUCCESS) run = 1; } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == 2){ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 50, 1); } mosquitto_loop(mosq, 50, 1); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/11-prop-recv-qos0.c0000664000175000017500000000306513626052637017760 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; if(rc){ exit(1); } } void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { int rc; char *str; if(properties){ if(mosquitto_property_read_string(properties, MQTT_PROP_CONTENT_TYPE, &str, false)){ rc = strcmp(str, "plain/text"); free(str); if(rc == 0){ if(mosquitto_property_read_string(properties, MQTT_PROP_RESPONSE_TOPIC, &str, false)){ rc = strcmp(str, "msg/123"); free(str); if(rc == 0){ if(msg->qos == 0){ mosquitto_publish(mosq, NULL, "ok", 2, "ok", 0, 0); return; } } } } } } /* No matching message, so quit with an error */ exit(1); } void on_publish(struct mosquitto *mosq, void *obj, int mid) { run = 0; } int main(int argc, char *argv[]) { int rc; int tmp; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("prop-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_message_v5_callback_set(mosq, on_message_v5); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-con-discon-success.c0000664000175000017500000000141113626052637020655 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-con-discon-success", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/11-prop-recv-qos1.c0000664000175000017500000000306513626052637017761 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; if(rc){ exit(1); } } void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { int rc; char *str; if(properties){ if(mosquitto_property_read_string(properties, MQTT_PROP_CONTENT_TYPE, &str, false)){ rc = strcmp(str, "plain/text"); free(str); if(rc == 0){ if(mosquitto_property_read_string(properties, MQTT_PROP_RESPONSE_TOPIC, &str, false)){ rc = strcmp(str, "msg/123"); free(str); if(rc == 0){ if(msg->qos == 1){ mosquitto_publish(mosq, NULL, "ok", 2, "ok", 0, 0); return; } } } } } } /* No matching message, so quit with an error */ exit(1); } void on_publish(struct mosquitto *mosq, void *obj, int mid) { run = 0; } int main(int argc, char *argv[]) { int rc; int tmp; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("prop-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_message_v5_callback_set(mosq, on_message_v5); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos1-len.c0000664000175000017500000000207413626052637020732 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "pub/qos1/test", strlen("message"), "message", 1, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos1-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); mosquitto_message_retry_set(mosq, 3); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-subscribe-qos0.c0000664000175000017500000000167713626052637020033 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos0/test", 0); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("subscribe-qos0-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_subscribe_callback_set(mosq, on_subscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/08-ssl-bad-cacert.c0000664000175000017500000000063013626052637017750 0ustar rogerroger#include #include #include #include #include int main(int argc, char *argv[]) { int rc = 1; struct mosquitto *mosq; mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-bad-cacert", true, NULL); if(mosquitto_tls_set(mosq, "this/file/doesnt/exist", NULL, NULL, NULL, NULL) == MOSQ_ERR_INVAL){ rc = 0; } mosquitto_lib_cleanup(); return rc; } mosquitto-1.6.9/test/lib/c/11-prop-send-content-type.c0000664000175000017500000000225213626052637021516 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_string(&proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); mosquitto_publish_v5(mosq, &sent_mid, "prop/qos0", strlen("message"), "message", 0, false, proplist); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { int rc; int tmp; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("prop-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); tmp = MQTT_PROTOCOL_V5; mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &tmp); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/08-ssl-fake-cacert.c0000664000175000017500000000133113626052637020127 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { exit(1); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-crt-auth", true, NULL); mosquitto_tls_set(mosq, "../ssl/test-fake-root-ca.crt", NULL, "../ssl/client.crt", "../ssl/client.key", NULL); mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 60); rc = mosquitto_loop_forever(mosq, -1, 1); if(rc == MOSQ_ERR_ERRNO && errno == EPROTO){ return 0; }else{ return 1; } } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos1-receive-maximum.c0000664000175000017500000000213413626052637023246 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { int i; if(rc){ exit(1); } for(i=0; i<6; i++){ mosquitto_publish_v5(mosq, NULL, "topic", 5, "12345", 1, false, NULL); } } void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { if(mid == 6){ mosquitto_disconnect(mosq); run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; mosquitto_property *props = NULL; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos1-test", true, &run); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_publish_v5_callback_set(mosq, on_publish); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/08-ssl-connect-no-auth.c0000664000175000017500000000151113626052637020764 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-no-auth", true, NULL); mosquitto_tls_set(mosq, "../ssl/all-ca.crt", NULL, NULL, NULL, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/11-prop-oversize-packet.c0000664000175000017500000000315613626052637021255 0ustar rogerroger#include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ rc = mosquitto_subscribe(mosq, NULL, "0123456789012345678901234567890", 0); if(rc != MOSQ_ERR_OVERSIZE_PACKET){ printf("Fail on subscribe\n"); exit(1); } rc = mosquitto_unsubscribe(mosq, NULL, "0123456789012345678901234567890"); if(rc != MOSQ_ERR_OVERSIZE_PACKET){ printf("Fail on unsubscribe\n"); exit(1); } rc = mosquitto_publish(mosq, &sent_mid, "pub/test", strlen("0123456789012345678"), "0123456789012345678", 0, false); if(rc != MOSQ_ERR_OVERSIZE_PACKET){ printf("Fail on publish 1\n"); exit(1); } rc = mosquitto_publish(mosq, &sent_mid, "pub/test", strlen("012345678901234567"), "012345678901234567", 0, false); if(rc != MOSQ_ERR_SUCCESS){ printf("Fail on publish 2\n"); exit(1); } } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos0-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-receive-maximum-1.c0000664000175000017500000000213413626052637023405 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { int i; if(rc){ exit(1); } for(i=0; i<5; i++){ mosquitto_publish_v5(mosq, NULL, "topic", 5, "12345", 2, false, NULL); } } void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { if(mid == 5){ mosquitto_disconnect(mosq); run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; mosquitto_property *props = NULL; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, &run); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_publish_v5_callback_set(mosq, on_publish); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-request-response-2.c0000664000175000017500000000306513626052637020647 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "request/topic", 0); } } void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *props) { const mosquitto_property *p_resp, *p_corr = NULL; char *resp_topic = NULL; int rc; if(!strcmp(msg->topic, "request/topic")){ p_resp = mosquitto_property_read_string(props, MQTT_PROP_RESPONSE_TOPIC, &resp_topic, false); if(p_resp){ p_corr = mosquitto_property_read_binary(props, MQTT_PROP_CORRELATION_DATA, NULL, NULL, false); rc = mosquitto_publish_v5(mosq, NULL, resp_topic, strlen("a response"), "a response", 0, false, p_corr); free(resp_topic); } } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int ver = PROTOCOL_VERSION_v5; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("response-test", true, NULL); mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &ver); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); mosquitto_message_v5_callback_set(mosq, on_message_v5); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/08-ssl-connect-cert-auth.c0000664000175000017500000000157013626052637021312 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-crt-auth", true, NULL); mosquitto_tls_set(mosq, "../ssl/test-root-ca.crt", "../ssl/certs", "../ssl/client.crt", "../ssl/client.key", NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/11-prop-recv-qos2.c0000664000175000017500000000311713626052637017760 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; if(rc){ exit(1); } } void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { int rc; char *str; if(properties){ if(mosquitto_property_read_string(properties, MQTT_PROP_CONTENT_TYPE, &str, false)){ rc = strcmp(str, "plain/text"); free(str); if(rc == 0){ if(mosquitto_property_read_string(properties, MQTT_PROP_RESPONSE_TOPIC, &str, false)){ rc = strcmp(str, "msg/123"); free(str); if(rc == 0){ if(msg->qos == 2){ mosquitto_publish(mosq, NULL, "ok", 2, "ok", 0, 0); return; } } } } } } /* No matching message, so quit with an error */ exit(1); } void on_publish(struct mosquitto *mosq, void *obj, int mid) { run = 0; } int main(int argc, char *argv[]) { int rc; int tmp; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("prop-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_message_v5_callback_set(mosq, on_message_v5); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-receive-maximum-2.c0000664000175000017500000000213413626052637023406 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { int i; if(rc){ exit(1); } for(i=0; i<5; i++){ mosquitto_publish_v5(mosq, NULL, "topic", 5, "12345", 2, false, NULL); } } void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { if(mid == 5){ mosquitto_disconnect(mosq); run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; mosquitto_property *props = NULL; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, &run); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_publish_v5_callback_set(mosq, on_publish); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/04-retain-qos0.c0000664000175000017500000000130613626052637017323 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "retain/qos0/test", strlen("retained message"), "retained message", 0, true); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("retain-qos0-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-subscribe-qos1-async1.c0000664000175000017500000000271713626052637021224 0ustar rogerroger#include #include #include #include #include /* mosquitto_connect_async() test, with mosquitto_loop_start() called before mosquitto_connect_async(). */ static int run = -1; static bool should_run = true; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos1/test", 1); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { //mosquitto_disconnect(mosq); should_run = false; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("subscribe-qos1-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_subscribe_callback_set(mosq, on_subscribe); rc = mosquitto_loop_start(mosq); if(rc){ printf("loop_start failed: %s\n", mosquitto_strerror(rc)); return rc; } rc = mosquitto_connect_async(mosq, "localhost", port, 60); if(rc){ printf("connect_async failed: %s\n", mosquitto_strerror(rc)); return rc; } /* 50 millis to be system polite */ struct timespec tv = { 0, 50e6 }; while(should_run){ nanosleep(&tv, NULL); } mosquitto_disconnect(mosq); mosquitto_loop_stop(mosq, false); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-disconnect.c0000664000175000017500000000220013626052637022275 0ustar rogerroger#include #include #include #include #include static int run = -1; static int first_connection = 1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ if(first_connection == 1){ mosquitto_publish(mosq, NULL, "pub/qos2/test", strlen("message"), "message", 2, false); first_connection = 0; } } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ mosquitto_reconnect(mosq); }else{ run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); mosquitto_message_retry_set(mosq, 3); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-unsubscribe-multiple-v5.c0000664000175000017500000000237013626052637021666 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "unsubscribe/test", 2); } } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int sub_count, const int *subs) { char *unsubs[] = {"unsubscribe/test", "no-sub"}; mosquitto_unsubscribe_multiple(mosq, NULL, 2, unsubs, NULL); } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("unsubscribe-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_subscribe_callback_set(mosq, on_subscribe); mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-qos0-no-payload.c0000664000175000017500000000162413626052637021552 0ustar rogerroger#include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "pub/qos0/no-payload/test", 0, NULL, 0, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos0-test-np", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-request-response-1.c0000664000175000017500000000261113626052637020642 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "response/topic", 0); } } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_property *props = NULL; mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); mosquitto_publish_v5(mosq, NULL, "request/topic", 6, "action", 0, 0, props); mosquitto_property_free_all(&props); } void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { if(!strcmp(msg->payload, "a response")){ run = 0; }else{ run = 1; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int ver = PROTOCOL_VERSION_v5; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("request-test", true, NULL); mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &ver); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_subscribe_callback_set(mosq, on_subscribe); mosquitto_message_callback_set(mosq, on_message); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-will-unpwd-set.c0000664000175000017500000000114313626052637020050 0ustar rogerroger#include #include #include #include #include static int run = -1; int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-will-unpwd-set", true, NULL); mosquitto_username_pw_set(mosq, "oibvvwqw", "#'^2hg9a&nm38*us"); mosquitto_will_set(mosq, "will-topic", strlen("will message"), "will message", 2, false); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-server-keepalive-pingreq.c0000664000175000017500000000125313626052637022073 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-server-keepalive-pingreq", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-subscribe-qos1.c0000664000175000017500000000167713626052637020034 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos1/test", 1); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("subscribe-qos1-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_subscribe_callback_set(mosq, on_subscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/01-will-set.c0000664000175000017500000000105613626052637016720 0ustar rogerroger#include #include #include #include #include static int run = -1; int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-will-set", true, NULL); mosquitto_will_set(mosq, "topic/on/unexpected/disconnect", strlen("will message"), "will message", 1, true); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-b2c-qos1.c0000664000175000017500000000243713626052637020161 0ustar rogerroger#include #include #include #include #include void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); } } void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { if(msg->mid != 123){ printf("Invalid mid (%d)\n", msg->mid); exit(1); } if(msg->qos != 1){ printf("Invalid qos (%d)\n", msg->qos); exit(1); } if(strcmp(msg->topic, "pub/qos1/receive")){ printf("Invalid topic (%s)\n", msg->topic); exit(1); } if(strcmp(msg->payload, "message")){ printf("Invalid payload (%s)\n", (char *)msg->payload); exit(1); } if(msg->payloadlen != 7){ printf("Invalid payloadlen (%d)\n", msg->payloadlen); exit(1); } if(msg->retain != false){ printf("Invalid retain (%d)\n", msg->retain); exit(1); } exit(0); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos1-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_message_callback_set(mosq, on_message); mosquitto_message_retry_set(mosq, 3); rc = mosquitto_connect(mosq, "localhost", port, 60); while(1){ mosquitto_loop(mosq, 300, 1); } mosquitto_lib_cleanup(); return 1; } mosquitto-1.6.9/test/lib/c/03-publish-c2b-qos2-maximum-qos-0.c0000664000175000017500000000257113626052637022571 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ rc = mosquitto_publish(mosq, NULL, "maximum/qos/qos2", strlen("message"), "message", 2, false); if(rc != MOSQ_ERR_QOS_NOT_SUPPORTED) run = 1; rc = mosquitto_publish(mosq, NULL, "maximum/qos/qos1", strlen("message"), "message", 1, false); if(rc != MOSQ_ERR_QOS_NOT_SUPPORTED) run = 1; rc = mosquitto_publish(mosq, NULL, "maximum/qos/qos0", strlen("message"), "message", 0, false); if(rc != MOSQ_ERR_SUCCESS) run = 1; } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == 1){ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos2-test", true, NULL); mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, 50, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/03-publish-qos0.c0000664000175000017500000000164013626052637017507 0ustar rogerroger#include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "pub/qos0/test", strlen("message"), "message", 0, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("publish-qos0-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/09-util-topic-tokenise.c0000664000175000017500000000560213626052637021101 0ustar rogerroger#include #include #include void print_error(const char *topic, char **topics, int topic_count) { int i; printf("TOPIC: %s\n", topic); printf("TOKENS: "); for(i=0; i #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "response/topic", 0); } } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_property *props = NULL; mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); mosquitto_property_add_binary(&props, MQTT_PROP_CORRELATION_DATA, "corridor", 8); mosquitto_publish_v5(mosq, NULL, "request/topic", 6, "action", 0, 0, props); mosquitto_property_free_all(&props); } void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { if(!strcmp(msg->payload, "a response")){ run = 0; }else{ run = 1; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int ver = PROTOCOL_VERSION_v5; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("request-test", true, NULL); mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &ver); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_subscribe_callback_set(mosq, on_subscribe); mosquitto_message_callback_set(mosq, on_message); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/Makefile0000664000175000017500000000310713626052637016235 0ustar rogerroger.PHONY: all clean reallyclean CFLAGS=-I../../../lib -Werror LIBS=../../../lib/libmosquitto.so.1 SRC = \ 01-con-discon-success.c \ 01-will-set.c \ 01-unpwd-set.c \ 01-will-unpwd-set.c \ 01-no-clean-session.c \ 01-keepalive-pingreq.c \ 01-server-keepalive-pingreq.c \ 02-subscribe-qos0.c \ 02-subscribe-qos1.c \ 02-subscribe-qos1-async1.c \ 02-subscribe-qos1-async2.c \ 02-subscribe-qos2.c \ 02-unsubscribe.c \ 02-unsubscribe-v5.c \ 02-unsubscribe-multiple-v5.c \ 03-publish-qos0.c \ 03-publish-qos0-no-payload.c \ 03-publish-c2b-qos1-disconnect.c \ 03-publish-c2b-qos1-len.c \ 03-publish-c2b-qos2.c \ 03-publish-c2b-qos2-disconnect.c \ 03-publish-c2b-qos2-len.c \ 03-publish-b2c-qos2-len.c \ 03-publish-c2b-qos1-receive-maximum.c \ 03-publish-c2b-qos2-receive-maximum-1.c \ 03-publish-c2b-qos2-receive-maximum-2.c \ 03-publish-c2b-qos2-pubrec-error.c \ 03-publish-c2b-qos2-maximum-qos-0.c \ 03-publish-c2b-qos2-maximum-qos-1.c \ 03-publish-b2c-qos1.c \ 03-publish-b2c-qos2.c \ 03-request-response-1.c \ 03-request-response-2.c \ 03-request-response-correlation-1.c \ 04-retain-qos0.c \ 08-ssl-connect-no-auth.c \ 08-ssl-connect-cert-auth.c \ 08-ssl-connect-cert-auth-enc.c \ 08-ssl-bad-cacert.c \ 08-ssl-fake-cacert.c \ 09-util-topic-tokenise.c \ 11-prop-oversize-packet.c \ 11-prop-recv-qos0.c \ 11-prop-recv-qos1.c \ 11-prop-recv-qos2.c \ 11-prop-send-payload-format.c \ 11-prop-send-content-type.c TESTS = ${SRC:.c=.test} all : ${TESTS} ${TESTS} : %.test: %.c $(CC) $< -o $@ $(CFLAGS) $(LIBS) reallyclean : clean -rm -f *.orig clean : rm -f *.test mosquitto-1.6.9/test/lib/c/11-prop-send-payload-format.c0000664000175000017500000000224313626052637022004 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); mosquitto_publish_v5(mosq, &sent_mid, "prop/qos0", strlen("message"), "message", 0, false, proplist); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { int rc; int tmp; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("prop-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); tmp = MQTT_PROTOCOL_V5; mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &tmp); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/02-subscribe-qos2.c0000664000175000017500000000167713626052637020035 0ustar rogerroger#include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos2/test", 2); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("subscribe-qos2-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_subscribe_callback_set(mosq, on_subscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/c/08-ssl-connect-cert-auth-enc.c0000664000175000017500000000212013626052637022045 0ustar rogerroger#include #include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } static int password_callback(char* buf, int size, int rwflag, void* userdata) { strncpy(buf, "password", size); buf[size-1] = '\0'; return strlen(buf); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-crt-auth-enc", true, NULL); mosquitto_tls_set(mosq, "../ssl/test-root-ca.crt", "../ssl/certs", "../ssl/client-encrypted.crt", "../ssl/client-encrypted.key", password_callback); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/02-subscribe-qos0.py0000775000175000017500000000374613626052637020021 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct SUBSCRIBE to a topic with QoS 0. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id subscribe-qos0-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a SUBSCRIBE # message to subscribe to topic "qos0/test" with QoS=0. If rc!=0, the client # should exit with an error. # Upon receiving the correct SUBSCRIBE message, the test will reply with a # SUBACK message with the accepted QoS set to 0. On receiving the SUBACK # message, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "subscribe", subscribe_packet): conn.send(suback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/01-no-clean-session.py0000775000175000017500000000217413626052637020326 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect with clean session not set. # The client should connect to port 1888 with keepalive=60, clean session not # set, and client id 01-no-clean-session. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("01-no-clean-session", clean_session=False, keepalive=keepalive) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-timeout.py0000775000175000017500000000614613626052637021636 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 1 and responds to a delay. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos2-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK the client should verify that rc==0. If not, it should exit with # return code=1. # On a successful CONNACK, the client should send a PUBLISH message with topic # "pub/qos2/test", payload "message" and QoS=2. # The test will not respond to the first PUBLISH message, so the client must # resend the PUBLISH message with dup=1. Note that to keep test durations low, a # message retry timeout of less than 10 seconds is required for this test. # On receiving the second PUBLISH message, the test will send the correct # PUBREC response. On receiving the correct PUBREC response, the client should # send a PUBREL message. # The test will not respond to the first PUBREL message, so the client must # resend the PUBREL message with dup=1. On receiving the second PUBREL message, # the test will send the correct PUBCOMP response. On receiving the correct # PUBCOMP response, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message") publish_dup_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): # Delay for > 3 seconds (message retry time) if mosq_test.expect_packet(conn, "dup publish", publish_dup_packet): conn.send(pubrec_packet) if mosq_test.expect_packet(conn, "pubrel", pubrel_packet): if mosq_test.expect_packet(conn, "dup pubrel", pubrel_packet): conn.send(pubcomp_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/01-will-unpwd-set.py0000775000175000017500000000262513626052637020045 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect with a will, username and password. # The client should connect to port 1888 with keepalive=60, clean session set, # client id 01-will-unpwd-set , will topic set to "will-topic", will payload # set to "will message", will qos=2, will retain not set, username set to # "oibvvwqw" and password set to "#'^2hg9a&nm38*us". from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("01-will-unpwd-set", keepalive=keepalive, username="oibvvwqw", password="#'^2hg9a&nm38*us", will_topic="will-topic", will_qos=2, will_payload=b"will message") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-receive-maximum-1.py0000775000175000017500000001046213626052637023377 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client responds correctly to multiple PUBLISH with QoS 2, with # receive maximum set to 1. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 publish_1_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_1_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_1_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_1_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 2 publish_2_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_2_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_2_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_2_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 3 publish_3_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_3_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_3_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_3_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 4 publish_4_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_4_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_4_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_4_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 5 publish_5_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="12345", proto_ver=5) pubrec_5_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_5_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_5_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish 1", publish_1_packet): conn.send(pubrec_1_packet) if mosq_test.expect_packet(conn, "pubrel 1", pubrel_1_packet): conn.send(pubcomp_1_packet) if mosq_test.expect_packet(conn, "publish 2", publish_2_packet): conn.send(pubrec_2_packet) if mosq_test.expect_packet(conn, "pubrel 2", pubrel_2_packet): conn.send(pubcomp_2_packet) if mosq_test.expect_packet(conn, "publish 3", publish_3_packet): conn.send(pubrec_3_packet) if mosq_test.expect_packet(conn, "pubrel 3", pubrel_3_packet): conn.send(pubcomp_3_packet) if mosq_test.expect_packet(conn, "publish 4", publish_4_packet): conn.send(pubrec_4_packet) if mosq_test.expect_packet(conn, "pubrel 4", pubrel_4_packet): conn.send(pubcomp_4_packet) if mosq_test.expect_packet(conn, "publish 5", publish_5_packet): conn.send(pubrec_5_packet) if mosq_test.expect_packet(conn, "pubrel 5", pubrel_5_packet): conn.send(pubcomp_5_packet) rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/11-prop-oversize-packet.py0000775000175000017500000000344613626052637021246 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client publishing an oversize packet correctly. # The client should try to publish a message that is too big, then the one below which is ok. # It should also try to subscribe with a too large topic from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos0-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MAXIMUM_PACKET_SIZE, 30) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) bad_publish_packet = mosq_test.gen_publish("pub/test", qos=0, payload="0123456789012345678", proto_ver=5) publish_packet = mosq_test.gen_publish("pub/test", qos=0, payload="012345678901234567", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos1-receive-maximum.py0000775000175000017500000000636313626052637023245 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client responds correctly to multiple PUBLISH with QoS 1, with # receive maximum set to 3. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos1-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 3) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 publish_1_packet = mosq_test.gen_publish("topic", qos=1, mid=mid, payload="12345", proto_ver=5) puback_1_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 2 publish_2_packet = mosq_test.gen_publish("topic", qos=1, mid=mid, payload="12345", proto_ver=5) puback_2_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 3 publish_3_packet = mosq_test.gen_publish("topic", qos=1, mid=mid, payload="12345", proto_ver=5) puback_3_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 4 publish_4_packet = mosq_test.gen_publish("topic", qos=1, mid=mid, payload="12345", proto_ver=5) puback_4_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 5 publish_5_packet = mosq_test.gen_publish("topic", qos=1, mid=mid, payload="12345", proto_ver=5) puback_5_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 6 publish_6_packet = mosq_test.gen_publish("topic", qos=1, mid=mid, payload="12345", proto_ver=5) puback_6_packet = mosq_test.gen_puback(mid, proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish 1", publish_1_packet): if mosq_test.expect_packet(conn, "publish 2", publish_2_packet): if mosq_test.expect_packet(conn, "publish 3", publish_3_packet): conn.send(puback_1_packet) conn.send(puback_2_packet) if mosq_test.expect_packet(conn, "publish 4", publish_4_packet): if mosq_test.expect_packet(conn, "publish 5", publish_5_packet): conn.send(puback_3_packet) if mosq_test.expect_packet(conn, "publish 6", publish_6_packet): conn.send(puback_4_packet) conn.send(puback_5_packet) conn.send(puback_6_packet) rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/01-unpwd-set.py0000775000175000017500000000225713626052637017101 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect with a username and password. # The client should connect to port 1888 with keepalive=60, clean session set, # client id 01-unpwd-set, username set to uname and password set to ;'[08gn=# from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("01-unpwd-set", keepalive=keepalive, username="uname", password=";'[08gn=#") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/02-unsubscribe-multiple-v5.py0000775000175000017500000000352513626052637021660 0ustar rogerroger#!/usr/bin/env python3 # Test whether a v5 client sends a correct UNSUBSCRIBE packet with multiple # topics, and handles the UNSUBACK. from mosq_test_helper import * port = mosq_test.get_lib_port() keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "unsubscribe/test", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 2 unsubscribe_packet = mosq_test.gen_unsubscribe_multiple(mid, ["unsubscribe/test", "no-sub"], proto_ver=5) unsuback_packet = mosq_test.gen_unsuback(mid, reason_code=[0, 17], proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) rc = 1 try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "subscribe", subscribe_packet): conn.send(suback_packet) if mosq_test.expect_packet(conn, "unsubscribe", unsubscribe_packet): conn.send(unsuback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-qos0.py0000775000175000017500000000355713626052637017507 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 0. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos0-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a PUBLISH message # to topic "pub/qos0/test" with payload "message" and QoS=0. If rc!=0, the # client should exit with an error. # After sending the PUBLISH message, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("pub/qos0/test", qos=0, payload="message") disconnect_packet = mosq_test.gen_disconnect() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/02-unsubscribe.py0000775000175000017500000000264213626052637017476 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct UNSUBSCRIBE packet. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "unsubscribe/test") unsuback_packet = mosq_test.gen_unsuback(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "unsubscribe", unsubscribe_packet): conn.send(unsuback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/11-prop-recv-qos1.py0000775000175000017500000000342413626052637017747 0ustar rogerroger#!/usr/bin/env python3 # Check whether the v5 message callback gets the properties from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("prop-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "msg/123") publish_packet = mosq_test.gen_publish("prop/test", mid=mid, qos=1, payload="message", proto_ver=5, properties=props) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=5) ok_packet = mosq_test.gen_publish("ok", qos=0, payload="ok", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) conn.send(publish_packet) if mosq_test.expect_packet(conn, "puback", puback_packet): if mosq_test.expect_packet(conn, "ok", ok_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/mosq_test_helper.py0000664000175000017500000000064413626052637020305 0ustar rogerrogerimport inspect, os, sys # From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],".."))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) import mosq_test import mqtt5_props import socket import ssl import struct import subprocess import time mosquitto-1.6.9/test/lib/test.py0000775000175000017500000001161113626052637015706 0ustar rogerroger#!/usr/bin/env python3 import mosq_test_helper import ptest tests = [ (1, ['./01-con-discon-success.py', 'c/01-con-discon-success.test']), (1, ['./01-keepalive-pingreq.py', 'c/01-keepalive-pingreq.test']), (1, ['./01-no-clean-session.py', 'c/01-no-clean-session.test']), (1, ['./01-server-keepalive-pingreq.py', 'c/01-server-keepalive-pingreq.test']), (1, ['./01-unpwd-set.py', 'c/01-unpwd-set.test']), (1, ['./01-will-set.py', 'c/01-will-set.test']), (1, ['./01-will-unpwd-set.py', 'c/01-will-unpwd-set.test']), (1, ['./02-subscribe-qos0.py', 'c/02-subscribe-qos0.test']), (1, ['./02-subscribe-qos1.py', 'c/02-subscribe-qos1.test']), (1, ['./02-subscribe-qos1.py', 'c/02-subscribe-qos1-async1.test']), (1, ['./02-subscribe-qos1.py', 'c/02-subscribe-qos1-async2.test']), (1, ['./02-subscribe-qos2.py', 'c/02-subscribe-qos2.test']), (1, ['./02-unsubscribe-multiple-v5.py', 'c/02-unsubscribe-multiple-v5.test']), (1, ['./02-unsubscribe-v5.py', 'c/02-unsubscribe-v5.test']), (1, ['./02-unsubscribe.py', 'c/02-unsubscribe.test']), (1, ['./03-publish-b2c-qos1.py', 'c/03-publish-b2c-qos1.test']), (1, ['./03-publish-b2c-qos2-len.py', 'c/03-publish-b2c-qos2-len.test']), (1, ['./03-publish-b2c-qos2.py', 'c/03-publish-b2c-qos2.test']), (1, ['./03-publish-c2b-qos1-disconnect.py', 'c/03-publish-c2b-qos1-disconnect.test']), (1, ['./03-publish-c2b-qos1-len.py', 'c/03-publish-c2b-qos1-len.test']), (1, ['./03-publish-c2b-qos1-receive-maximum.py', 'c/03-publish-c2b-qos1-receive-maximum.test']), (1, ['./03-publish-c2b-qos2-disconnect.py', 'c/03-publish-c2b-qos2-disconnect.test']), (1, ['./03-publish-c2b-qos2-len.py', 'c/03-publish-c2b-qos2-len.test']), (1, ['./03-publish-c2b-qos2-maximum-qos-0.py', 'c/03-publish-c2b-qos2-maximum-qos-0.test']), (1, ['./03-publish-c2b-qos2-maximum-qos-1.py', 'c/03-publish-c2b-qos2-maximum-qos-1.test']), (1, ['./03-publish-c2b-qos2-pubrec-error.py', 'c/03-publish-c2b-qos2-pubrec-error.test']), (1, ['./03-publish-c2b-qos2-receive-maximum-1.py', 'c/03-publish-c2b-qos2-receive-maximum-1.test']), (1, ['./03-publish-c2b-qos2-receive-maximum-2.py', 'c/03-publish-c2b-qos2-receive-maximum-2.test']), (1, ['./03-publish-c2b-qos2.py', 'c/03-publish-c2b-qos2.test']), (1, ['./03-publish-qos0-no-payload.py', 'c/03-publish-qos0-no-payload.test']), (1, ['./03-publish-qos0.py', 'c/03-publish-qos0.test']), (1, ['./03-request-response-correlation.py', 'c/03-request-response-correlation.test']), (1, ['./03-request-response.py', 'c/03-request-response.test']), (1, ['./04-retain-qos0.py', 'c/04-retain-qos0.test']), (1, ['./08-ssl-bad-cacert.py', 'c/08-ssl-bad-cacert.test']), (1, ['./08-ssl-connect-cert-auth-enc.py', 'c/08-ssl-connect-cert-auth-enc.test']), (1, ['./08-ssl-connect-cert-auth.py', 'c/08-ssl-connect-cert-auth.test']), (1, ['./08-ssl-connect-no-auth.py', 'c/08-ssl-connect-no-auth.test']), (1, ['./09-util-topic-tokenise.py', 'c/09-util-topic-tokenise.test']), (1, ['./11-prop-oversize-packet.py', 'c/11-prop-oversize-packet.test']), (1, ['./11-prop-send-content-type.py', 'c/11-prop-send-content-type.test']), (1, ['./11-prop-send-payload-format.py', 'c/11-prop-send-payload-format.test']), (1, ['./01-con-discon-success.py', 'cpp/01-con-discon-success.test']), (1, ['./01-keepalive-pingreq.py', 'cpp/01-keepalive-pingreq.test']), (1, ['./01-no-clean-session.py', 'cpp/01-no-clean-session.test']), (1, ['./01-unpwd-set.py', 'cpp/01-unpwd-set.test']), (1, ['./01-will-set.py', 'cpp/01-will-set.test']), (1, ['./01-will-unpwd-set.py', 'cpp/01-will-unpwd-set.test']), (1, ['./02-subscribe-qos0.py', 'cpp/02-subscribe-qos0.test']), (1, ['./02-subscribe-qos1.py', 'cpp/02-subscribe-qos1.test']), (1, ['./02-subscribe-qos2.py', 'cpp/02-subscribe-qos2.test']), (1, ['./02-unsubscribe.py', 'cpp/02-unsubscribe.test']), (1, ['./03-publish-b2c-qos1.py', 'cpp/03-publish-b2c-qos1.test']), (1, ['./03-publish-b2c-qos2.py', 'cpp/03-publish-b2c-qos2.test']), (1, ['./03-publish-c2b-qos1-disconnect.py', 'cpp/03-publish-c2b-qos1-disconnect.test']), (1, ['./03-publish-c2b-qos2-disconnect.py', 'cpp/03-publish-c2b-qos2-disconnect.test']), (1, ['./03-publish-c2b-qos2.py', 'cpp/03-publish-c2b-qos2.test']), (1, ['./03-publish-qos0-no-payload.py', 'cpp/03-publish-qos0-no-payload.test']), (1, ['./03-publish-qos0.py', 'cpp/03-publish-qos0.test']), (1, ['./04-retain-qos0.py', 'cpp/04-retain-qos0.test']), (1, ['./08-ssl-bad-cacert.py', 'cpp/08-ssl-bad-cacert.test']), (1, ['./08-ssl-connect-cert-auth-enc.py', 'cpp/08-ssl-connect-cert-auth-enc.test']), (1, ['./08-ssl-connect-cert-auth.py', 'cpp/08-ssl-connect-cert-auth.test']), (1, ['./08-ssl-connect-no-auth.py', 'cpp/08-ssl-connect-no-auth.test']), (1, ['./09-util-topic-tokenise.py', 'cpp/09-util-topic-tokenise.test']), ] ptest.run_tests(tests) mosquitto-1.6.9/test/lib/03-publish-c2b-qos1-disconnect.py0000775000175000017500000000371013626052637022272 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 1, then responds correctly to a disconnect. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message") publish_packet_dup = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", dup=True) puback_packet = mosq_test.gen_puback(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(15) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): # Disconnect client. It should reconnect. conn.close() (conn, address) = sock.accept() conn.settimeout(15) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "retried publish", publish_packet_dup): conn.send(puback_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/cpp/0000775000175000017500000000000013626052637015134 5ustar rogerrogermosquitto-1.6.9/test/lib/cpp/03-publish-b2c-qos2.cpp0000664000175000017500000000260713626052637021061 0ustar rogerroger#include #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_message(const struct mosquitto_message *msg); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); } } void mosquittopp_test::on_message(const struct mosquitto_message *msg) { if(msg->mid != 13423){ printf("Invalid mid (%d)\n", msg->mid); exit(1); } if(msg->qos != 2){ printf("Invalid qos (%d)\n", msg->qos); exit(1); } if(strcmp(msg->topic, "pub/qos2/receive")){ printf("Invalid topic (%s)\n", msg->topic); exit(1); } if(strcmp((char *)msg->payload, "message")){ printf("Invalid payload (%s)\n", (char *)msg->payload); exit(1); } if(msg->payloadlen != 7){ printf("Invalid payloadlen (%d)\n", msg->payloadlen); exit(1); } if(msg->retain != false){ printf("Invalid retain (%d)\n", msg->retain); exit(1); } run = 0; } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->message_retry_set(3); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/02-unsubscribe.cpp0000664000175000017500000000153213626052637020404 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_unsubscribe(int mid); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ unsubscribe(NULL, "unsubscribe/test"); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_unsubscribe(int mid) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("unsubscribe-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/08-ssl-bad-cacert.cpp0000664000175000017500000000103713626052637020652 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int rc = 1; mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-bad-cacert"); mosq->tls_opts_set(1, "tlsv1", NULL); if(mosq->tls_set("this/file/doesnt/exist") == MOSQ_ERR_INVAL){ rc = 0; } mosqpp::lib_cleanup(); return rc; } mosquitto-1.6.9/test/lib/cpp/08-ssl-fake-cacert.cpp0000664000175000017500000000144313626052637021033 0ustar rogerroger#include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { exit(1); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int rc; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-fake-cacert"); mosq->tls_opts_set(1, "tlsv1", NULL); mosq->tls_set("../ssl/test-fake-root-ca.crt", NULL, "../ssl/client.crt", "../ssl/client.key"); mosq->connect("localhost", port, 60); rc = mosq->loop_forever(); if(rc == MOSQ_ERR_ERRNO && errno == EPROTO){ return 0; }else{ return 1; } } mosquitto-1.6.9/test/lib/cpp/03-publish-qos0-no-payload.cpp0000664000175000017500000000156213626052637022453 0ustar rogerroger#include #include static int run = -1; static int sent_mid = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_publish(int mid); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ publish(&sent_mid, "pub/qos0/no-payload/test", 0, NULL, 0, false); } } void mosquittopp_test::on_publish(int mid) { if(sent_mid == mid){ disconnect(); }else{ exit(1); } } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos0-test-np"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/03-publish-c2b-qos1-disconnect.cpp0000664000175000017500000000207013626052637023201 0ustar rogerroger#include #include #include static int run = -1; static int first_connection = 1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_publish(int mid); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ if(first_connection == 1){ publish(NULL, "pub/qos1/test", strlen("message"), "message", 1, false); first_connection = 0; } } } void mosquittopp_test::on_disconnect(int rc) { if(rc){ reconnect(); }else{ run = 0; } } void mosquittopp_test::on_publish(int mid) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->message_retry_set(3); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/09-util-topic-tokenise.cpp0000664000175000017500000000554513626052637022007 0ustar rogerroger#include #include #include void print_error(const char *topic, char **topics, int topic_count) { int i; printf("TOPIC: %s\n", topic); printf("TOKENS: "); for(i=0; i static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-crt-auth"); mosq->tls_opts_set(1, "tlsv1", NULL); //mosq->tls_set("../ssl/test-ca.crt", NULL, "../ssl/client.crt", "../ssl/client.key"); mosq->tls_set("../ssl/all-ca.crt", NULL, "../ssl/client.crt", "../ssl/client.key"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/08-ssl-connect-cert-auth-enc.cpp0000664000175000017500000000222713626052637022755 0ustar rogerroger#include #include static int run = -1; static int password_callback(char* buf, int size, int rwflag, void* userdata) { strncpy(buf, "password", size); buf[size-1] = '\0'; return strlen(buf); } class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-crt-auth-enc"); mosq->tls_opts_set(1, "tlsv1", NULL); //mosq->tls_set("../ssl/test-ca.crt", NULL, "../ssl/client.crt", "../ssl/client.key"); mosq->tls_set("../ssl/all-ca.crt", NULL, "../ssl/client-encrypted.crt", "../ssl/client-encrypted.key", password_callback); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/02-subscribe-qos2.cpp0000664000175000017500000000164213626052637020725 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_subscribe(int mid, int qos_count, const int *granted_qos); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ subscribe(NULL, "qos2/test", 2); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("subscribe-qos2-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/03-publish-c2b-qos2.cpp0000664000175000017500000000163313626052637021057 0ustar rogerroger#include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_publish(int mid); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ publish(NULL, "pub/qos2/test", strlen("message"), "message", 2, false); } } void mosquittopp_test::on_disconnect(int rc) { run = 0; } void mosquittopp_test::on_publish(int mid) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/01-will-set.cpp0000664000175000017500000000127413626052637017622 0ustar rogerroger//#include //#include //#include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-will-set"); mosq->will_set("topic/on/unexpected/disconnect", strlen("will message"), "will message", 1, true); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/03-publish-b2c-qos1.cpp0000664000175000017500000000254513626052637021061 0ustar rogerroger#include #include #include #include class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_message(const struct mosquitto_message *msg); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); } } void mosquittopp_test::on_message(const struct mosquitto_message *msg) { if(msg->mid != 123){ printf("Invalid mid (%d)\n", msg->mid); exit(1); } if(msg->qos != 1){ printf("Invalid qos (%d)\n", msg->qos); exit(1); } if(strcmp(msg->topic, "pub/qos1/receive")){ printf("Invalid topic (%s)\n", msg->topic); exit(1); } if(strcmp((char *)msg->payload, "message")){ printf("Invalid payload (%s)\n", (char *)msg->payload); exit(1); } if(msg->payloadlen != 7){ printf("Invalid payloadlen (%d)\n", msg->payloadlen); exit(1); } if(msg->retain != false){ printf("Invalid retain (%d)\n", msg->retain); exit(1); } exit(0); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->message_retry_set(3); mosq->connect("localhost", port, 60); while(1){ mosq->loop(); } mosqpp::lib_cleanup(); return 1; } mosquitto-1.6.9/test/lib/cpp/01-con-discon-success.cpp0000664000175000017500000000144513626052637021564 0ustar rogerroger//#include //#include //#include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-con-discon-success"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/08-ssl-connect-no-auth.cpp0000664000175000017500000000153613626052637021673 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-no-auth"); mosq->tls_opts_set(1, "tlsv1", NULL); //mosq->tls_set("../ssl/test-root-ca.crt"); mosq->tls_set("../ssl/all-ca.crt"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/03-publish-c2b-qos2-disconnect.cpp0000664000175000017500000000207013626052637023202 0ustar rogerroger#include #include #include static int run = -1; static int first_connection = 1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_publish(int mid); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ if(first_connection == 1){ publish(NULL, "pub/qos2/test", strlen("message"), "message", 2, false); first_connection = 0; } } } void mosquittopp_test::on_disconnect(int rc) { if(rc){ reconnect(); }else{ run = 0; } } void mosquittopp_test::on_publish(int mid) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->message_retry_set(3); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/01-will-unpwd-set.cpp0000664000175000017500000000124613626052637020754 0ustar rogerroger#include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-will-unpwd-set"); mosq->username_pw_set("oibvvwqw", "#'^2hg9a&nm38*us"); mosq->will_set("will-topic", strlen("will message"), "will message", 2, false); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/01-keepalive-pingreq.cpp0000664000175000017500000000115613626052637021471 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); } } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-keepalive-pingreq"); mosq->connect("localhost", port, 5); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/03-publish-qos0.cpp0000664000175000017500000000157113626052637020412 0ustar rogerroger#include #include static int run = -1; static int sent_mid = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_publish(int mid); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ publish(&sent_mid, "pub/qos0/test", strlen("message"), "message", 0, false); } } void mosquittopp_test::on_publish(int mid) { if(sent_mid == mid){ disconnect(); }else{ exit(1); } } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos0-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/02-subscribe-qos0.cpp0000664000175000017500000000164113626052637020722 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_subscribe(int mid, int qos_count, const int *granted_qos); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ subscribe(NULL, "qos0/test", 0); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("subscribe-qos0-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/04-retain-qos0.cpp0000664000175000017500000000134513626052637020226 0ustar rogerroger#include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ publish(NULL, "retain/qos0/test", strlen("retained message"), "retained message", 0, true); } } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("retain-qos0-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/01-no-clean-session.cpp0000664000175000017500000000113513626052637021233 0ustar rogerroger#include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id, bool clean_session); }; mosquittopp_test::mosquittopp_test(const char *id, bool clean_session) : mosqpp::mosquittopp(id, clean_session) { } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-no-clean-session", false); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/02-subscribe-qos1.cpp0000664000175000017500000000164213626052637020724 0ustar rogerroger#include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_disconnect(int rc); void on_subscribe(int mid, int qos_count, const int *granted_qos); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ subscribe(NULL, "qos1/test", 1); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { disconnect(); } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("subscribe-qos1-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/01-unpwd-set.cpp0000664000175000017500000000110613626052637020002 0ustar rogerroger#include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } int main(int argc, char *argv[]) { struct mosquittopp_test *mosq; int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-unpwd-set"); mosq->username_pw_set("uname", ";'[08gn=#"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } mosqpp::lib_cleanup(); return run; } mosquitto-1.6.9/test/lib/cpp/Makefile0000664000175000017500000000571413626052637016603 0ustar rogerroger.PHONY: all test 01 02 03 04 08 09 clean reallyclean CFLAGS=-I../../../lib -I../../../lib/cpp -DDEBUG LIBS=../../../lib/libmosquitto.so.1 ../../../lib/cpp/libmosquittopp.so.1 all : 01 02 03 04 08 09 01-con-discon-success.test : 01-con-discon-success.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 01-will-set.test : 01-will-set.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 01-unpwd-set.test : 01-unpwd-set.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 01-will-unpwd-set.test : 01-will-unpwd-set.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 01-no-clean-session.test : 01-no-clean-session.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 01-keepalive-pingreq.test : 01-keepalive-pingreq.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 02-subscribe-qos0.test : 02-subscribe-qos0.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 02-subscribe-qos1.test : 02-subscribe-qos1.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 02-subscribe-qos2.test : 02-subscribe-qos2.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 02-unsubscribe.test : 02-unsubscribe.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-qos0.test : 03-publish-qos0.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-qos0-no-payload.test : 03-publish-qos0-no-payload.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-c2b-qos1-disconnect.test : 03-publish-c2b-qos1-disconnect.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-c2b-qos2.test : 03-publish-c2b-qos2.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-c2b-qos2-disconnect.test : 03-publish-c2b-qos2-disconnect.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-b2c-qos1.test : 03-publish-b2c-qos1.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 03-publish-b2c-qos2.test : 03-publish-b2c-qos2.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 04-retain-qos0.test : 04-retain-qos0.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 08-ssl-connect-no-auth.test : 08-ssl-connect-no-auth.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 08-ssl-connect-cert-auth.test : 08-ssl-connect-cert-auth.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 08-ssl-connect-cert-auth-enc.test : 08-ssl-connect-cert-auth-enc.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 08-ssl-bad-cacert.test : 08-ssl-bad-cacert.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 08-ssl-fake-cacert.test : 08-ssl-fake-cacert.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 09-util-topic-tokenise.test : 09-util-topic-tokenise.cpp $(CXX) $< -o $@ $(CFLAGS) $(LIBS) 01 : 01-con-discon-success.test 01-will-set.test 01-unpwd-set.test 01-will-unpwd-set.test 01-no-clean-session.test 01-keepalive-pingreq.test 02 : 02-subscribe-qos0.test 02-subscribe-qos1.test 02-subscribe-qos2.test 02-unsubscribe.test 03 : 03-publish-qos0.test 03-publish-qos0-no-payload.test 03-publish-c2b-qos1-disconnect.test 03-publish-c2b-qos2.test 03-publish-c2b-qos2-disconnect.test 03-publish-b2c-qos1.test 03-publish-b2c-qos2.test 04 : 04-retain-qos0.test 08 : 08-ssl-connect-no-auth.test 08-ssl-connect-cert-auth.test 08-ssl-connect-cert-auth-enc.test 08-ssl-bad-cacert.test 08-ssl-fake-cacert.test 09 : 09-util-topic-tokenise.test reallyclean : clean -rm -f *.orig clean : rm -f *.test mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-pubrec-error.py0000775000175000017500000000466713626052637022565 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client responds correctly when sending multiple PUBLISH with # QoS 2, with the broker rejecting the first PUBLISH by setting the reason code # in PUBACK to >= 0x80. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 publish_1_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="rejected", proto_ver=5) pubrec_1_packet = mosq_test.gen_pubrec(mid, proto_ver=5, reason_code=0x80) mid = 2 publish_2_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="accepted", proto_ver=5) pubrec_2_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_2_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_2_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish 1", publish_1_packet): conn.send(pubrec_1_packet) if mosq_test.expect_packet(conn, "publish 2", publish_2_packet): conn.send(pubrec_2_packet) if mosq_test.expect_packet(conn, "pubrel 2", pubrel_2_packet): conn.send(pubcomp_2_packet) rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/11-prop-recv-qos2.py0000775000175000017500000000400213626052637017741 0ustar rogerroger#!/usr/bin/env python3 # Check whether the v5 message callback gets the properties from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("prop-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "msg/123") publish_packet = mosq_test.gen_publish("prop/test", mid=mid, qos=2, payload="message", proto_ver=5, properties=props) pubrec_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=5) pubrel_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=5) pubcomp_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=5) ok_packet = mosq_test.gen_publish("ok", qos=0, payload="ok", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) conn.send(publish_packet) if mosq_test.expect_packet(conn, "pubrec", pubrec_packet): conn.send(pubrel_packet) if mosq_test.expect_packet(conn, "pubcomp", pubcomp_packet): if mosq_test.expect_packet(conn, "ok", ok_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-b2c-qos1.py0000775000175000017500000000402413626052637020142 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client responds correctly to a PUBLISH with QoS 1. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos1-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK the client should verify that rc==0. # The test will send the client a PUBLISH message with topic # "pub/qos1/receive", payload of "message", QoS=1 and mid=123. The client # should handle this as per the spec by sending a PUBACK message. # The client should then exit with return code==0. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 123 publish_packet = mosq_test.gen_publish("pub/qos1/receive", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) conn.send(publish_packet) if mosq_test.expect_packet(conn, "puback", puback_packet): rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-maximum-qos-0.py0000775000175000017500000000336613626052637022563 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client correctly handles sending a message with QoS > maximum QoS. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_MAXIMUM_QOS, 0) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) publish_1_packet = mosq_test.gen_publish("maximum/qos/qos0", qos=0, payload="message", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish 1", publish_1_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/11-prop-send-payload-format.py0000775000175000017500000000377213626052637022003 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 0. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos0-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK and verifying that rc=0, the client should send a PUBLISH message # to topic "pub/qos0/test" with payload "message" and QoS=0. If rc!=0, the # client should exit with an error. # After sending the PUBLISH message, the client should send a DISCONNECT message. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("prop-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 0x01) publish_packet = mosq_test.gen_publish("prop/qos0", qos=0, payload="message", proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-1.6.9/test/lib/08-ssl-fake-cacert.py0000775000175000017500000000224413626052637020122 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_lib_port() if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/all-ca.crt", keyfile="../ssl/server.key", certfile="../ssl/server.crt", server_side=True, cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = ssock.accept() conn.close() except ssl.SSLError: # Expected error due to ca certs not matching. pass finally: time.sleep(1.0) try: client.terminate() except OSError: pass client.wait() ssock.close() if client.returncode == 0: exit(0) else: exit(1) mosquitto-1.6.9/test/lib/03-publish-b2c-qos2-len.py0000775000175000017500000000500413626052637020716 0ustar rogerroger#!/usr/bin/env python3 # Check whether a v5 client handles a v5 PUBREL with all combinations # of with/without reason code and properties. from mosq_test_helper import * mid = 56 def len_test(test, pubrel_packet): port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) publish_packet = mosq_test.gen_publish("len/qos2/test", qos=2, mid=mid, payload="message", proto_ver=5) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(15) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) mosq_test.do_send_receive(conn, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(conn, pubrel_packet, pubcomp_packet, "pubcomp") if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() if rc != 0: print(test) exit(rc) # No reason code, no properties pubrel_packet = mosq_test.gen_pubrel(mid) len_test("qos2 len 2", pubrel_packet) # Reason code, no properties pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=5, reason_code=0x00) len_test("qos2 len 3", pubrel_packet) # Reason code, empty properties pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=5, reason_code=0x00, properties="") len_test("qos2 len 4", pubrel_packet) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=5, reason_code=0x00, properties=props) len_test("qos2 len >5", pubrel_packet) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-disconnect.py0000775000175000017500000000525313626052637022277 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 2 and responds to a disconnect. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mid = 1 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message") publish_dup_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): # Disconnect client. It should reconnect. conn.close() (conn, address) = sock.accept() conn.settimeout(15) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "retried publish", publish_dup_packet): conn.send(pubrec_packet) if mosq_test.expect_packet(conn, "pubrel", pubrel_packet): # Disconnect client. It should reconnect. conn.close() (conn, address) = sock.accept() conn.settimeout(15) # Complete connection and message flow. if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "retried pubrel", pubrel_packet): conn.send(pubcomp_packet) if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/03-publish-c2b-qos2-maximum-qos-1.py0000775000175000017500000000404113626052637022553 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client correctly handles sending a message with QoS > maximum QoS. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_MAXIMUM_QOS, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mid = 1 publish_1_packet = mosq_test.gen_publish("maximum/qos/qos1", qos=1, mid=mid, payload="message", proto_ver=5) puback_1_packet = mosq_test.gen_puback(mid, proto_ver=5) publish_2_packet = mosq_test.gen_publish("maximum/qos/qos0", qos=0, payload="message", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish 1", publish_1_packet): conn.send(puback_1_packet) if mosq_test.expect_packet(conn, "publish 2", publish_2_packet): if mosq_test.expect_packet(conn, "disconnect", disconnect_packet): rc = 0 conn.close() finally: for i in range(0, 5): if client.returncode != None: break time.sleep(0.1) try: client.terminate() except OSError: pass client.wait() sock.close() if client.returncode != 0: exit(1) exit(rc) mosquitto-1.6.9/test/lib/Makefile0000664000175000017500000000623013626052637016013 0ustar rogerrogerinclude ../../config.mk .PHONY: all check test test-compile test-compile-c test-compile-cpp c cpp .NOTPARALLEL: LD_LIBRARY_PATH=../../lib all : check : test ptest : test-compile ./test.py test : c cpp test-compile : test-compile-c test-compile-cpp test-compile-c : $(MAKE) -C c test-compile-cpp : $(MAKE) -C cpp c : test-compile ./01-con-discon-success.py $@/01-con-discon-success.test ./01-keepalive-pingreq.py $@/01-keepalive-pingreq.test ./01-no-clean-session.py $@/01-no-clean-session.test ./01-server-keepalive-pingreq.py $@/01-server-keepalive-pingreq.test ./01-unpwd-set.py $@/01-unpwd-set.test ./01-will-set.py $@/01-will-set.test ./01-will-unpwd-set.py $@/01-will-unpwd-set.test ./02-subscribe-qos0.py $@/02-subscribe-qos0.test ./02-subscribe-qos1.py $@/02-subscribe-qos1.test ./02-subscribe-qos1.py $@/02-subscribe-qos1-async1.test ./02-subscribe-qos1.py $@/02-subscribe-qos1-async2.test ./02-subscribe-qos2.py $@/02-subscribe-qos2.test ./02-unsubscribe-multiple-v5.py $@/02-unsubscribe-multiple-v5.test ./02-unsubscribe-v5.py $@/02-unsubscribe-v5.test ./02-unsubscribe.py $@/02-unsubscribe.test ./03-publish-b2c-qos1.py $@/03-publish-b2c-qos1.test ./03-publish-b2c-qos2-len.py $@/03-publish-b2c-qos2-len.test ./03-publish-b2c-qos2.py $@/03-publish-b2c-qos2.test ./03-publish-c2b-qos1-disconnect.py $@/03-publish-c2b-qos1-disconnect.test ./03-publish-c2b-qos1-len.py $@/03-publish-c2b-qos1-len.test ./03-publish-c2b-qos1-receive-maximum.py $@/03-publish-c2b-qos1-receive-maximum.test ./03-publish-c2b-qos2-disconnect.py $@/03-publish-c2b-qos2-disconnect.test ./03-publish-c2b-qos2-len.py $@/03-publish-c2b-qos2-len.test ./03-publish-c2b-qos2-maximum-qos-0.py $@/03-publish-c2b-qos2-maximum-qos-0.test ./03-publish-c2b-qos2-maximum-qos-1.py $@/03-publish-c2b-qos2-maximum-qos-1.test ./03-publish-c2b-qos2-pubrec-error.py $@/03-publish-c2b-qos2-pubrec-error.test ./03-publish-c2b-qos2-receive-maximum-1.py $@/03-publish-c2b-qos2-receive-maximum-1.test ./03-publish-c2b-qos2-receive-maximum-2.py $@/03-publish-c2b-qos2-receive-maximum-2.test ./03-publish-c2b-qos2.py $@/03-publish-c2b-qos2.test ./03-publish-qos0-no-payload.py $@/03-publish-qos0-no-payload.test ./03-publish-qos0.py $@/03-publish-qos0.test ./03-request-response-correlation.py $@/03-request-response-correlation.test ./03-request-response.py $@/03-request-response.test ./04-retain-qos0.py $@/04-retain-qos0.test ifeq ($(WITH_TLS),yes) #./08-ssl-fake-cacert.py $@/08-ssl-fake-cacert.test ./08-ssl-bad-cacert.py $@/08-ssl-bad-cacert.test ./08-ssl-connect-cert-auth-enc.py $@/08-ssl-connect-cert-auth-enc.test ./08-ssl-connect-cert-auth.py $@/08-ssl-connect-cert-auth.test ./08-ssl-connect-no-auth.py $@/08-ssl-connect-no-auth.test endif ./09-util-topic-tokenise.py $@/09-util-topic-tokenise.test ./11-prop-oversize-packet.py $@/11-prop-oversize-packet.test ./11-prop-send-content-type.py $@/11-prop-send-content-type.test ./11-prop-send-payload-format.py $@/11-prop-send-payload-format.test ./11-prop-recv-qos0.py $@/11-prop-recv-qos0.test ./11-prop-recv-qos1.py $@/11-prop-recv-qos1.test ./11-prop-recv-qos2.py $@/11-prop-recv-qos2.test clean : $(MAKE) -C c clean $(MAKE) -C cpp clean mosquitto-1.6.9/test/lib/04-retain-qos0.py0000775000175000017500000000237113626052637017315 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a correct retained PUBLISH to a topic with QoS 0. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "publish", publish_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/lib/01-will-set.py0000775000175000017500000000250513626052637016707 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client produces a correct connect with a will. # Will QoS=1, will retain=1. # The client should connect to port 1888 with keepalive=60, clean session set, # client id 01-will-set will topic set to topic/on/unexpected/disconnect , will # payload set to "will message", will qos set to 1 and will retain set. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("01-will-set", keepalive=keepalive, will_topic="topic/on/unexpected/disconnect", will_qos=1, will_retain=True, will_payload=b"will message") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env, port=port) try: (conn, address) = sock.accept() conn.settimeout(10) if mosq_test.expect_packet(conn, "connect", connect_packet): rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-1.6.9/test/ssl/0000775000175000017500000000000013626052637014405 5ustar rogerrogermosquitto-1.6.9/test/ssl/test-signing-ca.key0000664000175000017500000000321313626052637020112 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAwaEabnYfmLccftZn1dySNO9IImKUVsshKcGIfHpi6225r4uA dfSOMuIg4vo6ScggdFODD8FI4hM+SCfy5X1VxYeMQZ7ikFiMCZcevFrOEHGyZgIC mwzQJEd6Ok06LsDwZWtqzxMTivBtoKWAX2tYd66RbrqrxcAk9yInpL9HUi2g/Faw GRaE6VOsHX8pr8KGRPWbBOS/j+G4YaBjVQp6kyrYSiC4a7bpIMYswpPC3HppkI7q AFsMZoqQdLTZAZid/ltm4DkZIlANdj0cBPuTTW5F2ujMJzUqpjWoh+GZMkLocet8 +Wlwx8/FzGHFrkfcIIYrK/4c3SzpsDi2co4J6QIDAQABAoIBAEdv26OTWxbpv86f 5dFGPn7fJRriid33tXWFXIioUqSPZ+l3K17ZajklqoJzVVvxROAGC52dbvlRpjHS 4099zU5CMyHmr6oXsRq8sW9GhS4V9H6kETgJIyWvZU3rPiMPteGFHvPlEtm42Ilj ZhhOL2aAdlGG92bO/BRdeojStUqAvJn+5jYBpskZqw/4lLNlmpR8TpFOoGGE+eOC uXnf7Gz9+drPkoOg1/024Jygr721Klimkd6idf4v0hYt+g9GN+RVyxHKv2zYBGCV xCTYg2j7bKDgIUhBOtNGGZbpYLu5nPpZbWg9X0KEFFR7EBikSTYoBpaElCAkk3dp rGwLJr0CgYEA6oCtYouVcVabSVfvKpKep/RAYWFrz2VR5kakmRiis0Rpd1OLvwYt +Lz3c0j3ghHilcuVbB6pTjhdqa95whcPbsLzm5TcNovz3jz6sBrVJRH0wCfh+YGM hsU3SbeRDLaXCsvzmKeYrUG6SojNWsKOST+Iw93n6VlcR5nzXGobXYcCgYEA02E1 PQa+030IJt7Ord/ogOC7zK9D2s8vqK5hB5tEVpzw+NtK++HyezRgQ87/O8zm9Yka HhT6RcfhBu+UuPKZy3q+kQ5Lf3AXaj5kmfxgC9B83IwLmKINsusuBuzT4eHkVUor Lme+tNmztKogyITqDm7Bs8N98Xt8URzFMHf7uQ8CgYBx9hDMyDra9pTGouZG0TQr OQcki/yhsIKJnyEUiaVf60o5xC8wqSckL2kt7HLkEh8EXwiBn7D1o2zZLr7ENQK5 +CH9JO2T0JW2FfpaJOAagMxpqbgm0e9h+2uv9naWMBHdHFqIgEIxSLTozezGQ7B0 Jl0nmqq+ez/eSBG9go9D9wKBgBOCmGhelARvOO5liEwSK6Khm5Pj5W5vyyVVmw0Z rrAT4kYF76DaFQh8KBp6I6LAYdzt36RBKWyBa2q5eE+tzLY0SRyYZi2IChE7Wwu/ eJn+j1fH8VYQNxV5kZEAEPp7YBjjNKMe3kJRCb42Kbp4UiYs4OIXvCsqy6ms7yJv IKPPAoGBANxTT4FCNVISIvbNUSr1irLHbRfDg9m/3L7M/fU4dXO8RRY5L1LYi0hb fY3jV2nykLXbcUimJOPp0uwWMcFGM+LxVOwHGgYVBhd7mWeEAt3mLXXrNuP03gzw s4EBEKX/zGIt9YPxbhPKY5pJp0kyJ7WDxptPi+arTZA5SwJp9yyu -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/server.key0000664000175000017500000000321713626052637016430 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA8AG6l/g1TNDUHiKa2K/2qB11BaiNqgSpO7j8xr0tIyOx/nPE JHWqslWcyCc3ZhWNEEtGUt33DOMHkDU1ZPTBNIkUnn9a2rpqgCkZnjhVhfG7sB5h fZkDKC91S+sGqrza0MKXy2P4g5TA5iLaNxiZaLDPt14DvYs+8rdHy/7I6EVz4yNu kxRqsK+G4bSDMLXa36AIrNaf0U69u/d+tCjAFjXLxBh6W5LNDtkN1lfKbFnvrS6Z jUEHh3ALJ6kbZaT5dRWBzMjY0rVJyXcBIa2nRD1KiMlf3XBq9hQKTNK00oz2X8+9 AwrdrAjCVF135ZbxowYxX0/Yt/nOjxggdA5mQwIDAQABAoIBAQC26PpluxoT0sr1 tHXCUkhu0xROHajpO+glxdOPOrldoGSUgXGoP6y5gJmdyJVlzWLWWifcG6GeRp+K /aIVsJpWCWqXaIO7Unq79Za6iEBVdmcNz/mImMZZJ+IC27kXAhrZIpRAw42v6fwg 58raVnsD2ExVeObs22Q74gZrp19B88KFc8Ce3ZTJMhvIkrAbG38ilnlxZVCdxCzM Yl8NAxgHDlKUBDI9omKgksbWYwMWanZxQYwJ1i5rxJuDmGlmwqTe0z2W+2v0GxYj EldVDq9mK9dqQZQI0mQIJzGmG+weFlPoj8+GbU3aySULt8q6L/4U1nbmPfPlu5sp C1vbbsExAoGBAPtRG11qK1CP6AiYFAVUY4WF/OEzVlB2VEhyeXSm9QixZG1BbdHW vHWRxSwPwTtHwbih+hEuOXjAG8sg+JI60Iz8auhf3EVS6DjXpqN7+dua8x3ttJ9s c6PHDqRHxRcBKBGdC3Wx5IvxGGCqEb/4Aa5t3JUVPH8PvQaxCTJcJKzXAoGBAPR6 qvynjR75CqH/tDtSbR5CrUrXaup6s4xw/nUTbxXTb3PsVKklI+unFFDEs+PhmIyE xdCC2xuWbRzVSkF5vgbqraGqjGK04DGFjMdHA1oN9YskAoDaFudWp9vHAXKB0rFe HOYNuWEy2dR7qMvA9No2QbEN7Z2FWGcdTgVReth1AoGBAIxwe5lNLh1b/a9nxLBh wyeng3QZax+VsG23wtWEQyPzdYp0aLk9hZ0xs3x25WWKKOBTa9nT+fvXZvCxYRbe VRKkL93hS8dVmD3DjPSI4ExvH3LXFfuM8GZSY4U8MhAz7j9Bgljn6y6ksRm7kCW1 osLl08Ff16mtktU9c0U4JqqLAoGAc2OCWIVsYfYBQrzBgE5DGkk2KWDLIaiQHfUm 5HMrtw14SSp+OudAsPTG7egpT6EmswvnoaZha//vt/AjgAvJ2NHi6a7pW50rQ7RY 4aVuu45jGi0A0Xgd30pTJ7Qhxr3nh7d3xE0t9eZeUZ+b569G4cdB8iM0x2gsdV6r eG8goBECgYEAg2hxFf/moUr9XGUPvKgEnHHpnKflsqa93YApEP+zgMdr1yLXTKNw 5YL7tRyExXFmuNOAD3R8l0yUItX+uP01lzNrkdKl2S+yU3cYEaAvRSWH5SKqilrB e2/sVivHAthr8uIqjSnaLdpkQ3pyb7X5auSf/VfruQjHhuHCsXToRxU= -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/test-root-ca.key0000664000175000017500000000321713626052637017443 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA3aX7bLO3zeJcw4aac8I9ln0XoUfeVmJolp16BLCshH7odYSD bL7yN7c9RVhG/7rDka+lxmYYGMIyKUjkTKAcbjmYfEQzT5jvSqS2FzdYuIPgn5Bg CkKAVK+xRhpSg2iuH0YOscfASkNS8aq8fogDqSE+7VPWGD2K8ImG3YWmMHzEyl8g pVficqUUSloM1JLmuGEW9k5xB99zWl0tE8PgNLUcUjdur8EYXgq1X6PuglAdJBGj jfrMrohz9Zhqx492zIfzE3dx+btpbvtRlv0Xtx3RhS7h4RKuhJBdH5zwmj0voiSs FNS4EGcBnPlB4JU5pqlEusYaZvvv/edH2KGohwIDAQABAoIBAQDQTYhPrUqlJAJY Ay0uczLcNi259cffWVa/jbm5pKxNTNN8dg/paD5M3FmpzP/UoBnh1bgvD42/3umz YPylgqeVc216A8JRIQJqHQfAI9Sue8njS5Tmr37Zl9A7eMtpEjzpyTZQH9D4OfM+ iV3icEM4dLUl529Ckrv7uNPVZiA8WZUNa3NQ4lsuLHms12FOAi17wBMJOu0xTse/ vK7wucJ+p4wgXT8QZbOvqHmm3THMxKhhFYOoJK5S32jjy3kB4I56YzV6DRArLPNr RTjdXHtzNYUT4dYkDubekIDaebMKQi7nUofP6ZduJ7SAC9D118iKqChDTYP35Vmk kqqO2kgpAoGBAP47G+KhqT4tMLGs96r65Ve5KeRyLPLEgKfGXiEgrK1+lO9CFoTv 7hmZ3cF61IccilP/Tw1MG5uRrnXJWVi/u1jvdZEg74dGO2PivYhmdEgw/ZfJCAcn r8W+KKfrUQCcL/h++IrcLUVcRF4xjbhyvaCBc0zSpvxA5pn724caTm5NAoGBAN8w 1IUGpajJg8xHXca5y8UQeZwozjEn5oHdjivYL+lT2sKSKE49xzLmMPqhRtuIeiEe wBTo85PJ6SCjJPGc6wvbqPAq6CNC3BjZdh4i/+O87+fUloFAuXJn2TPAbulwFkvq 5GjeTbrJL+pd+x8VYalWSYusyxTdnlJyPE3KXOQjAoGBAJnrM4DMm2i3d2m67N+p szyfMEvNDIWWjsYFBWxNGf6YSpdojbXChYcebvH66b07fExKoJPOZlCTrOpHEz72 Jfk8UROiuyJNVRuuZU21qeUjNAW3gpLCZlr0PC0d/Ra/eROb2+JGV2pM6F+W5NSt Mz1/4ky6pLrImFTV9R0gwidpAoGAL7ZGmDF1lIGPtUnEWEk7sGL3PFTUz1lSQ4zT abgLdfvBFjscdq1qOg1PhySW+zNPuGjUcyPhfkR5m8qEiUocTSqmEMF7Yp5WYtGK GKMuxMaNGqgtjHADtNtSaWfHzgtyGMScE3cCct2zaoywtFJj0Elr63oC5/EAeWuG TLLn7LUCgYBB/Vy6WRhI8Eg+aI4vScgssdtx8FxGTYl/ZRQvgvK3iUnQdjcibY71 oPy7L1yzbOokoGZJWfcsvefTbO62DEi3k9uYlCd6T32RMbR/s1UQFZDWKcpNKzbo 5N21GE7lQp55F01nDE81RU4mcNhg1mf7792DobM7H+vM4wXW54sG9w== -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/client-revoked.key0000664000175000017500000000321313626052637020031 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA0wRlDdrj5mbSzEAFJP4XZ0C7bDXdGCxwfiDRACZWtxtO5j6M bA3k0sDdcTAC96CDeQ8VlM2jqsfU4xWvChqzuFS46/NrcjvT9AvGTKl5WJVTo0ox gZcxoWf3TZyLArKNebKxhz81dX7RBGv7f0TXPMJLc5nuYaBUL0ekYuPmDLsaiIyh lI+1edW7vnX4p+FWi9wPkJuURVD9C3ypvxdaCgK0FTyI+pNfGyCKw6rIGNECJzg0 OIzt91hQIFOeKV486fbMmDcc5CR/L0Q5QjF8MBMPQizI4VOsBUvjvXsFetPBFO7D BnVkXRGmvk1TjQYEHx4Up4tTuarDl8k8ikVrBQIDAQABAoIBAC8u5mGothjImQ3u qrfQ0O7XfJD/okZLeYPaVqFP8UfUJVo6Vi+7E5VEZr9uWtt/2qXxB4RUTupa8HEu YgtCWTk4SHkJ3taWJhiFoXt20ZlLGn6CkntFkWVj19pUzIh34EZ7/FIfghaZmqcA diXJAM+nKjPZEYJm1SwVOt6Z0tC5hRW9R3eCf8dxC6YlPJv9sebi6C9AqKVe6IsG 98CNFJG7hdgdsMFCzjDfasHreXGZ9w/pG9O+szAloqyM6k8R/3gT1Cx8Qwh6KIMt xL1KZyBw3dm7rCBxtozZC8nRzGFNoHWYS44wFxYaN11Y96h+ACLJYD7q6oOL4Oz9 Kh8hn+kCgYEA/6X8WDbjEv9akZurMa3AOOAsAHb+K/kSyc3pV3C3RMxR2y4z6W4x 4ZiJePpwsFZR0Ss/wXPnVBo1CEAJxHrBIb5zrzQwYIPFrNL7lPO4oalN0+Xpvo5r GIP354Yh1Eb98eLotBpcppI2MiE6z++lvUJ8HGcIuOMNeFEmIRl1E18CgYEA006x vMGrzv36ZPPsTkaAU8gLVinqseEggNd90fuOAi9UQ/9k/MjeTYtL/c/3VcIWgHA1 4Emvt5UUI0Gr3/it+O2cr5snIglrsnAFADaWrzjSMHLpLdHzUfMHCbAJLYO9vYec l2vpIcASvR7C1cQzFuBhNZC13uRWtV8O4BvPoBsCgYA/+Tl8mb+ZMW1oopvkgqZn lTFtrFlOh7W76ltKFlrGTJrvTlCPSZQR8Cn2rDUm63Lt9PSvZGGvGh/LQLsw/8b0 usQYQ+cXP+JnrSRn0dWSHtvq+s3TcbA7IksXFOnCRUGnFjFFYJNu24fUY5xkDIRd KBYGxYHZQnhMc4InJke14QKBgQCXSb6DkH48IydFZEcJ+/whABbtx/EbDj5BQQf6 cYrJEa3ZSV+6hO50wojT3jQNmHqX1r8cKGXAoOHcJEa0gs28bhNCv2kTO396MC3E a1ETfzEuMve0MJ9vSvr8+qZ3id0td4yr9TzjRyujcAS7HFAfzuKKgWNVhFJ4ZOi3 l/HdhQKBgE7V2j71No6xkjj9jOguI3TpCFXqQoSa9KhWOVXJrbpfE0K2QxvfQ6WO usWDGw9102OdFqfaFf2LE1cbIQe9M35QRrT9AjsZxtoc60XpZEwYS+FFh7po/t2t Apb8jiyBBAI9aYNRlWVo/1emnG6QUR45gX0Bu7glr+P4A+aopBi2 -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/test-signing-ca.crt0000664000175000017500000001044413626052637020116 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, L=Derby, O=Mosquitto Project, OU=Testing, CN=Root CA Validity Not Before: Feb 25 14:54:18 2020 GMT Not After : Feb 23 14:54:18 2025 GMT Subject: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:c1:a1:1a:6e:76:1f:98:b7:1c:7e:d6:67:d5:dc: 92:34:ef:48:22:62:94:56:cb:21:29:c1:88:7c:7a: 62:eb:6d:b9:af:8b:80:75:f4:8e:32:e2:20:e2:fa: 3a:49:c8:20:74:53:83:0f:c1:48:e2:13:3e:48:27: f2:e5:7d:55:c5:87:8c:41:9e:e2:90:58:8c:09:97: 1e:bc:5a:ce:10:71:b2:66:02:02:9b:0c:d0:24:47: 7a:3a:4d:3a:2e:c0:f0:65:6b:6a:cf:13:13:8a:f0: 6d:a0:a5:80:5f:6b:58:77:ae:91:6e:ba:ab:c5:c0: 24:f7:22:27:a4:bf:47:52:2d:a0:fc:56:b0:19:16: 84:e9:53:ac:1d:7f:29:af:c2:86:44:f5:9b:04:e4: bf:8f:e1:b8:61:a0:63:55:0a:7a:93:2a:d8:4a:20: b8:6b:b6:e9:20:c6:2c:c2:93:c2:dc:7a:69:90:8e: ea:00:5b:0c:66:8a:90:74:b4:d9:01:98:9d:fe:5b: 66:e0:39:19:22:50:0d:76:3d:1c:04:fb:93:4d:6e: 45:da:e8:cc:27:35:2a:a6:35:a8:87:e1:99:32:42: e8:71:eb:7c:f9:69:70:c7:cf:c5:cc:61:c5:ae:47: dc:20:86:2b:2b:fe:1c:dd:2c:e9:b0:38:b6:72:8e: 09:e9 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 X509v3 Authority Key Identifier: keyid:7A:89:5D:1E:C9:B1:72:2F:38:DB:DE:E7:D3:49:80:2C:01:FA:3B:74 X509v3 Basic Constraints: CA:TRUE Signature Algorithm: sha256WithRSAEncryption d3:8d:e3:33:87:f3:1e:4f:ff:da:1d:f8:61:3f:4a:ae:21:49: cd:ee:b1:e0:62:ab:44:70:a8:29:92:83:8d:33:45:4c:ac:b0: 66:a0:e8:32:23:76:ef:aa:89:7d:bc:e1:04:17:a5:d7:39:59: 99:ab:d9:bf:0c:fd:c5:b6:ad:6f:45:39:c9:27:f1:3e:c0:af: c3:8e:b1:1f:8f:fc:34:66:31:f4:f1:11:a0:27:99:a2:65:e2: aa:20:a7:98:b6:0e:ff:71:5e:10:e7:ab:1e:33:e7:fb:c8:59: d7:89:7a:3b:d9:a9:9f:48:2f:2e:ff:02:61:cd:86:47:60:61: 8e:81:71:68:f0:cd:63:72:b8:d2:7d:22:9d:6b:07:49:3a:0a: f7:8b:94:b3:98:90:3c:9f:e5:78:1b:84:a9:2e:fb:85:64:59: ce:6f:33:05:18:bc:21:df:f5:7c:10:79:d6:58:34:61:0e:1f: d5:af:b6:a0:8f:86:ce:56:d1:67:4f:b8:7e:50:2d:ba:77:37: 50:0f:91:06:dc:a8:7f:3c:8b:2b:8b:47:df:e3:7e:2f:79:81: 22:70:eb:f9:14:f3:66:73:17:33:e4:26:7e:47:df:80:89:de: a5:e8:5a:a9:c0:4b:3e:1b:9b:11:4b:3b:b4:8b:6a:9d:6c:ce: 39:f5:04:c9 -----BEGIN CERTIFICATE----- MIIDojCCAoqgAwIBAgIBATANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEOMAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1v c3F1aXR0byBQcm9qZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRAwDgYDVQQDDAdSb290 IENBMB4XDTIwMDIyNTE0NTQxOFoXDTI1MDIyMzE0NTQxOFowZTELMAkGA1UEBhMC R0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9q ZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRMwEQYDVQQDDApTaWduaW5nIENBMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwaEabnYfmLccftZn1dySNO9IImKU VsshKcGIfHpi6225r4uAdfSOMuIg4vo6ScggdFODD8FI4hM+SCfy5X1VxYeMQZ7i kFiMCZcevFrOEHGyZgICmwzQJEd6Ok06LsDwZWtqzxMTivBtoKWAX2tYd66Rbrqr xcAk9yInpL9HUi2g/FawGRaE6VOsHX8pr8KGRPWbBOS/j+G4YaBjVQp6kyrYSiC4 a7bpIMYswpPC3HppkI7qAFsMZoqQdLTZAZid/ltm4DkZIlANdj0cBPuTTW5F2ujM JzUqpjWoh+GZMkLocet8+Wlwx8/FzGHFrkfcIIYrK/4c3SzpsDi2co4J6QIDAQAB o1AwTjAdBgNVHQ4EFgQUqlpbHJEymz+bw0Js0mj2p+DPvuAwHwYDVR0jBBgwFoAU eoldHsmxci84297n00mALAH6O3QwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsF AAOCAQEA043jM4fzHk//2h34YT9KriFJze6x4GKrRHCoKZKDjTNFTKywZqDoMiN2 76qJfbzhBBel1zlZmavZvwz9xbatb0U5ySfxPsCvw46xH4/8NGYx9PERoCeZomXi qiCnmLYO/3FeEOerHjPn+8hZ14l6O9mpn0gvLv8CYc2GR2BhjoFxaPDNY3K40n0i nWsHSToK94uUs5iQPJ/leBuEqS77hWRZzm8zBRi8Id/1fBB51lg0YQ4f1a+2oI+G zlbRZ0+4flAtunc3UA+RBtyofzyLK4tH3+N+L3mBInDr+RTzZnMXM+QmfkffgIne pehaqcBLPhubEUs7tItqnWzOOfUEyQ== -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/gen.sh0000775000175000017500000001113113626052637015512 0ustar rogerroger# This file generates the keys and certificates used for testing mosquitto. # None of the keys are encrypted, so do not just use this script to generate # files for your own use. rm -f *.crt *.key *.csr for a in root signing; do rm -rf ${a}CA/ mkdir -p ${a}CA/newcerts touch ${a}CA/index.txt echo 01 > ${a}CA/serial echo 01 > ${a}CA/crlnumber done rm -rf certs BASESUBJ="/C=GB/ST=Derbyshire/L=Derby/O=Mosquitto Project/OU=Testing" SBASESUBJ="/C=GB/ST=Nottinghamshire/L=Nottingham/O=Server/OU=Production" BBASESUBJ="/C=GB/ST=Nottinghamshire/L=Nottingham/O=Server/OU=Bridge" # The root CA openssl genrsa -out test-root-ca.key 2048 openssl req -new -x509 -days 3650 -key test-root-ca.key -out test-root-ca.crt -config openssl.cnf -subj "${BASESUBJ}/CN=Root CA/" # Another root CA that doesn't sign anything openssl genrsa -out test-bad-root-ca.key 2048 openssl req -new -x509 -days 3650 -key test-bad-root-ca.key -out test-bad-root-ca.crt -config openssl.cnf -subj "${BASESUBJ}/CN=Bad Root CA/" # This is a root CA that has the exact same details as the real root CA, but is a different key and certificate. Effectively a "fake" CA. openssl genrsa -out test-fake-root-ca.key 2048 openssl req -new -x509 -days 3650 -key test-fake-root-ca.key -out test-fake-root-ca.crt -config openssl.cnf -subj "${BASESUBJ}/CN=Root CA/" # An intermediate CA, signed by the root CA, used to sign server/client csrs. openssl genrsa -out test-signing-ca.key 2048 openssl req -out test-signing-ca.csr -key test-signing-ca.key -new -config openssl.cnf -subj "${BASESUBJ}/CN=Signing CA/" openssl ca -batch -config openssl.cnf -name CA_root -extensions v3_ca -out test-signing-ca.crt -infiles test-signing-ca.csr rm -f test-signing-ca.csr # An alternative intermediate CA, signed by the root CA, not used to sign anything. openssl genrsa -out test-alt-ca.key 2048 openssl req -out test-alt-ca.csr -key test-alt-ca.key -new -config openssl.cnf -subj "${BASESUBJ}/CN=Alternative Signing CA/" openssl ca -batch -config openssl.cnf -name CA_root -extensions v3_ca -out test-alt-ca.crt -infiles test-alt-ca.csr rm -f test-alt-ca.csr # Valid server key and certificate. openssl genrsa -out server.key 2048 openssl req -new -key server.key -out server.csr -config openssl.cnf -subj "${SBASESUBJ}/CN=localhost/" openssl ca -batch -config openssl.cnf -name CA_signing -out server.crt -infiles server.csr rm -f server.csr # Expired server certificate openssl genrsa -out server-expired.key 2048 openssl req -new -key server-expired.key -out server-expired.csr -config openssl.cnf -subj "${SBASESUBJ}-expired/CN=localhost/" openssl ca -batch -config openssl.cnf -name CA_signing -days 1 -startdate 120820000000Z -enddate 120821000000Z -out server-expired.crt -infiles server-expired.csr rm -f server-expired.csr # Valid client key and certificate. openssl genrsa -out client.key 2048 openssl req -new -key client.key -out client.csr -config openssl.cnf -subj "${SBASESUBJ}/CN=test client/" openssl ca -batch -config openssl.cnf -name CA_signing -out client.crt -infiles client.csr rm -f client.csr # Expired client certificate openssl genrsa -out client-expired.key 2048 openssl req -new -key client-expired.key -out client-expired.csr -config openssl.cnf -subj "${SBASESUBJ}/CN=test client expired/" openssl ca -batch -config openssl.cnf -name CA_signing -days 1 -startdate 120820000000Z -enddate 120821000000Z -out client-expired.crt -infiles client-expired.csr rm -f client-expired.csr # Empty CRL file openssl ca -batch -config openssl.cnf -name CA_signing -gencrl -out crl-empty.pem # Revoked client certificate openssl genrsa -out client-revoked.key 2048 openssl req -new -key client-revoked.key -out client-revoked.csr -config openssl.cnf -subj "${SBASESUBJ}/CN=test client revoked/" openssl ca -batch -config openssl.cnf -name CA_signing -out client-revoked.crt -infiles client-revoked.csr openssl ca -batch -config openssl.cnf -name CA_signing -revoke client-revoked.crt openssl ca -batch -config openssl.cnf -name CA_signing -gencrl -out crl.pem rm -f client-revoked.csr # Valid client key and certificate, encrypted (use "password" as password) openssl genrsa -des3 -out client-encrypted.key -passout pass:password 2048 openssl req -new -key client-encrypted.key -out client-encrypted.csr -config openssl.cnf -subj "${SBASESUBJ}/CN=test client encrypted/" -passin pass:password openssl ca -batch -config openssl.cnf -name CA_signing -out client-encrypted.crt -infiles client-encrypted.csr rm -f client-encrypted.csr cat test-signing-ca.crt test-root-ca.crt > all-ca.crt #mkdir certs #cp test-signing-ca.crt certs/test-signing-ca.pem #cp test-root-ca.crt certs/test-root.ca.pem #openssl rehash certs mosquitto-1.6.9/test/ssl/test-alt-ca.key0000664000175000017500000000321313626052637017234 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAzpPPrE70FOFLqrno3cB/66tVFtqPARtVbn6z4E4DaF9ItIzT 0kSsOzp4iKyQ+SLTuYokNeTJLqAlsabK2IaXi2M0cxKM9rs46kDb1s4GM7vqmztg wq8iBwhB5IzU751Xs3OMKDoiFRtjZ6XMAMqjfMjv2WRywu8xoaa02a0VZkIyXI9u 3byXeloHpKHizSfDlVsde9UnZbQ02mxZQDrAeEGMSGTp3Y32pv+zO2P3nvj50aAN CjQ8L1FzBVh2zcpiYcu8nXbW5sobO5WiLyRsIITS+ihPsdWF6/ZHSdV3owMFy/rJ xrC/OMqOn0SYKO6l/tW8hXpAbuFr80OiIg8oewIDAQABAoIBAEgNoHMeet5JkwXy oHmwai3+bchx5U1ihlLrGLyVGXUvPwHS2RNPZq+l/mLVph9v+V+PAoBV06JSs7Ma VUhe8b7plGLKxqZMuVZj1wo+hEVJN1R7yo09XuYLCEi6oo8NV4i9NdbWKAsqqWp+ lwBzrcCZqacu9SRvH+Wdaxk92Of4cHcbP8nHSw9uGg6xmMONXntdJyFgX84DVC3P hRbl8SbhxzcVGGanhMvuag3lK/rJdoZGM9HRuXVUDY4vMNHzeyH783OOp3+U7TOI MQzG3gAnVzdUIqP2OxiAL8lqdPgsNPyl6z+fYnVe+8GzbkzSr7GxrEv6KqUQTX9Y IOn0cRECgYEA61OMoEeTHSaoIfPMAOYx+gq6s71x0xk5OI7kKDwitFuuxR+kA/Fi uzwomYSq8yUMAxxX97WCVQfeF5SiDYZ4ETnLjuNwh4i4mZbhwET6KeEfZz0MFQMM tBOB8e+SaNUbf1Of8l3qeFrCitYn1sY2BCGhz7DPUDwN2tqL6+Oot1kCgYEA4Lmz w9XLWe5aP2ix30qHnDjGzEouO30JxZMhk0iH/iu0QD7NEO4KPugLMATVdu5yfKnT 9Xr6gOfj2nUsMSiLBzyvOgo7OaCbznEMTdF7s3hfkh8nhKyOqYVGjzvjJP5tlnmq i+j/PAeB/my9eTof6msxJdlmVj34WXmBHQoNN/MCgYA56yxXXoZkzFjhUmHJbt6q De35wwy6yiB9PR4GkRZxkYcoWStDFSwZrSrI7hAtG9cjBNzZyMC1MOSGpTxlW809 YB4rourVUN8uXiZd7hwsJo5WGH5axY9g2tRGuZItXxYPdoONYXQN/ziWdzMC93Hf /m8W8Qt1UfKPBO8fNb8WsQKBgFTwe+ziazkzqTLcXJbcccNvhlyDEVR033OpOACW YqiEVl4OHq5uerrqNAhTW2fXmrhZ7H6VnAeLHolcznZKL7ptioGyik4u0ZVHD3J+ YnYkYmM1mVdBba7PbCsJZMJ/1GYS2I6HY6mJ4O2MplUizhtppqr6r/6a77rJ/S4/ tV1XAoGAV/73Onjr9h5TNdhzyvNYoyh9+DB8lCqMZW4oyb51m1IbhcOaHXvgiEoR WLW+iIKllTX0S0N3bwc1hzf5719FuhRN8a7KnokJ61sRwS6gdfKWTHF1j3kSlzRP +i7PEoxbRSqeA9lE/fKWprV5Iq4BP0xc1nujii8W4IjcXkp/cE8= -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/client-encrypted.crt0000664000175000017500000001072313626052637020373 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 6 (0x6) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Feb 25 14:54:19 2020 GMT Not After : Feb 23 14:54:19 2025 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client encrypted Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:b3:5c:d2:08:93:da:a7:4e:a7:39:74:b0:a2:cd: ce:f7:02:03:74:5d:f1:de:db:ff:51:68:d8:02:51: 1e:80:ac:aa:7c:90:c1:32:c9:7a:e5:ac:c4:bb:c5: 6a:c4:2b:96:3f:14:db:a2:b3:89:b6:24:ec:2f:80: 8a:a3:3b:89:89:29:c1:6a:de:ec:70:b0:9b:cb:92: cf:a1:25:0f:d1:9e:cf:be:71:63:b6:82:85:42:83: e9:bf:38:56:8c:f1:75:a7:7f:76:14:50:4c:67:bb: 53:a2:97:cf:5e:35:bd:fc:bb:c6:fd:aa:6e:fb:d7: fc:9e:64:74:61:6f:ea:48:c0:c1:01:2c:69:f9:20: 0e:6a:d1:d3:a1:a3:3f:f7:0d:88:71:93:27:47:5f: 94:d4:27:c5:9f:4b:be:86:0b:7f:73:dd:97:28:91: f0:aa:f0:09:de:a7:b6:1b:d7:ca:91:34:b0:b9:95: 2c:0f:14:1a:ce:da:84:bd:60:5e:f4:f0:f0:87:71: 93:44:70:88:3e:1c:2f:4e:16:a5:3c:9c:40:09:a0: 22:bd:b4:96:61:cb:e7:58:40:98:6e:61:d3:7f:ae: bf:6d:9a:d1:6b:04:c3:55:bd:93:da:95:0d:06:65: 65:19:3e:bc:d8:80:12:8f:d8:74:9a:20:5e:db:b6: b1:29 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: A4:B3:5E:21:A5:51:C7:37:ED:86:36:79:88:D7:36:88:FE:D0:3F:5D X509v3 Authority Key Identifier: keyid:AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 Signature Algorithm: sha256WithRSAEncryption 79:90:68:9b:1f:92:48:63:e4:bd:4d:1c:65:a5:b2:25:71:92: b4:13:41:b9:9b:fc:50:0b:38:65:34:17:da:22:9c:9f:8e:2b: a9:25:06:02:00:49:89:c4:cb:cc:6e:3d:b5:09:15:9f:f9:25: e7:a1:61:51:20:9f:68:f3:42:e3:41:70:a8:4a:7a:11:31:3d: 55:f5:20:49:d2:12:f5:1d:f6:c5:11:48:e5:c2:e8:47:bc:e1: d6:e1:a9:d9:f8:d7:78:18:b5:f5:9b:dd:cf:05:88:9e:06:59: 54:a5:b8:1e:db:3e:51:12:28:f4:c3:ff:cb:a3:77:19:b2:86: 05:6e:e0:82:77:7f:5f:cd:79:48:c1:bb:39:3b:67:a9:7d:0a: 65:24:de:ba:3e:01:a0:be:af:10:88:88:ec:24:b7:8f:ad:49: b0:b6:cf:ee:65:bd:78:39:c7:53:0e:a1:32:58:62:af:4c:54: 7d:3d:4a:20:ea:c7:b7:15:08:1a:29:f7:40:ab:a2:46:10:b5: e5:39:31:88:97:6d:54:fd:d5:9c:24:d1:88:e7:3f:97:b8:75: 54:f6:83:c3:de:13:c5:55:5a:df:da:af:d2:f8:d9:3a:c1:83: 75:a7:1c:c3:17:13:b8:94:54:73:65:11:87:11:e3:d8:5e:48: df:32:95:95 -----BEGIN CERTIFICATE----- MIID3jCCAsagAwIBAgIBBjANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjAwMjI1 MTQ1NDE5WhcNMjUwMjIzMTQ1NDE5WjCBgjELMAkGA1UEBhMCR0IxGDAWBgNVBAgM D05vdHRpbmdoYW1zaGlyZTETMBEGA1UEBwwKTm90dGluZ2hhbTEPMA0GA1UECgwG U2VydmVyMRMwEQYDVQQLDApQcm9kdWN0aW9uMR4wHAYDVQQDDBV0ZXN0IGNsaWVu dCBlbmNyeXB0ZWQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzXNII k9qnTqc5dLCizc73AgN0XfHe2/9RaNgCUR6ArKp8kMEyyXrlrMS7xWrEK5Y/FNui s4m2JOwvgIqjO4mJKcFq3uxwsJvLks+hJQ/Rns++cWO2goVCg+m/OFaM8XWnf3YU UExnu1Oil89eNb38u8b9qm771/yeZHRhb+pIwMEBLGn5IA5q0dOhoz/3DYhxkydH X5TUJ8WfS76GC39z3ZcokfCq8Anep7Yb18qRNLC5lSwPFBrO2oS9YF708PCHcZNE cIg+HC9OFqU8nEAJoCK9tJZhy+dYQJhuYdN/rr9tmtFrBMNVvZPalQ0GZWUZPrzY gBKP2HSaIF7btrEpAgMBAAGjezB5MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8W HU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBSks14hpVHH N+2GNnmI1zaI/tA/XTAfBgNVHSMEGDAWgBSqWlsckTKbP5vDQmzSaPan4M++4DAN BgkqhkiG9w0BAQsFAAOCAQEAeZBomx+SSGPkvU0cZaWyJXGStBNBuZv8UAs4ZTQX 2iKcn44rqSUGAgBJicTLzG49tQkVn/kl56FhUSCfaPNC40FwqEp6ETE9VfUgSdIS 9R32xRFI5cLoR7zh1uGp2fjXeBi19ZvdzwWIngZZVKW4Hts+URIo9MP/y6N3GbKG BW7ggnd/X815SMG7OTtnqX0KZSTeuj4BoL6vEIiI7CS3j61JsLbP7mW9eDnHUw6h Mlhir0xUfT1KIOrHtxUIGin3QKuiRhC15TkxiJdtVP3VnCTRiOc/l7h1VPaDw94T xVVa39qv0vjZOsGDdaccwxcTuJRUc2URhxHj2F5I3zKVlQ== -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/server.crt0000664000175000017500000001066313626052637016433 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Feb 25 14:54:18 2020 GMT Not After : Feb 23 14:54:18 2025 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=localhost Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:f0:01:ba:97:f8:35:4c:d0:d4:1e:22:9a:d8:af: f6:a8:1d:75:05:a8:8d:aa:04:a9:3b:b8:fc:c6:bd: 2d:23:23:b1:fe:73:c4:24:75:aa:b2:55:9c:c8:27: 37:66:15:8d:10:4b:46:52:dd:f7:0c:e3:07:90:35: 35:64:f4:c1:34:89:14:9e:7f:5a:da:ba:6a:80:29: 19:9e:38:55:85:f1:bb:b0:1e:61:7d:99:03:28:2f: 75:4b:eb:06:aa:bc:da:d0:c2:97:cb:63:f8:83:94: c0:e6:22:da:37:18:99:68:b0:cf:b7:5e:03:bd:8b: 3e:f2:b7:47:cb:fe:c8:e8:45:73:e3:23:6e:93:14: 6a:b0:af:86:e1:b4:83:30:b5:da:df:a0:08:ac:d6: 9f:d1:4e:bd:bb:f7:7e:b4:28:c0:16:35:cb:c4:18: 7a:5b:92:cd:0e:d9:0d:d6:57:ca:6c:59:ef:ad:2e: 99:8d:41:07:87:70:0b:27:a9:1b:65:a4:f9:75:15: 81:cc:c8:d8:d2:b5:49:c9:77:01:21:ad:a7:44:3d: 4a:88:c9:5f:dd:70:6a:f6:14:0a:4c:d2:b4:d2:8c: f6:5f:cf:bd:03:0a:dd:ac:08:c2:54:5d:77:e5:96: f1:a3:06:31:5f:4f:d8:b7:f9:ce:8f:18:20:74:0e: 66:43 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 21:93:75:73:22:5F:FA:88:1E:8C:4E:00:A8:B1:AD:67:B2:A7:7C:E3 X509v3 Authority Key Identifier: keyid:AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 Signature Algorithm: sha256WithRSAEncryption 5e:71:9a:51:b5:47:5b:a5:1a:fd:05:26:b6:98:50:47:d1:f3: c7:b9:1e:23:09:68:2c:23:74:48:55:2f:69:f7:e0:06:31:c0: 0c:14:4a:9a:e4:43:b4:1d:ec:80:3b:14:e7:2e:63:db:d5:99: 0a:64:5f:4e:0b:1e:e8:2d:db:7f:71:ad:b7:a6:51:a0:c9:e1: f4:52:19:30:c1:8d:ab:36:3c:77:85:da:f7:c0:5f:0b:54:d8: 48:c8:2b:98:ae:e0:f6:34:85:a1:17:5e:a5:cb:65:ea:cc:cc: 67:40:64:bf:0d:fd:21:de:1f:13:01:13:51:88:de:33:f9:94: d9:a3:13:9f:ba:6f:b4:bd:8b:61:1f:b7:43:24:97:30:f6:ab: 67:0e:ee:8d:6a:11:ba:4b:b1:1f:61:bd:d9:a0:c7:38:b1:5a: 4c:e6:51:36:03:5a:d6:56:85:b3:2f:32:0f:8d:96:da:5a:42: 85:10:ba:bb:cf:75:c9:ff:73:95:bc:34:c1:99:76:ca:b1:b5: 63:88:2c:98:51:b4:b5:61:ea:0e:20:6a:22:cf:09:65:26:b8: dc:72:d3:a1:fa:78:5c:b5:09:d9:b6:e6:d7:05:1b:35:72:e0: d8:ee:a3:39:95:5e:24:55:8c:1e:7e:87:17:40:b3:4f:4c:90: c9:2b:f2:43 -----BEGIN CERTIFICATE----- MIID0TCCArmgAwIBAgIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjAwMjI1 MTQ1NDE4WhcNMjUwMjIzMTQ1NDE4WjB2MQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxEzARBgNVBAsMClByb2R1Y3Rpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDCC ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAPABupf4NUzQ1B4imtiv9qgd dQWojaoEqTu4/Ma9LSMjsf5zxCR1qrJVnMgnN2YVjRBLRlLd9wzjB5A1NWT0wTSJ FJ5/Wtq6aoApGZ44VYXxu7AeYX2ZAygvdUvrBqq82tDCl8tj+IOUwOYi2jcYmWiw z7deA72LPvK3R8v+yOhFc+MjbpMUarCvhuG0gzC12t+gCKzWn9FOvbv3frQowBY1 y8QYeluSzQ7ZDdZXymxZ760umY1BB4dwCyepG2Wk+XUVgczI2NK1Scl3ASGtp0Q9 SojJX91wavYUCkzStNKM9l/PvQMK3awIwlRdd+WW8aMGMV9P2Lf5zo8YIHQOZkMC AwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5l cmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFCGTdXMiX/qIHoxOAKixrWeyp3zj MB8GA1UdIwQYMBaAFKpaWxyRMps/m8NCbNJo9qfgz77gMA0GCSqGSIb3DQEBCwUA A4IBAQBecZpRtUdbpRr9BSa2mFBH0fPHuR4jCWgsI3RIVS9p9+AGMcAMFEqa5EO0 HeyAOxTnLmPb1ZkKZF9OCx7oLdt/ca23plGgyeH0UhkwwY2rNjx3hdr3wF8LVNhI yCuYruD2NIWhF16ly2XqzMxnQGS/Df0h3h8TARNRiN4z+ZTZoxOfum+0vYthH7dD JJcw9qtnDu6NahG6S7EfYb3ZoMc4sVpM5lE2A1rWVoWzLzIPjZbaWkKFELq7z3XJ /3OVvDTBmXbKsbVjiCyYUbS1YeoOIGoizwllJrjcctOh+nhctQnZtubXBRs1cuDY 7qM5lV4kVYwefocXQLNPTJDJK/JD -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/test-root-ca.crt0000664000175000017500000000252313626052637017442 0ustar rogerroger-----BEGIN CERTIFICATE----- MIIDwjCCAqqgAwIBAgIURMxcSM9J+pY3g2SE3qoM34dHwPkwDQYJKoZIhvcNAQEL BQAwcjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEQMA4GA1UEAwwHUm9vdCBDQTAeFw0yMDAyMjUxNDU0MThaFw0zMDAyMjIx NDU0MThaMHIxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApEZXJieXNoaXJlMQ4wDAYD VQQHDAVEZXJieTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNVBAsM B1Rlc3RpbmcxEDAOBgNVBAMMB1Jvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDdpftss7fN4lzDhppzwj2WfRehR95WYmiWnXoEsKyEfuh1hINs vvI3tz1FWEb/usORr6XGZhgYwjIpSORMoBxuOZh8RDNPmO9KpLYXN1i4g+CfkGAK QoBUr7FGGlKDaK4fRg6xx8BKQ1Lxqrx+iAOpIT7tU9YYPYrwiYbdhaYwfMTKXyCl V+JypRRKWgzUkua4YRb2TnEH33NaXS0Tw+A0tRxSN26vwRheCrVfo+6CUB0kEaON +syuiHP1mGrHj3bMh/MTd3H5u2lu+1GW/Re3HdGFLuHhEq6EkF0fnPCaPS+iJKwU 1LgQZwGc+UHglTmmqUS6xhpm++/950fYoaiHAgMBAAGjUDBOMB0GA1UdDgQWBBR6 iV0eybFyLzjb3ufTSYAsAfo7dDAfBgNVHSMEGDAWgBR6iV0eybFyLzjb3ufTSYAs Afo7dDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQB7/Zn0VBciDCXo JA4ZX5boZyQMx7Lm62O+ixChT2hW0VNlouacgfSq455sNxFJKam0ZQKzusMzssNQ ticyZUwIosGx36f8qBaGksx0EbgAh9QdOulsYDLW5UsB4Rh94C36NoTd9+BJF6D4 89IpuxQehDKKuRG0NUChEkLvJ2AAPi/+iDHZQMB/sAzaT4gJ4eMeY4p4XBb/a9P2 w05RCpVNyLg32S7ynLNUrz+/lZUfZ8sYhpdECbFDpb0e1iVc1vst8Pur+cSGFO3f HabwuWTdF9Xx8MaH/n32Pv8BxZ/hBdjsXa/CiMyT4POs6XGTpZ2iLcmHo8WS4Uls 5gKvsjuj -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/server-expired.crt0000664000175000017500000001070713626052637020070 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Aug 20 00:00:00 2012 GMT Not After : Aug 21 00:00:00 2012 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production-expired, CN=localhost Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:95:0d:f4:ee:f2:c8:f8:84:23:78:af:73:53:78: 78:95:fd:cd:a6:fd:fd:0f:c7:ee:1c:39:e7:3c:d5: 2b:ac:1d:ab:92:e9:8d:df:c1:15:37:40:3d:d1:b6: 96:78:ec:4e:63:54:53:14:d4:9d:bc:42:6d:d9:5d: 3b:ce:d4:d0:a5:f1:ef:32:5a:c7:63:1b:2c:01:a7: f4:9e:9a:39:95:c4:70:02:fa:8f:d2:d1:fc:0c:51: 4e:e1:91:54:88:ee:0d:c1:f0:6a:17:7d:05:9e:f2: 2e:b8:ed:49:b3:41:70:21:94:b4:02:22:bf:ff:79: 0d:fb:38:bb:a1:3d:c0:a9:60:5e:39:18:8e:07:48: 15:10:7b:b0:01:2b:2b:35:8c:67:be:85:70:cf:ba: 99:bc:a8:1d:50:3f:ac:d9:32:91:ea:59:c4:4a:7a: 72:5d:28:1e:43:5b:0b:b5:c0:d0:9d:ac:c5:68:c9: e5:ef:3e:cf:58:04:e6:99:4e:21:7c:c0:80:9d:88: f4:89:ca:d3:17:e1:77:fa:31:8c:7d:14:3e:af:e0: 16:f8:67:28:4b:18:bb:fd:c3:4a:64:1f:c7:26:3b: 0c:db:04:e7:11:35:13:99:ca:9c:25:87:48:e6:60: f2:a1:ef:7c:c2:5f:c3:02:ee:4c:27:32:da:20:76: 70:79 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 75:36:7F:77:C7:7D:8D:B8:2B:7C:7D:8B:D8:0C:AD:59:3C:B0:85:E6 X509v3 Authority Key Identifier: keyid:AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 Signature Algorithm: sha256WithRSAEncryption 74:c7:1f:42:e3:00:94:1a:16:ec:c9:17:02:1f:4f:e6:b0:4a: 4b:b1:2d:d2:3f:04:54:54:23:d1:b6:da:fa:fc:ac:3e:32:35: a9:68:6b:b7:bc:06:ee:58:d5:95:a5:48:56:cb:ea:9d:d3:5e: 68:ce:8f:65:60:40:42:a6:8d:c5:e4:33:d3:ef:ed:e4:fd:23: fe:28:34:ca:eb:2f:69:45:8e:61:dc:e2:0c:50:96:35:94:90: 25:61:55:d5:9c:d8:00:63:e0:6e:a1:67:f2:3f:34:a5:9d:33: 2a:7d:de:c0:89:8c:46:b1:fc:d4:19:7e:be:83:e0:f1:34:ff: 41:d3:cd:fb:e5:71:9d:05:00:67:af:f3:03:be:f6:e9:db:76: 58:89:72:68:7f:32:84:ff:c0:38:95:89:60:1b:99:fc:5e:37: 81:fa:ce:e7:78:7f:6c:3e:b9:70:74:62:62:d3:c2:8e:8e:2c: 11:fc:e6:fa:9a:cd:1e:79:67:51:01:54:1e:7d:db:32:09:13: 14:91:a3:56:2d:8e:fa:f8:3d:49:67:fe:b2:c8:11:8a:09:0e: 05:b0:0e:6b:39:4e:c5:7e:13:ea:40:41:26:d1:c0:c3:a2:cb: cc:3d:cf:fe:59:0a:e1:b8:0d:50:47:0a:86:b4:72:21:89:b7: 5b:e2:37:2d -----BEGIN CERTIFICATE----- MIID2TCCAsGgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMTIwODIw MDAwMDAwWhcNMTIwODIxMDAwMDAwWjB+MQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxGzAZBgNVBAsMElByb2R1Y3Rpb24tZXhwaXJlZDESMBAGA1UEAwwJbG9j YWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlQ307vLI+IQj eK9zU3h4lf3Npv39D8fuHDnnPNUrrB2rkumN38EVN0A90baWeOxOY1RTFNSdvEJt 2V07ztTQpfHvMlrHYxssAaf0npo5lcRwAvqP0tH8DFFO4ZFUiO4NwfBqF30FnvIu uO1Js0FwIZS0AiK//3kN+zi7oT3AqWBeORiOB0gVEHuwASsrNYxnvoVwz7qZvKgd UD+s2TKR6lnESnpyXSgeQ1sLtcDQnazFaMnl7z7PWATmmU4hfMCAnYj0icrTF+F3 +jGMfRQ+r+AW+GcoSxi7/cNKZB/HJjsM2wTnETUTmcqcJYdI5mDyoe98wl/DAu5M JzLaIHZweQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVu U1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUdTZ/d8d9jbgrfH2L 2AytWTywheYwHwYDVR0jBBgwFoAUqlpbHJEymz+bw0Js0mj2p+DPvuAwDQYJKoZI hvcNAQELBQADggEBAHTHH0LjAJQaFuzJFwIfT+awSkuxLdI/BFRUI9G22vr8rD4y Naloa7e8Bu5Y1ZWlSFbL6p3TXmjOj2VgQEKmjcXkM9Pv7eT9I/4oNMrrL2lFjmHc 4gxQljWUkCVhVdWc2ABj4G6hZ/I/NKWdMyp93sCJjEax/NQZfr6D4PE0/0HTzfvl cZ0FAGev8wO+9unbdliJcmh/MoT/wDiViWAbmfxeN4H6zud4f2w+uXB0YmLTwo6O LBH85vqazR55Z1EBVB592zIJExSRo1Ytjvr4PUln/rLIEYoJDgWwDms5TsV+E+pA QSbRwMOiy8w9z/5ZCuG4DVBHCoa0ciGJt1viNy0= -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/client-expired.crt0000664000175000017500000001071513626052637020037 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 4 (0x4) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Aug 20 00:00:00 2012 GMT Not After : Aug 21 00:00:00 2012 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client expired Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:d0:5a:fb:75:01:67:ef:ce:6a:66:1b:44:11:68: 0d:49:d1:8e:68:39:f3:a8:71:38:c3:1f:7b:ff:77: b7:0f:2e:e8:87:db:be:48:5c:12:6f:ba:fd:3c:22: ec:7b:dd:2f:47:42:c5:db:9a:1b:8e:c3:9e:3e:c1: 59:53:19:69:7d:37:f8:70:75:b4:eb:28:09:4e:88: dd:b1:0f:21:fc:4b:33:98:2a:9a:e6:ed:8d:2a:7b: b4:b7:c9:53:28:c8:76:69:35:f2:2e:3d:31:2c:4b: 51:f9:2c:73:b9:ab:26:01:7e:8c:ef:7f:33:ee:99: ca:ad:61:9f:60:3d:ac:11:c8:09:7b:fd:31:dd:7e: 7e:d8:68:69:49:a8:2e:29:f0:9f:61:24:b7:63:5d: 98:93:73:96:7e:6f:a6:c2:3b:05:05:9c:82:eb:87: dd:f4:56:02:c2:ef:1e:34:02:0a:9c:9d:9a:7e:0c: 67:9b:91:74:a0:6e:5e:f6:52:5b:f7:f3:b7:0e:fe: 4e:0e:10:e4:fa:dc:4b:91:62:b4:49:42:6d:ea:84: 87:4a:89:8e:0d:8a:42:f2:6c:82:a1:93:bd:4d:a2: f0:ad:0f:ba:f7:6f:60:b7:7a:1b:9a:b5:e6:41:92: d7:3b:37:c6:79:b1:70:9a:6b:35:6a:42:3a:f1:20: 90:b7 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 74:67:BC:4D:15:27:BF:FF:E6:FF:20:B2:FE:9E:D5:B4:A2:57:D1:78 X509v3 Authority Key Identifier: keyid:AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 Signature Algorithm: sha256WithRSAEncryption 62:fd:1a:03:bc:1a:45:d0:ac:c1:4c:61:08:d0:df:d4:3f:8e: 85:f5:6c:ca:f0:ac:75:f9:56:54:f2:e2:17:95:e2:40:be:b3: cf:6e:c9:ff:db:12:cb:cd:c9:21:9a:79:35:45:2b:98:e7:38: 4d:a8:f1:39:db:5f:e4:fd:7e:f3:da:24:77:86:3a:1c:ab:f1: 60:af:33:ed:5b:7a:e8:cb:18:0c:7c:d7:32:af:50:8b:9d:74: 53:38:2f:31:9b:16:fc:99:c5:36:b7:4a:bd:96:38:27:96:b2: ba:9b:87:8e:48:2a:d7:3d:40:00:8f:54:8e:00:c7:8d:b8:97: 0c:3d:d5:67:5c:31:8d:ac:40:7a:27:86:a7:88:ac:90:ac:eb: ae:e3:35:dd:b2:03:ae:8b:c0:9d:a3:32:ac:d7:39:f2:b7:d2: f8:d2:f8:76:4d:77:cf:df:fd:e6:d6:7c:df:67:3d:21:01:e2: 45:d2:59:47:e6:f6:08:99:13:7b:ac:f9:ec:51:0d:8e:68:83: 7c:82:84:3d:03:24:dd:db:4c:8d:5a:44:8f:93:de:ea:14:b5: 8e:e4:65:02:a4:98:4a:20:eb:07:01:b0:80:9e:2c:52:00:c8: f2:9e:60:8e:72:67:57:97:44:7f:65:f7:2b:19:95:e6:c3:38: 80:39:66:cd -----BEGIN CERTIFICATE----- MIID3DCCAsSgAwIBAgIBBDANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMTIwODIw MDAwMDAwWhcNMTIwODIxMDAwMDAwWjCBgDELMAkGA1UEBhMCR0IxGDAWBgNVBAgM D05vdHRpbmdoYW1zaGlyZTETMBEGA1UEBwwKTm90dGluZ2hhbTEPMA0GA1UECgwG U2VydmVyMRMwEQYDVQQLDApQcm9kdWN0aW9uMRwwGgYDVQQDDBN0ZXN0IGNsaWVu dCBleHBpcmVkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0Fr7dQFn 785qZhtEEWgNSdGOaDnzqHE4wx97/3e3Dy7oh9u+SFwSb7r9PCLse90vR0LF25ob jsOePsFZUxlpfTf4cHW06ygJTojdsQ8h/EszmCqa5u2NKnu0t8lTKMh2aTXyLj0x LEtR+SxzuasmAX6M738z7pnKrWGfYD2sEcgJe/0x3X5+2GhpSaguKfCfYSS3Y12Y k3OWfm+mwjsFBZyC64fd9FYCwu8eNAIKnJ2afgxnm5F0oG5e9lJb9/O3Dv5ODhDk +txLkWK0SUJt6oSHSomODYpC8myCoZO9TaLwrQ+6929gt3obmrXmQZLXOzfGebFw mms1akI68SCQtwIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1P cGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUdGe8TRUnv//m /yCy/p7VtKJX0XgwHwYDVR0jBBgwFoAUqlpbHJEymz+bw0Js0mj2p+DPvuAwDQYJ KoZIhvcNAQELBQADggEBAGL9GgO8GkXQrMFMYQjQ39Q/joX1bMrwrHX5VlTy4heV 4kC+s89uyf/bEsvNySGaeTVFK5jnOE2o8TnbX+T9fvPaJHeGOhyr8WCvM+1beujL GAx81zKvUIuddFM4LzGbFvyZxTa3Sr2WOCeWsrqbh45IKtc9QACPVI4Ax424lww9 1WdcMY2sQHonhqeIrJCs667jNd2yA66LwJ2jMqzXOfK30vjS+HZNd8/f/ebWfN9n PSEB4kXSWUfm9giZE3us+exRDY5og3yChD0DJN3bTI1aRI+T3uoUtY7kZQKkmEog 6wcBsICeLFIAyPKeYI5yZ1eXRH9l9ysZlebDOIA5Zs0= -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/signingCA/0000775000175000017500000000000013626052637016247 5ustar rogerrogermosquitto-1.6.9/test/ssl/signingCA/serial0000664000175000017500000000000313626052637017442 0ustar rogerroger07 mosquitto-1.6.9/test/ssl/signingCA/index.txt.attr0000664000175000017500000000002513626052637021065 0ustar rogerrogerunique_subject = yes mosquitto-1.6.9/test/ssl/signingCA/crlnumber0000664000175000017500000000000313626052637020154 0ustar rogerroger03 mosquitto-1.6.9/test/ssl/test-bad-root-ca.crt0000664000175000017500000000253713626052637020173 0ustar rogerroger-----BEGIN CERTIFICATE----- MIIDyjCCArKgAwIBAgIUdyk9NtFrh5WnXWwmIarH9aqo+2cwDQYJKoZIhvcNAQEL BQAwdjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEUMBIGA1UEAwwLQmFkIFJvb3QgQ0EwHhcNMjAwMjI1MTQ1NDE4WhcNMzAw MjIyMTQ1NDE4WjB2MQswCQYDVQQGEwJHQjETMBEGA1UECAwKRGVyYnlzaGlyZTEO MAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9qZWN0MRAwDgYD VQQLDAdUZXN0aW5nMRQwEgYDVQQDDAtCYWQgUm9vdCBDQTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBAMsMhOIsSRKAopYjV/0lG252A4Xd1qUQlcwOPq3Z 1JYuBsa2We19xT427tSTXoDR2zdUH9nB1709wes7oTM8q1WWHszV/8DLBHotZZzf aNFy9ipwqjaJXMG5hWO1p+wg2q2BspoOpRcWhNO4ZrR5dPT1cm/N+A8TxtYd4WtO PWxXQj84rppeEUJjyE1QIRTGuQMiQxzsiyiTvyzKjuCELFcPjNwpqjEfxKaoHCD/ 5GWH1C8r2pOVIpRnP9qDVX4jQvSyAdfWeuPT0h2qHWp751e5w/inXkavzqYqI9xE vImUgW5/rVY8DrOf8huFXpfMwMBYuzxjbnObPhD85xRcc58CAwEAAaNQME4wHQYD VR0OBBYEFBuIpb/fFNJ54niM+oiZMHEDFPiNMB8GA1UdIwQYMBaAFBuIpb/fFNJ5 4niM+oiZMHEDFPiNMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAH71 WiPLeVumxVuB40cuaKpNDcMGFg3snkKi9d9eEVTP1gtfWt1dclXYnaPwYr8a3d5D iZnIVC5LUtFdWHaO6SHwsNmb59LFfXPtYxO3mOxUbSW3kTuB/N0B6laOcViPVpVt nLJ3FKKcRAjTuBfP191hbG6uG1bdAh5VLrDgA0taXcwiRd7zlKp+MdoxbetnLw3R GyzdAlWjJUGm5b7cE5sJZ0t3UoJsDeJckYJzUeDRV/90395pay3E9bd3ooa+1K9Q AJk8MuGRY7W4qtC1JioqCTJJpkyryNql2pXiN4RqChTElYa1mbOP1qet1xLMEQY6 8D9qi22Al8++KQ+gw0o= -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/test-alt-ca.crt0000664000175000017500000001050013626052637017231 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, L=Derby, O=Mosquitto Project, OU=Testing, CN=Root CA Validity Not Before: Feb 25 14:54:18 2020 GMT Not After : Feb 23 14:54:18 2025 GMT Subject: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Alternative Signing CA Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:ce:93:cf:ac:4e:f4:14:e1:4b:aa:b9:e8:dd:c0: 7f:eb:ab:55:16:da:8f:01:1b:55:6e:7e:b3:e0:4e: 03:68:5f:48:b4:8c:d3:d2:44:ac:3b:3a:78:88:ac: 90:f9:22:d3:b9:8a:24:35:e4:c9:2e:a0:25:b1:a6: ca:d8:86:97:8b:63:34:73:12:8c:f6:bb:38:ea:40: db:d6:ce:06:33:bb:ea:9b:3b:60:c2:af:22:07:08: 41:e4:8c:d4:ef:9d:57:b3:73:8c:28:3a:22:15:1b: 63:67:a5:cc:00:ca:a3:7c:c8:ef:d9:64:72:c2:ef: 31:a1:a6:b4:d9:ad:15:66:42:32:5c:8f:6e:dd:bc: 97:7a:5a:07:a4:a1:e2:cd:27:c3:95:5b:1d:7b:d5: 27:65:b4:34:da:6c:59:40:3a:c0:78:41:8c:48:64: e9:dd:8d:f6:a6:ff:b3:3b:63:f7:9e:f8:f9:d1:a0: 0d:0a:34:3c:2f:51:73:05:58:76:cd:ca:62:61:cb: bc:9d:76:d6:e6:ca:1b:3b:95:a2:2f:24:6c:20:84: d2:fa:28:4f:b1:d5:85:eb:f6:47:49:d5:77:a3:03: 05:cb:fa:c9:c6:b0:bf:38:ca:8e:9f:44:98:28:ee: a5:fe:d5:bc:85:7a:40:6e:e1:6b:f3:43:a2:22:0f: 28:7b Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: 75:A1:3D:93:BD:A7:31:3D:0F:D2:0B:8D:04:43:49:BF:BC:B7:BD:87 X509v3 Authority Key Identifier: keyid:7A:89:5D:1E:C9:B1:72:2F:38:DB:DE:E7:D3:49:80:2C:01:FA:3B:74 X509v3 Basic Constraints: CA:TRUE Signature Algorithm: sha256WithRSAEncryption b1:d6:97:e3:46:14:82:1e:c6:8c:50:b8:e8:13:4b:62:70:62: 0c:f9:3d:07:19:cf:d0:78:2c:53:1f:10:87:0f:f9:2a:95:2e: 6f:c6:d3:87:d7:69:8d:7e:42:ee:c3:50:e6:13:56:65:6d:0f: 7c:cb:9c:35:d6:12:ff:e1:57:63:98:e0:80:53:9d:2b:8e:45: c4:34:e4:c0:60:79:d6:53:85:bc:5d:26:e4:ce:1b:6b:c4:ef: 47:e5:87:a9:9c:ea:a8:dc:35:cd:f0:b2:95:60:e2:67:89:56: e0:1e:95:71:2b:6a:77:91:15:ad:a1:50:27:5d:03:1c:13:0f: 2f:7d:ea:41:3d:1b:9f:e4:b4:b5:92:99:ca:32:dc:17:d9:54: 52:f9:b9:e0:9b:ed:23:b7:78:d3:07:36:34:2f:25:19:5f:49: e6:35:c6:d9:99:07:e9:52:dd:01:09:a9:d7:bf:e7:f4:74:6f: e2:0b:ce:da:7f:fa:38:95:43:d0:6c:f3:c4:1b:14:1c:47:50: 14:a9:48:4d:0c:d0:c6:be:a3:bc:17:9c:e3:92:24:e6:b3:51: 91:64:f4:55:1d:d1:5f:1b:69:90:ac:7e:69:e5:92:f7:d6:d2: 8a:f5:b2:5d:9b:79:8b:19:1c:6f:5a:9b:17:e5:c1:44:89:13: 0f:69:17:7c -----BEGIN CERTIFICATE----- MIIDrjCCApagAwIBAgIBAjANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEOMAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1v c3F1aXR0byBQcm9qZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRAwDgYDVQQDDAdSb290 IENBMB4XDTIwMDIyNTE0NTQxOFoXDTI1MDIyMzE0NTQxOFowcTELMAkGA1UEBhMC R0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9q ZWN0MRAwDgYDVQQLDAdUZXN0aW5nMR8wHQYDVQQDDBZBbHRlcm5hdGl2ZSBTaWdu aW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzpPPrE70FOFL qrno3cB/66tVFtqPARtVbn6z4E4DaF9ItIzT0kSsOzp4iKyQ+SLTuYokNeTJLqAl sabK2IaXi2M0cxKM9rs46kDb1s4GM7vqmztgwq8iBwhB5IzU751Xs3OMKDoiFRtj Z6XMAMqjfMjv2WRywu8xoaa02a0VZkIyXI9u3byXeloHpKHizSfDlVsde9UnZbQ0 2mxZQDrAeEGMSGTp3Y32pv+zO2P3nvj50aANCjQ8L1FzBVh2zcpiYcu8nXbW5sob O5WiLyRsIITS+ihPsdWF6/ZHSdV3owMFy/rJxrC/OMqOn0SYKO6l/tW8hXpAbuFr 80OiIg8oewIDAQABo1AwTjAdBgNVHQ4EFgQUdaE9k72nMT0P0guNBENJv7y3vYcw HwYDVR0jBBgwFoAUeoldHsmxci84297n00mALAH6O3QwDAYDVR0TBAUwAwEB/zAN BgkqhkiG9w0BAQsFAAOCAQEAsdaX40YUgh7GjFC46BNLYnBiDPk9BxnP0HgsUx8Q hw/5KpUub8bTh9dpjX5C7sNQ5hNWZW0PfMucNdYS/+FXY5jggFOdK45FxDTkwGB5 1lOFvF0m5M4ba8TvR+WHqZzqqNw1zfCylWDiZ4lW4B6VcStqd5EVraFQJ10DHBMP L33qQT0bn+S0tZKZyjLcF9lUUvm54JvtI7d40wc2NC8lGV9J5jXG2ZkH6VLdAQmp 17/n9HRv4gvO2n/6OJVD0GzzxBsUHEdQFKlITQzQxr6jvBec45Ik5rNRkWT0VR3R XxtpkKx+aeWS99bSivWyXZt5ixkcb1qbF+XBRIkTD2kXfA== -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/test-bad-root-ca.key0000664000175000017500000000321713626052637020167 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAywyE4ixJEoCiliNX/SUbbnYDhd3WpRCVzA4+rdnUli4GxrZZ 7X3FPjbu1JNegNHbN1Qf2cHXvT3B6zuhMzyrVZYezNX/wMsEei1lnN9o0XL2KnCq NolcwbmFY7Wn7CDarYGymg6lFxaE07hmtHl09PVyb834DxPG1h3ha049bFdCPziu ml4RQmPITVAhFMa5AyJDHOyLKJO/LMqO4IQsVw+M3CmqMR/EpqgcIP/kZYfULyva k5UilGc/2oNVfiNC9LIB19Z649PSHaodanvnV7nD+KdeRq/Opioj3ES8iZSBbn+t VjwOs5/yG4Vel8zAwFi7PGNuc5s+EPznFFxznwIDAQABAoIBAAduwuKAmoAp40m5 q3vhwtpNSZ253CSYsdMRZmv4wFZrAuZ9QFd4NiMr4Zw4dMokZHDnDG9tMBeGTjXt Ld5xRxhP8XqwDreg9t3+EW0npG+eVLKDA0gRySpyPxbCTI5ROZAGYmJPTO3GbkBN zLyogYaCAZlkIcNzhuDJoTnLWGZBzrsvwCGqwHdjGras31FSf+HYC8KcjQysQmUV F/puNldvV5rXo8rDOIdtrCC9oYvGMJDSk9X0qsHLWWqVnrruy7SmHMJ2kn6wUFfj qjm9OTdaHJOrswNmW/xLyQzj5gQOh45y7/e1W2X08HpUBzuraOnDJM2ty0dTetEW sb2+eUECgYEA8iGLJcHOWmK3cws/mAfI4GCvI1FcwYKXJzVCs+lozlzd7kioM4dW h4Mg30LbBDDsytxMNcaq5Aglwdg5CLg657vreQeZk6HUuFcwf//sJoBRAbwScE6r pI5fSSce9K+xzQzjpKiWy+Q3eC3Sax5yeeEKBSolUSKgVmDQ/lgv+D8CgYEA1q3m YK2RukYOEdcT2BpZmJI8vmeKRl6rswj6q4eSzRnruCrLxgNsDIQUkhX6zQ+a5Lhy g8USSqnpAZdBTXYIFo8fztx5abzXZpXrrUXpZTjNLncHrYE0/ztaBhEjVhoRRZ4P 4LMNnPKWNX+E5g+IhvzA8D9spSWTD1L1SorZrKECgYEAkkaBcYXry97nRLD+8jGB wUungoacqqrh9eXPLjFMB59C07lBJCAWvjcRnM8e0SFdbBA6WiJzCt+BL+IYUpQ5 wdVdI/jbZrzVbaf+vNU3LOtIBOxBl2dvejIojmD76oZZu66Vt9vBfduZRxknjV8P eWHiU8xqTuHES2qh14YfNLECgYB8GYkMqCmO0cJ+Y6OQECNtBFRjCT2w0jdVRsKJ d9TQBcTy8KJddEr4rT2q+VPDSNsUjt979udNDA2rIsHYQnwIdnI/xcnV6xllrxLP VpPGNOC/lIV2sjNtu+SdjzirJGSJpwassTUUXlOg13d++snEpsXt2+w1R5RMjntH vR56IQKBgQCF+kqRYtwBIXXyQDpxFV7ISKhfIdI2wnmEKHekXsg6APm2Hzqt8xGq nIqJIMUJvNp4mgBjw7drVuyuLu/xAsHg9zd2e85wnM5nyxTSlrD4EyN7oSSzEl4n qMI+y868gX0ZHjejFTRHiEPjERO9TndYlsXpbl8sUxs6TYzZNjB7FQ== -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/client.crt0000664000175000017500000001067113626052637016402 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Feb 25 14:54:19 2020 GMT Not After : Feb 23 14:54:19 2025 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:bf:6a:a5:cd:66:6a:1d:20:48:3a:f1:ff:61:9d: fd:1f:18:26:a0:43:4c:b0:4c:b9:8d:4e:7d:d0:81: e0:43:81:9e:70:75:cb:c4:57:49:3c:84:34:51:45: a2:9f:00:50:20:d6:5f:34:3c:02:bb:69:2f:64:4a: 28:21:e3:95:41:e8:50:04:f3:bf:f2:5a:9e:27:64: 5b:b3:bc:49:96:36:10:56:06:47:1a:ca:db:ad:6f: e3:f7:83:dc:42:37:28:07:58:a7:6f:26:45:b7:69: 6f:af:28:62:f8:7e:98:98:21:0a:a6:da:ae:d5:4b: fe:db:09:1a:b4:75:d5:09:3b:13:9e:33:9e:b4:d6: 5e:21:e6:fb:37:09:bb:1a:56:e1:5d:64:bc:5a:77: 99:ac:81:cc:2b:b7:9b:49:b6:e8:ba:2e:32:d9:9e: 8e:4d:2e:fc:17:d0:37:44:0f:35:a9:af:f1:44:bb: cb:2c:2a:75:f0:7e:ba:b6:1a:73:32:d6:1f:4c:3b: 9b:38:f0:e9:22:06:3c:94:6b:5f:69:e4:be:2f:fa: 9c:c4:9e:7c:c0:dd:c2:3c:53:b8:28:ca:77:a0:96: 6b:9c:cb:3f:44:b1:c5:51:75:89:a0:16:ba:82:63: f7:c4:24:7f:06:89:58:45:10:69:e4:97:f5:35:fe: 7e:97 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 36:51:2B:BB:3E:B7:6B:2B:7F:D4:86:AE:67:75:C2:01:54:5B:72:3C X509v3 Authority Key Identifier: keyid:AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 Signature Algorithm: sha256WithRSAEncryption 32:70:51:f0:c2:35:6f:83:e3:bc:f3:f2:6f:e9:79:e6:a9:51: d0:69:fa:fb:a8:a8:d4:59:c4:c4:ee:9b:59:9a:ce:a8:2e:7e: 71:a5:23:4c:27:76:e5:b6:e1:6d:bd:a4:24:f1:38:01:7d:d8: d6:f2:c4:d8:58:b5:59:0d:b9:05:45:62:59:34:54:56:49:c4: 2c:f4:bd:17:a0:f2:72:e3:63:c3:69:40:55:e8:a4:57:23:38: e5:5e:f2:b0:3a:ee:27:b4:0e:ca:5e:a9:55:60:db:4d:30:ad: c5:13:d3:a4:ed:49:ff:c3:4a:e5:82:9d:5d:c6:ad:62:d9:49: 90:d1:0f:5e:89:1b:d7:f3:c1:3c:45:dc:84:09:b2:77:c2:fe: 47:9d:90:d4:f1:6c:54:20:a9:0d:9e:f8:a4:b9:55:c9:22:ef: 30:d1:d2:59:ba:ae:c1:d2:60:44:83:7f:0a:eb:36:ed:e2:0e: 7c:67:b3:c2:0d:25:bd:75:36:d8:af:ad:62:f8:f4:80:8f:ae: ec:e7:1c:a6:1f:f5:ff:8e:8b:c8:28:03:d3:de:08:4e:26:e1: 61:ce:3d:24:93:9b:da:d7:f7:8e:15:5d:32:55:5e:c9:7f:6b: 0d:a8:f7:b2:73:85:2a:63:25:93:37:14:ce:64:cc:f6:07:a1: dc:29:f6:53 -----BEGIN CERTIFICATE----- MIID0zCCArugAwIBAgIBAzANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjAwMjI1 MTQ1NDE5WhcNMjUwMjIzMTQ1NDE5WjB4MQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxEzARBgNVBAsMClByb2R1Y3Rpb24xFDASBgNVBAMMC3Rlc3QgY2xpZW50 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv2qlzWZqHSBIOvH/YZ39 HxgmoENMsEy5jU590IHgQ4GecHXLxFdJPIQ0UUWinwBQINZfNDwCu2kvZEooIeOV QehQBPO/8lqeJ2Rbs7xJljYQVgZHGsrbrW/j94PcQjcoB1inbyZFt2lvryhi+H6Y mCEKptqu1Uv+2wkatHXVCTsTnjOetNZeIeb7Nwm7GlbhXWS8WneZrIHMK7ebSbbo ui4y2Z6OTS78F9A3RA81qa/xRLvLLCp18H66thpzMtYfTDubOPDpIgY8lGtfaeS+ L/qcxJ58wN3CPFO4KMp3oJZrnMs/RLHFUXWJoBa6gmP3xCR/BolYRRBp5Jf1Nf5+ lwIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdl bmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUNlEruz63ayt/1IauZ3XCAVRb cjwwHwYDVR0jBBgwFoAUqlpbHJEymz+bw0Js0mj2p+DPvuAwDQYJKoZIhvcNAQEL BQADggEBADJwUfDCNW+D47zz8m/peeapUdBp+vuoqNRZxMTum1mazqgufnGlI0wn duW24W29pCTxOAF92NbyxNhYtVkNuQVFYlk0VFZJxCz0vReg8nLjY8NpQFXopFcj OOVe8rA67ie0DspeqVVg200wrcUT06TtSf/DSuWCnV3GrWLZSZDRD16JG9fzwTxF 3IQJsnfC/kedkNTxbFQgqQ2e+KS5Vcki7zDR0lm6rsHSYESDfwrrNu3iDnxns8IN Jb11NtivrWL49ICPruznHKYf9f+Oi8goA9PeCE4m4WHOPSSTm9rX944VXTJVXsl/ aw2o97JzhSpjJZM3FM5kzPYHodwp9lM= -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/client-encrypted.key0000664000175000017500000000332713626052637020375 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,D72CFBC7CD65D7FB vNK1aAAQQ+mBvJuQh9hM34Vn+yqj+ISIP5bkrtwfGIjTnnN3KNbCqUPhVTaO1uz9 YA1qpCpr+64oLjpcPBZ1tIVhVwcIoq8/nCJKiWEA7/zICDq1f2x7t3JP5NoP9TlD GaAm77JmriUZY0/DEyVBLhRyRIasO3tQSKnmHY1IHI1xalmxK46FTF8YsNpUr5bu UdhUyfslVVFxgSArrrQfPi6GS/ik/4Kr9RZUb3U3Zx1xxACGIDudQIYlkSzy0Ye5 7ff6JS3Y3UzPi//RKBUVWxqSwPlv6KqfNLQ+vNB4mnILSMmxHrOVY2bB+6c5OdP9 LSqDF/Rt+Xga9FraibHtvkrZsr3zQ6IlFt6sjvnN5K2v8d70wep2+lS8o7ljaQkp dgvP5YcWhdpMA5ye7JlVQOq7ApmIP1/MhlpLeH7gSZpazKvjQHzPLhjMTjJgDZLj lHn3z0+iLIY7Jt9O0NCKHcGvc96A0y+CPt5OaXYLzbnAZXr3HXwB0t85L9FXtZfp DL0uFgzQavqQagR6fQvN+F2D/jK3aMA1BmOAlTXl19OgEeXRulltKQfKrE+66W99 HVfRxapJMdtIvbZ4unzC4AHmLoDhTF2ryA0U97JeIta3NAk0D1gR9Q3uTWL3FKaO 4zyTnkUmhEe1xOkXu69n6FannSE0HlyuceX/9VvnPobEXAfs1C5Z3GQ+6WlXtQPh +Aaa0mkEG9zukXf1txDoOokXuKHFqQj731MxMj6ah99FBTvr+FNHIj0TpmmQKUBU 8oufr1E2tUiRwcGD9jGOd7RUJ9Yg4haSeEF5fJfyfIiEa2Vfd+FwuZ31xkC1pf0r un456DMT+TwcoCjgGabD5WrRlrIWwcBanwpktiGuDb0B42SZjo6Hb0UxIuialtis l/bF1HdTQU8uNwA85M2zKWW8nELQxtp8+sebkOJW+hocNuGNMa8R+2rLXrrKnaIY JcWSXHEKbNSVFHohEDHJlC8OTHqhOWf1dqBg23po9PJGcNGmRXnsW1s5I3LMVIuV +wy8boQZHY/3OYeHmVfvHpnR1XIz1uOGEyX3jl/pvrlmNnkfF8ZWewcpSarORwSa PGulUbsVbG6gXtn4A0cgf2XsbnlB5id1IGzbmeVO/7NMSbqrvucOeHTJWWMNItEk 6DNnU4k8i0LI/qXSld9d67nqEaYPQlesENASnhAAekMNC6qwrn0CeK/Hw6kKv/y7 TsMMsC8bSVCUgHDu1s3GeJ/ziAbmAebw3mdsO6r9HDszlhpqU4htJWmZG8PT9XKy f5RoIM039FZFF34T4dZQTJ6AdgIRjtTE/ViOBoQxRd6sHlsBQjX2i2NqHwIifGpS y9l4F/AzkpCCxxdey2ueupU9EEGWTifIFH3L0nwKbtDU/PUbSUx0wQTfD4PoB3ll 1EI+jJGvFqkvlPmKBroMbo6ckd7j7PZba7koiDV4QA2ALDHUruSM8rbVGbF4fplg a29WU16BNWPIjrjVYwKBh0571jl8tleun63tvRQ3Cma+QOFJtyYaX01LqYed48od 19o/XiAarErs077YcrBsiNASBLILTr0QR87oLDNQWLbJghRUCUGV5TVifUnAr2tO -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/test-fake-root-ca.key0000664000175000017500000000321313626052637020343 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAz3gLAskD7FfF/Y3XBkqJih1Jak0qLRCgoGUA3ev35YXid/Op +QMuoP9+8B/qrz+Zem6UxsTy5Il6z3ByrNImG+uXuL8yFF9DJsViY5akZ0Zkn5WR 0ZSw2/9k1xgBTpyl+6e4ydjzWgNwNx3UW8uVFECltsuE6OkaVoDFMGRNkb960sJG lPmM34PhdhsWaNZUqNCrRGfGkpz/0AvgYRh/qQ/mHji4EvNOmmtFPNpiBimOaL4M lNZp/XChgsEo/bxiInTorz/cNCWMMRFy4176dmUtqN2rKriExdFYTCMLO1K78p8h RTi5o8ZlUY6DaBFGpMdP87h3tGAs/JG5INMroQIDAQABAoIBAEoBBuRycYzPbldY Tff3hIIYmkRpy/6RLMqp3JpMfnuHu1WQO/QP94UEPfJHYD4s0IFEipswS3fLtlvi P3V37JIPAmqrAKEVre1ZgRQG+xO/n0rxXjdE86U1v3GeJXE2HVrb4+VUFtHn4hI2 +LXZs46q1LGUfQ9bfsKWYkA1txmicBMcWho5ugTe0h/LucwOFE1CUg6bBr1BJhpK t2HCOE3vAnYZA9Zv/KowECP0PL5nw37Fpqvqpkr67j12q7z8XGAeqnl6HtLUZOVU AwSvgLcGgKsRaDTmLLwnwEvOWe3yZvC80uO8FpI4JYiRH+O0e6v5S5yW+KS+Ogl0 cAD3WAECgYEA75AZzAtOG8P19mfcPzYydR2RYw1gEVGYXVeCZFlcSpBHhgQUXFaU TJmTHZoIQ5Mmf7csjzc9FSExACLWmuQDzg6+c9Y7lETcBKLf/5/za/q1x1ExXQ+3 pAA3SYBsFAFy2npI5NOGx2y118Z+eXYRTeW6oJQhdncdDXH339jiwEECgYEA3bQ2 8q9i90LQsnGKC45/d+laS2nXbroU+DNtfIz390m9rAjjmy4625BIXY7oaEua3D9s 1QK8S6eYEVUsoXzFaLHxPAstKyJhxFYPR4++EUZ7ro7BZMJ2AJSq7aFWpOpjlsAU Olt51Ijh1sOpK/X1xbAifi7c3ocpGGILYg3Dk2ECgYEA11tghXiIQBearmdRrJWp KHVrNHNasFb8tLStaE6Y1AL9+TEDqLrAWFga05qb4TuQeXGOojSTOcJ7zVaEO/vM m9nPRk0JhFGexKAy5BbDeoeIEGUiDjnJ6am0CeRjxFxFBri1fNfXKsHEevRa0A/e oHtrmV1w85FC0cppfZb4yMECgYARY1T7662DXwYnOKhvB5oPuYmPaJmw4X9LiB0K K7Q2/N2XZIsVXKbZGZPTYqXvqB5ZL9BFVJWYCWjv0xJRCAwjjfExmF7Ohz/LukQw hKGPkUuaATBBys6edQqC4Kh+/rMY26+6c/o2JRYxVd8qx3ujKZFK/DnuagNbGjVy V0oDgQKBgBKjvOnQhFx5yGKiHUNoAFcq7y5QdpvMHUfAtsz7qHHdCEkUbJ9DqjRk j3Pwn/iR7pAXYVN1s+jmLfFTlFjLqFNXe9+TYKgnMWkKZA+9dTsryD77BJj3fhLH SbvXQs/GvYAc8xIrB5pSTIRe8r2B8PaEUjiG5rtjIHT5F5G0y92M -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/client.key0000664000175000017500000000321713626052637016400 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAv2qlzWZqHSBIOvH/YZ39HxgmoENMsEy5jU590IHgQ4GecHXL xFdJPIQ0UUWinwBQINZfNDwCu2kvZEooIeOVQehQBPO/8lqeJ2Rbs7xJljYQVgZH GsrbrW/j94PcQjcoB1inbyZFt2lvryhi+H6YmCEKptqu1Uv+2wkatHXVCTsTnjOe tNZeIeb7Nwm7GlbhXWS8WneZrIHMK7ebSbboui4y2Z6OTS78F9A3RA81qa/xRLvL LCp18H66thpzMtYfTDubOPDpIgY8lGtfaeS+L/qcxJ58wN3CPFO4KMp3oJZrnMs/ RLHFUXWJoBa6gmP3xCR/BolYRRBp5Jf1Nf5+lwIDAQABAoIBAQCxu6DAG3wkFzl6 IgFy7nN9T7tty4+Fk3gm0N7Zn/5QMCahXX8ai8Ggw1CgtfvNj0jXdLVplt8ijQRI JuMktGB+lerW7k0oByQah4DuXsIlC4YXmjSjmABqBh6yUGlPwk8Uoyi0d+D78JaX GPTsrv+ZIfT2AM+dlbbKQqXdMhvhOLHn+p8+j5iX4UMt5UY3wbVH9gu4nTSG2Sce +OKRbOynCleYtlhpkVx2J2f3szxz/FBGjywX/9EMmJvOg3uvJ74lxYEB3e5RQdnZ FAxRlh+S54u1AjqFjUjLtWFgYjrQfmwtEA+GYGDwQK8CZJKEN8ARkNl4SzNu+qj0 mDfWIzjBAoGBAOhhBCY/k6rwa6RjwArEX4KpTkAISo3esBC8IF7rIDWrvK0c+hqY QO8Zdt2vnJNO2e94c7WXLZ90FGan2vD7E9ICEU4fC2Rk3xdMUSpTFToKRvWvD7Z1 RhOYkOLz904t391UdQrhT3DnIZ+05XbheR9GJWS2SImbCqjlzI3aFTOfAoGBANLf tIwf6k676mOigJ0ueNI3/Hz3UbnJFWeqwclgQbpCQpzLeexyKrkTZqslxnge29hb JrQrem97WSVC8EqXU3PI/0chRYUUL2UdGX6nKlBL+MDLbGoUkRNqrBxhUajBT2Yq 3tONIlHsFFd843dAr90DZxoj8WYA4NnaW4xR0ZIJAoGAeBWiek2CduSVC7eMh0Ph g3kQeeCO/m9kltFQ/RwOYg3ki6Uczd9+NtD27yqQBEPMNYcObHm6Vts6q630Y3Gs VWtCHBfI4FGMQ9LpYrDamEq1TsLvoL9LvlaqEM44L4tfU1YQwdWbIuIeKxTlO6Da 4cFzE29rXsjjIlLWeTuIl0sCgYEA0Mak5VqvyzXnUK/RsE0TV+YQN9VQ96SraZC4 /dwsFvGFK+GUm9FIlSYtLuNehQzgUmukfRrSxE8WKnsEloUOHYNxooXBY4lhhzVx SWDN1uPwq0h71Ob534RsVEjR5UdGifuF02NXCE64sQm31xiXRTUaPdo6JOhXtbin jNxwpakCgYEAoGkfZxUd6yZtNLmEKUwFT4/1edMg9XdyZggbfkaM2acn6cCk/XdJ zZSDcvnNyui30Amuiiin40QWX0OizeTnUS73knPTitQIb0+YEXp6NTKKsc1Frn6w pGjTOoVH4PDwBGs7vSO8uip6gdeGI1bCAK5zKeWR5gHE/UCrP/WQXy8= -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/openssl.cnf0000664000175000017500000002707013626052637016566 0ustar rogerroger# # OpenSSL example configuration file. # This is mostly being used for generation of certificate requests. # # This definition stops the following lines choking if HOME isn't # defined. HOME = . RANDFILE = $ENV::HOME/.rnd # Extra OBJECT IDENTIFIER info: #oid_file = $ENV::HOME/.oid oid_section = new_oids # To use this configuration file with the "-extfile" option of the # "openssl x509" utility, name here the section containing the # X.509v3 extensions to use: # extensions = # (Alternatively, use a configuration file that has only # X.509v3 extensions in its main [= default] section.) [ new_oids ] # We can add new OIDs in here for use by 'ca', 'req' and 'ts'. # Add a simple OID like this: # testoid1=1.2.3.4 # Or use config file substitution like this: # testoid2=${testoid1}.5.6 # Policies used by the TSA examples. tsa_policy1 = 1.2.3.4.1 tsa_policy2 = 1.2.3.4.5.6 tsa_policy3 = 1.2.3.4.5.7 #################################################################### [ ca ] default_ca = CA_default # The default ca section #################################################################### [ CA_signing ] dir = ./signingCA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of # several ctificates with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = test-signing-ca.crt # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number # must be commented out to leave a V1 CRL crl = $dir/crl.pem # The current CRL private_key = test-signing-ca.key # The private key RANDFILE = $dir/.rand # private random number file x509_extensions = usr_cert # The extentions to add to the cert # Comment out the following two lines for the "traditional" # (and highly broken) format. name_opt = ca_default # Subject Name options cert_opt = ca_default # Certificate field options # Extension copying option: use with caution. # copy_extensions = copy # Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs # so this is commented out by default to leave a V1 CRL. # crlnumber must also be commented out to leave a V1 CRL. # crl_extensions = crl_ext default_days = 1825 # how long to certify for default_crl_days= 30000 # how long before next CRL default_md = default # use public key default MD preserve = no # keep passed DN ordering # A few difference way of specifying how similar the request should look # For type CA, the listed attributes must be the same, and the optional # and supplied fields are just that :-) policy = policy_anything [ CA_inter ] dir = ./interCA certs = $dir/certs crl_dir = $dir/crl database = $dir/index.txt new_certs_dir = $dir/newcerts certificate = test-inter-ca.crt serial = $dir/serial crlnumber = $dir/crlnumber crl = $dir/crl.pem private_key = test-inter-ca.key RANDFILE = $dir/.rand #x509_extensions = v3_ca x509_extensions = usr_cert name_opt = ca_default cert_opt = ca_default default_days = 1825 default_crl_days = 30 default_md = default preserve = no policy = policy_match unique_subject = yes [ CA_root ] dir = ./rootCA certs = $dir/certs crl_dir = $dir/crl database = $dir/index.txt new_certs_dir = $dir/newcerts certificate = test-root-ca.crt serial = $dir/serial crlnumber = $dir/crlnumber crl = $dir/crl.pem private_key = test-root-ca.key RANDFILE = $dir/.rand x509_extensions = v3_ca name_opt = ca_default cert_opt = ca_default default_days = 1825 default_crl_days = 30 default_md = default preserve = no policy = policy_match unique_subject = yes # For the CA policy [ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional # For the 'anything' policy # At this point in time, you must list all acceptable 'object' # types. [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional #################################################################### [ req ] default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes x509_extensions = v3_ca # The extentions to add to the self signed cert # Passwords for private keys if not present they will be prompted for # input_password = secret # output_password = secret # This sets a mask for permitted string types. There are several options. # default: PrintableString, T61String, BMPString. # pkix : PrintableString, BMPString (PKIX recommendation before 2004) # utf8only: only UTF8Strings (PKIX recommendation after 2004). # nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings). # MASK:XXXX a literal mask value. # WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings. string_mask = utf8only # req_extensions = v3_req # The extensions to add to a certificate request [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = GB countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = Derbyshire localityName = Locality Name (eg, city) localityName_default = Derby 0.organizationName = Organization Name (eg, company) 0.organizationName_default = Mosquitto Project # we can do this but it is not needed normally :-) #1.organizationName = Second Organization Name (eg, company) #1.organizationName_default = World Wide Web Pty Ltd organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = Testing commonName = Common Name (e.g. server FQDN or YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 64 # SET-ex3 = SET extension number 3 [ req_attributes ] challengePassword = A challenge password challengePassword_min = 4 challengePassword_max = 20 unstructuredName = An optional company name [ usr_cert ] # These extensions are added when 'ca' signs a request. # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # Here are some examples of the usage of nsCertType. If it is omitted # the certificate can be used for anything *except* object signing. # This is OK for an SSL server. # nsCertType = server # For an object signing certificate this would be used. # nsCertType = objsign # For normal client use this is typical # nsCertType = client, email # and for everything including object signing: # nsCertType = client, email, objsign # This is typical in keyUsage for a client certificate. # keyUsage = nonRepudiation, digitalSignature, keyEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" # PKIX recommendations harmless if included in all certificates. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer # This stuff is for subjectAltName and issuerAltname. # Import the email address. # subjectAltName=email:copy # An alternative to produce certificates that aren't # deprecated according to PKIX. # subjectAltName=email:move # Copy subject details # issuerAltName=issuer:copy #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem #nsBaseUrl #nsRevocationUrl #nsRenewalUrl #nsCaPolicyUrl #nsSslServerName # This is required for TSA certificates. # extendedKeyUsage = critical,timeStamping [ v3_req ] # Extensions to add to a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment [ v3_ca ] # Extensions for a typical CA # PKIX recommendation. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer # This is what PKIX recommends but some broken software chokes on critical # extensions. #basicConstraints = critical,CA:true # So we do this instead. basicConstraints = CA:true # Key usage: this is typical for a CA certificate. However since it will # prevent it being used as an test self-signed certificate it is best # left out by default. # keyUsage = cRLSign, keyCertSign # Some might want this also # nsCertType = sslCA, emailCA # Include email address in subject alt name: another PKIX recommendation # subjectAltName=email:copy # Copy issuer details # issuerAltName=issuer:copy # DER hex encoding of an extension: beware experts only! # obj=DER:02:03 # Where 'obj' is a standard or added object # You can even override a supported extension: # basicConstraints= critical, DER:30:03:01:01:FF [ crl_ext ] # CRL extensions. # Only issuerAltName and authorityKeyIdentifier make any sense in a CRL. # issuerAltName=issuer:copy authorityKeyIdentifier=keyid:always [ proxy_cert_ext ] # These extensions should be added when creating a proxy certificate # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # Here are some examples of the usage of nsCertType. If it is omitted # the certificate can be used for anything *except* object signing. # This is OK for an SSL server. # nsCertType = server # For an object signing certificate this would be used. # nsCertType = objsign # For normal client use this is typical # nsCertType = client, email # and for everything including object signing: # nsCertType = client, email, objsign # This is typical in keyUsage for a client certificate. # keyUsage = nonRepudiation, digitalSignature, keyEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" # PKIX recommendations harmless if included in all certificates. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer # This stuff is for subjectAltName and issuerAltname. # Import the email address. # subjectAltName=email:copy # An alternative to produce certificates that aren't # deprecated according to PKIX. # subjectAltName=email:move # Copy subject details # issuerAltName=issuer:copy #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem #nsBaseUrl #nsRevocationUrl #nsRenewalUrl #nsCaPolicyUrl #nsSslServerName # This really needs to be in place for it to be a proxy certificate. proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo #################################################################### [ tsa ] default_tsa = tsa_config1 # the default TSA section [ tsa_config1 ] # These are used by the TSA reply generation only. dir = ./demoCA # TSA root directory serial = $dir/tsaserial # The current serial number (mandatory) crypto_device = builtin # OpenSSL engine to use for signing signer_cert = $dir/tsacert.pem # The TSA signing certificate # (optional) certs = $dir/cacert.pem # Certificate chain to include in reply # (optional) signer_key = $dir/private/tsakey.pem # The TSA private key (optional) default_policy = tsa_policy1 # Policy if request did not specify it # (optional) other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional) digests = md5, sha1 # Acceptable message digests (mandatory) accuracy = secs:1, millisecs:500, microsecs:100 # (optional) clock_precision_digits = 0 # number of digits after dot. (optional) ordering = yes # Is ordering defined for timestamps? # (optional, default: no) tsa_name = yes # Must the TSA name be included in the reply? # (optional, default: no) ess_cert_id_chain = no # Must the ESS cert id chain be included? # (optional, default: no) mosquitto-1.6.9/test/ssl/server-expired.key0000664000175000017500000000321313626052637020062 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAlQ307vLI+IQjeK9zU3h4lf3Npv39D8fuHDnnPNUrrB2rkumN 38EVN0A90baWeOxOY1RTFNSdvEJt2V07ztTQpfHvMlrHYxssAaf0npo5lcRwAvqP 0tH8DFFO4ZFUiO4NwfBqF30FnvIuuO1Js0FwIZS0AiK//3kN+zi7oT3AqWBeORiO B0gVEHuwASsrNYxnvoVwz7qZvKgdUD+s2TKR6lnESnpyXSgeQ1sLtcDQnazFaMnl 7z7PWATmmU4hfMCAnYj0icrTF+F3+jGMfRQ+r+AW+GcoSxi7/cNKZB/HJjsM2wTn ETUTmcqcJYdI5mDyoe98wl/DAu5MJzLaIHZweQIDAQABAoIBAGp3BJtkaS4xXBDI 6UwWwbMJDUqZIpeSC763kTZ/YOlYbAPMtNy80oWbakyP6ZzH1RnX0lwPnfcpT8Mx eBW9JqdRTrQd6UsdzmoEaJKcwEL8g7Fs/SvtduXpcblmkAYaW1NKgMz0LP6iJ8NJ IhpaxFgIGidoYNF+ywDFPifmruWLa9OOQNv3fFrLHfLaZnoO/jdk6uMPMuoTsaV2 VgkzTlyQ+6VkBKB0j1VKGJIPsQglrw2kTdlucyWD6J5Lymex38nfuu8hVwIMZYxj eC0lxLllNagu6RgRx4PYmOv4041dP39MxAuLfawWz61/gXxzhaiBvUI9SXvLmWY+ hhyfFXECgYEAw3v+dBXCUSsQ/TU0AQCukGvzWYdgksZN5mK2Jq1dkdvVbgWYdrcv sY05n0ejrojouLShVdXY7hktzG122nZLuZSN8Vb8enV/FjM5s+JZi6DRSZJ/9KQN sklutALXyDsfxcvqnAZkznx/BRF2Ny1ZPuWewInFNP5B+OJ4u+GLjK0CgYEAwzJt 3VvfVNsqagHWM94L+tiDBHQjz0Wiv69wZzcCJcaVfGly8F0Uyt/DHs4cl1l3aKS3 04wgVHkowvm//MoApRYNt4LS80BnL42NFinPT+L+/eNETRUheSOEFzdi2aXAmD2G ojaVON9BKvr69BfSHNtSQFpX3qZYyczS8c41wH0CgYBYs+jwb/cusaYR35RraA3O Bs3zsBRIRaePhPc2cbBlwSUFuZBHPjRsErM07WL+ja1cMsqKknDPCanYe0tVMhyG ZzxJaLlEMBCs2C20zF7plt2gztM1BUQZxGxxTmDvwLRYIoGgrt4LPD6+4/+KZg97 FOKGZ32O4Fi7QLicOGoEOQKBgCxcU5eQ/4pbXKJG1JVpCzPw7KWgd1rtqnUBu/vZ BoXrQaHKnTJ/FPCeNcvUb679yCNh+9z55YcNGfRlqfobNlZOUsO32ZUqt8iY1M2K pvCy19x/P9B80uSi66wTDEYGY2S15tkKqpMIOdk4vLuohjnEpka1wW56Q4dpIy+M +65JAoGAYV8oukeeucSAIB74AdP6F9NP1HQc2RQT6lVYQRkSwuhRi1rEyelati/Y bezK5vsHPaNQcTM0IJup0MSQjslm7NU06xiW+jE5YCbaqTzwto1YB9U9NnOI3Cd7 2kwcJzEAvgJNEbGvHVE1c0TQh7/5YePfY+smrlpLdGF5IwsU0Fw= -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/ssl/readme.txt0000664000175000017500000000015413626052637016403 0ustar rogerrogerThis directory contains certificates and keys required for SSL testing. The CA key has password "password". mosquitto-1.6.9/test/ssl/test-fake-root-ca.crt0000664000175000017500000000252313626052637020346 0ustar rogerroger-----BEGIN CERTIFICATE----- MIIDwjCCAqqgAwIBAgIUJtJNmR2IUunoKAPzp6GCdwpeRGkwDQYJKoZIhvcNAQEL BQAwcjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEQMA4GA1UEAwwHUm9vdCBDQTAeFw0yMDAyMjUxNDU0MThaFw0zMDAyMjIx NDU0MThaMHIxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApEZXJieXNoaXJlMQ4wDAYD VQQHDAVEZXJieTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNVBAsM B1Rlc3RpbmcxEDAOBgNVBAMMB1Jvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDPeAsCyQPsV8X9jdcGSomKHUlqTSotEKCgZQDd6/flheJ386n5 Ay6g/37wH+qvP5l6bpTGxPLkiXrPcHKs0iYb65e4vzIUX0MmxWJjlqRnRmSflZHR lLDb/2TXGAFOnKX7p7jJ2PNaA3A3HdRby5UUQKW2y4To6RpWgMUwZE2Rv3rSwkaU +Yzfg+F2GxZo1lSo0KtEZ8aSnP/QC+BhGH+pD+YeOLgS806aa0U82mIGKY5ovgyU 1mn9cKGCwSj9vGIidOivP9w0JYwxEXLjXvp2ZS2o3asquITF0VhMIws7UrvynyFF OLmjxmVRjoNoEUakx0/zuHe0YCz8kbkg0yuhAgMBAAGjUDBOMB0GA1UdDgQWBBRU Cz3bp0AtTrVrLL/JDJwIXvG3WTAfBgNVHSMEGDAWgBRUCz3bp0AtTrVrLL/JDJwI XvG3WTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQC8iqJSyJOCPJak f6DEinKJzQde5aYvkswyJ1gVKVQztF50bPUsXHHrQNP6Vvk8U/EFWWqYqJQ3Mk6/ t262FxS1wTllhddNu9+YfXA7yO38GDfcsr4uBTylxOTJY7lI+aRn5oOn6A9OuQcV m1HjE5QQiV8JXAl80JX29FYxSVDmDjLG+48GMhIHNhtYH4IS/jZFyfwbn+JeolEB NeGUtwryMAJqnptsIXen85mW/6j33/d7n1nabVa6Mo7V/07eE0uC45Ngmi2isOxB 23WEhOkJRANNbm9fK6qn8YMAzsGvx9O4SeQEUdp2Yd/jTvdgIBB+Ewzem8Pmn53C 7fgo0LjB -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/rootCA/0000775000175000017500000000000013626052637015574 5ustar rogerrogermosquitto-1.6.9/test/ssl/rootCA/serial0000664000175000017500000000000313626052637016767 0ustar rogerroger03 mosquitto-1.6.9/test/ssl/rootCA/index.txt.attr0000664000175000017500000000002513626052637020412 0ustar rogerrogerunique_subject = yes mosquitto-1.6.9/test/ssl/rootCA/crlnumber0000664000175000017500000000000313626052637017501 0ustar rogerroger01 mosquitto-1.6.9/test/ssl/crl-empty.pem0000664000175000017500000000122613626052637017025 0ustar rogerroger-----BEGIN X509 CRL----- MIIBwDCBqQIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjETMBEGA1UE CAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNV BAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EXDTIwMDIyNTE0NTQxOVoY DzIxMDIwNDE2MTQ1NDE5WqAOMAwwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQAD ggEBADXrRSpMfj+Iuz/Uy/ti4k0Qx+H/e93pown8Cgx/w9FwtsTsaTKOff0r3uKb KpKJJ4BSkysUOaZ72cLoooNYoEcYgpcqx3PlhmjuBGcOH1YG5ca+nzIayZgQe3Nl hGBvYfpX+YMpG7gHy5WPxi0T+uUF7XfTEfpmw8asVSZvZNy0nMB3cZCCA4yiICay vaOIrrHshSlDPw6iafhcBNLAdq5Xz+KF4Pv78Wfs+zwnm0BzRGtVB7cWCaGvUi3v dAqzzBsdP0naFYVaZ1BJcE06Dn5O6LSA6snOswCTGOYI50zMZzRXkUo3pZ/xqVPc Cdo6QspVlxGedSxXD13KbGPAoak= -----END X509 CRL----- mosquitto-1.6.9/test/ssl/crl.pem0000664000175000017500000000126213626052637015671 0ustar rogerroger-----BEGIN X509 CRL----- MIIB1jCBvwIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjETMBEGA1UE CAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNV BAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EXDTIwMDIyNTE0NTQxOVoY DzIxMDIwNDE2MTQ1NDE5WjAUMBICAQUXDTIwMDIyNTE0NTQxOVqgDjAMMAoGA1Ud FAQDAgECMA0GCSqGSIb3DQEBCwUAA4IBAQCMM5PyBAY5BuNVk0k2Bqn5FvlIrSnS LMZaoUVG/OtgjMD6g47dSXVHgIXmuFu3Bp44mRM85ZVd1URjmjR4ZwfVfcprkqo7 L655K+nyPUoq5IZh7y4MKVYwbEfetu0HjWuOqFI9T7zalOF9MfeoOx6u93CTgUvy 1s5EVnG0d0qon3CEHTJwpzYQDgXVesUX0ZqNwvKnMGQhB8YQ/NOX807xQR5Ckl7s 6CYkAySe84lMascnwe1nFp3nGIxbOTxXqohWkvscM6933+veisgh6F4p63oF4rKs Xr93Bf9FsvwfitI/PfMWkKzFEEaZTjAM26ioLgBBcBxxIJleLysyudd2 -----END X509 CRL----- mosquitto-1.6.9/test/ssl/client-revoked.crt0000664000175000017500000001071513626052637020036 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 5 (0x5) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Feb 25 14:54:19 2020 GMT Not After : Feb 23 14:54:19 2025 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client revoked Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:d3:04:65:0d:da:e3:e6:66:d2:cc:40:05:24:fe: 17:67:40:bb:6c:35:dd:18:2c:70:7e:20:d1:00:26: 56:b7:1b:4e:e6:3e:8c:6c:0d:e4:d2:c0:dd:71:30: 02:f7:a0:83:79:0f:15:94:cd:a3:aa:c7:d4:e3:15: af:0a:1a:b3:b8:54:b8:eb:f3:6b:72:3b:d3:f4:0b: c6:4c:a9:79:58:95:53:a3:4a:31:81:97:31:a1:67: f7:4d:9c:8b:02:b2:8d:79:b2:b1:87:3f:35:75:7e: d1:04:6b:fb:7f:44:d7:3c:c2:4b:73:99:ee:61:a0: 54:2f:47:a4:62:e3:e6:0c:bb:1a:88:8c:a1:94:8f: b5:79:d5:bb:be:75:f8:a7:e1:56:8b:dc:0f:90:9b: 94:45:50:fd:0b:7c:a9:bf:17:5a:0a:02:b4:15:3c: 88:fa:93:5f:1b:20:8a:c3:aa:c8:18:d1:02:27:38: 34:38:8c:ed:f7:58:50:20:53:9e:29:5e:3c:e9:f6: cc:98:37:1c:e4:24:7f:2f:44:39:42:31:7c:30:13: 0f:42:2c:c8:e1:53:ac:05:4b:e3:bd:7b:05:7a:d3: c1:14:ee:c3:06:75:64:5d:11:a6:be:4d:53:8d:06: 04:1f:1e:14:a7:8b:53:b9:aa:c3:97:c9:3c:8a:45: 6b:05 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 4B:8F:CC:F4:64:26:0C:0A:37:2B:D1:18:76:9D:AF:B7:D6:19:47:92 X509v3 Authority Key Identifier: keyid:AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 Signature Algorithm: sha256WithRSAEncryption 13:0e:0b:71:b7:f3:53:f9:4e:7b:19:20:89:4e:a2:bf:e3:a2: 5d:66:35:ba:02:ca:b5:b7:39:3f:4f:5b:47:b9:7a:14:c6:83: 28:02:2a:fe:68:56:d1:08:8d:e1:a0:c0:8b:8a:38:92:41:ba: 79:11:d4:df:8b:f5:1a:bd:ae:59:97:41:8c:4c:de:28:87:ce: fb:9e:ad:fb:22:48:d4:3d:9c:60:96:e5:35:71:b9:bc:24:ec: 11:e5:c8:96:1c:b1:ec:96:26:32:91:ef:a9:d9:d9:b8:3f:92: 9e:61:54:d7:b5:2d:f5:ac:89:4a:49:3e:8f:a9:b7:e2:39:7d: 98:5f:21:25:0c:71:16:e7:12:d5:e5:9c:01:6b:a8:50:65:ab: 48:db:a8:04:c1:ec:3e:ea:2f:54:30:f8:38:0c:90:fc:71:68: 56:98:a9:d4:b7:0e:bb:66:a9:fc:24:50:0b:b9:46:cf:45:56: 86:0c:7d:b9:e2:9b:ec:36:e4:c9:fd:96:a6:b0:f7:f3:c9:d4: 74:8e:6a:68:5a:2e:6d:6f:78:26:af:93:7d:9c:53:73:92:b5: 1d:c1:77:52:ea:2d:21:06:b6:3a:71:be:59:c9:51:a8:fe:89: fc:6c:e3:7e:5e:46:93:4c:eb:4f:14:1d:e8:05:99:95:7c:49: 40:c9:db:81 -----BEGIN CERTIFICATE----- MIID3DCCAsSgAwIBAgIBBTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjAwMjI1 MTQ1NDE5WhcNMjUwMjIzMTQ1NDE5WjCBgDELMAkGA1UEBhMCR0IxGDAWBgNVBAgM D05vdHRpbmdoYW1zaGlyZTETMBEGA1UEBwwKTm90dGluZ2hhbTEPMA0GA1UECgwG U2VydmVyMRMwEQYDVQQLDApQcm9kdWN0aW9uMRwwGgYDVQQDDBN0ZXN0IGNsaWVu dCByZXZva2VkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0wRlDdrj 5mbSzEAFJP4XZ0C7bDXdGCxwfiDRACZWtxtO5j6MbA3k0sDdcTAC96CDeQ8VlM2j qsfU4xWvChqzuFS46/NrcjvT9AvGTKl5WJVTo0oxgZcxoWf3TZyLArKNebKxhz81 dX7RBGv7f0TXPMJLc5nuYaBUL0ekYuPmDLsaiIyhlI+1edW7vnX4p+FWi9wPkJuU RVD9C3ypvxdaCgK0FTyI+pNfGyCKw6rIGNECJzg0OIzt91hQIFOeKV486fbMmDcc 5CR/L0Q5QjF8MBMPQizI4VOsBUvjvXsFetPBFO7DBnVkXRGmvk1TjQYEHx4Up4tT uarDl8k8ikVrBQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1P cGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUS4/M9GQmDAo3 K9EYdp2vt9YZR5IwHwYDVR0jBBgwFoAUqlpbHJEymz+bw0Js0mj2p+DPvuAwDQYJ KoZIhvcNAQELBQADggEBABMOC3G381P5TnsZIIlOor/jol1mNboCyrW3OT9PW0e5 ehTGgygCKv5oVtEIjeGgwIuKOJJBunkR1N+L9Rq9rlmXQYxM3iiHzvuerfsiSNQ9 nGCW5TVxubwk7BHlyJYcseyWJjKR76nZ2bg/kp5hVNe1LfWsiUpJPo+pt+I5fZhf ISUMcRbnEtXlnAFrqFBlq0jbqATB7D7qL1Qw+DgMkPxxaFaYqdS3DrtmqfwkUAu5 Rs9FVoYMfbnim+w25Mn9lqaw9/PJ1HSOamhaLm1veCavk32cU3OStR3Bd1LqLSEG tjpxvlnJUaj+ifxs435eRpNM608UHegFmZV8SUDJ24E= -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/all-ca.crt0000664000175000017500000001316713626052637016260 0ustar rogerrogerCertificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, L=Derby, O=Mosquitto Project, OU=Testing, CN=Root CA Validity Not Before: Feb 25 14:54:18 2020 GMT Not After : Feb 23 14:54:18 2025 GMT Subject: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:c1:a1:1a:6e:76:1f:98:b7:1c:7e:d6:67:d5:dc: 92:34:ef:48:22:62:94:56:cb:21:29:c1:88:7c:7a: 62:eb:6d:b9:af:8b:80:75:f4:8e:32:e2:20:e2:fa: 3a:49:c8:20:74:53:83:0f:c1:48:e2:13:3e:48:27: f2:e5:7d:55:c5:87:8c:41:9e:e2:90:58:8c:09:97: 1e:bc:5a:ce:10:71:b2:66:02:02:9b:0c:d0:24:47: 7a:3a:4d:3a:2e:c0:f0:65:6b:6a:cf:13:13:8a:f0: 6d:a0:a5:80:5f:6b:58:77:ae:91:6e:ba:ab:c5:c0: 24:f7:22:27:a4:bf:47:52:2d:a0:fc:56:b0:19:16: 84:e9:53:ac:1d:7f:29:af:c2:86:44:f5:9b:04:e4: bf:8f:e1:b8:61:a0:63:55:0a:7a:93:2a:d8:4a:20: b8:6b:b6:e9:20:c6:2c:c2:93:c2:dc:7a:69:90:8e: ea:00:5b:0c:66:8a:90:74:b4:d9:01:98:9d:fe:5b: 66:e0:39:19:22:50:0d:76:3d:1c:04:fb:93:4d:6e: 45:da:e8:cc:27:35:2a:a6:35:a8:87:e1:99:32:42: e8:71:eb:7c:f9:69:70:c7:cf:c5:cc:61:c5:ae:47: dc:20:86:2b:2b:fe:1c:dd:2c:e9:b0:38:b6:72:8e: 09:e9 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: AA:5A:5B:1C:91:32:9B:3F:9B:C3:42:6C:D2:68:F6:A7:E0:CF:BE:E0 X509v3 Authority Key Identifier: keyid:7A:89:5D:1E:C9:B1:72:2F:38:DB:DE:E7:D3:49:80:2C:01:FA:3B:74 X509v3 Basic Constraints: CA:TRUE Signature Algorithm: sha256WithRSAEncryption d3:8d:e3:33:87:f3:1e:4f:ff:da:1d:f8:61:3f:4a:ae:21:49: cd:ee:b1:e0:62:ab:44:70:a8:29:92:83:8d:33:45:4c:ac:b0: 66:a0:e8:32:23:76:ef:aa:89:7d:bc:e1:04:17:a5:d7:39:59: 99:ab:d9:bf:0c:fd:c5:b6:ad:6f:45:39:c9:27:f1:3e:c0:af: c3:8e:b1:1f:8f:fc:34:66:31:f4:f1:11:a0:27:99:a2:65:e2: aa:20:a7:98:b6:0e:ff:71:5e:10:e7:ab:1e:33:e7:fb:c8:59: d7:89:7a:3b:d9:a9:9f:48:2f:2e:ff:02:61:cd:86:47:60:61: 8e:81:71:68:f0:cd:63:72:b8:d2:7d:22:9d:6b:07:49:3a:0a: f7:8b:94:b3:98:90:3c:9f:e5:78:1b:84:a9:2e:fb:85:64:59: ce:6f:33:05:18:bc:21:df:f5:7c:10:79:d6:58:34:61:0e:1f: d5:af:b6:a0:8f:86:ce:56:d1:67:4f:b8:7e:50:2d:ba:77:37: 50:0f:91:06:dc:a8:7f:3c:8b:2b:8b:47:df:e3:7e:2f:79:81: 22:70:eb:f9:14:f3:66:73:17:33:e4:26:7e:47:df:80:89:de: a5:e8:5a:a9:c0:4b:3e:1b:9b:11:4b:3b:b4:8b:6a:9d:6c:ce: 39:f5:04:c9 -----BEGIN CERTIFICATE----- MIIDojCCAoqgAwIBAgIBATANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEOMAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1v c3F1aXR0byBQcm9qZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRAwDgYDVQQDDAdSb290 IENBMB4XDTIwMDIyNTE0NTQxOFoXDTI1MDIyMzE0NTQxOFowZTELMAkGA1UEBhMC R0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9q ZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRMwEQYDVQQDDApTaWduaW5nIENBMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwaEabnYfmLccftZn1dySNO9IImKU VsshKcGIfHpi6225r4uAdfSOMuIg4vo6ScggdFODD8FI4hM+SCfy5X1VxYeMQZ7i kFiMCZcevFrOEHGyZgICmwzQJEd6Ok06LsDwZWtqzxMTivBtoKWAX2tYd66Rbrqr xcAk9yInpL9HUi2g/FawGRaE6VOsHX8pr8KGRPWbBOS/j+G4YaBjVQp6kyrYSiC4 a7bpIMYswpPC3HppkI7qAFsMZoqQdLTZAZid/ltm4DkZIlANdj0cBPuTTW5F2ujM JzUqpjWoh+GZMkLocet8+Wlwx8/FzGHFrkfcIIYrK/4c3SzpsDi2co4J6QIDAQAB o1AwTjAdBgNVHQ4EFgQUqlpbHJEymz+bw0Js0mj2p+DPvuAwHwYDVR0jBBgwFoAU eoldHsmxci84297n00mALAH6O3QwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsF AAOCAQEA043jM4fzHk//2h34YT9KriFJze6x4GKrRHCoKZKDjTNFTKywZqDoMiN2 76qJfbzhBBel1zlZmavZvwz9xbatb0U5ySfxPsCvw46xH4/8NGYx9PERoCeZomXi qiCnmLYO/3FeEOerHjPn+8hZ14l6O9mpn0gvLv8CYc2GR2BhjoFxaPDNY3K40n0i nWsHSToK94uUs5iQPJ/leBuEqS77hWRZzm8zBRi8Id/1fBB51lg0YQ4f1a+2oI+G zlbRZ0+4flAtunc3UA+RBtyofzyLK4tH3+N+L3mBInDr+RTzZnMXM+QmfkffgIne pehaqcBLPhubEUs7tItqnWzOOfUEyQ== -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDwjCCAqqgAwIBAgIURMxcSM9J+pY3g2SE3qoM34dHwPkwDQYJKoZIhvcNAQEL BQAwcjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEQMA4GA1UEAwwHUm9vdCBDQTAeFw0yMDAyMjUxNDU0MThaFw0zMDAyMjIx NDU0MThaMHIxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApEZXJieXNoaXJlMQ4wDAYD VQQHDAVEZXJieTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNVBAsM B1Rlc3RpbmcxEDAOBgNVBAMMB1Jvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDdpftss7fN4lzDhppzwj2WfRehR95WYmiWnXoEsKyEfuh1hINs vvI3tz1FWEb/usORr6XGZhgYwjIpSORMoBxuOZh8RDNPmO9KpLYXN1i4g+CfkGAK QoBUr7FGGlKDaK4fRg6xx8BKQ1Lxqrx+iAOpIT7tU9YYPYrwiYbdhaYwfMTKXyCl V+JypRRKWgzUkua4YRb2TnEH33NaXS0Tw+A0tRxSN26vwRheCrVfo+6CUB0kEaON +syuiHP1mGrHj3bMh/MTd3H5u2lu+1GW/Re3HdGFLuHhEq6EkF0fnPCaPS+iJKwU 1LgQZwGc+UHglTmmqUS6xhpm++/950fYoaiHAgMBAAGjUDBOMB0GA1UdDgQWBBR6 iV0eybFyLzjb3ufTSYAsAfo7dDAfBgNVHSMEGDAWgBR6iV0eybFyLzjb3ufTSYAs Afo7dDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQB7/Zn0VBciDCXo JA4ZX5boZyQMx7Lm62O+ixChT2hW0VNlouacgfSq455sNxFJKam0ZQKzusMzssNQ ticyZUwIosGx36f8qBaGksx0EbgAh9QdOulsYDLW5UsB4Rh94C36NoTd9+BJF6D4 89IpuxQehDKKuRG0NUChEkLvJ2AAPi/+iDHZQMB/sAzaT4gJ4eMeY4p4XBb/a9P2 w05RCpVNyLg32S7ynLNUrz+/lZUfZ8sYhpdECbFDpb0e1iVc1vst8Pur+cSGFO3f HabwuWTdF9Xx8MaH/n32Pv8BxZ/hBdjsXa/CiMyT4POs6XGTpZ2iLcmHo8WS4Uls 5gKvsjuj -----END CERTIFICATE----- mosquitto-1.6.9/test/ssl/client-expired.key0000664000175000017500000000321313626052637020032 0ustar rogerroger-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEA0Fr7dQFn785qZhtEEWgNSdGOaDnzqHE4wx97/3e3Dy7oh9u+ SFwSb7r9PCLse90vR0LF25objsOePsFZUxlpfTf4cHW06ygJTojdsQ8h/EszmCqa 5u2NKnu0t8lTKMh2aTXyLj0xLEtR+SxzuasmAX6M738z7pnKrWGfYD2sEcgJe/0x 3X5+2GhpSaguKfCfYSS3Y12Yk3OWfm+mwjsFBZyC64fd9FYCwu8eNAIKnJ2afgxn m5F0oG5e9lJb9/O3Dv5ODhDk+txLkWK0SUJt6oSHSomODYpC8myCoZO9TaLwrQ+6 929gt3obmrXmQZLXOzfGebFwmms1akI68SCQtwIDAQABAoIBAHz1ZAQbcMOA740H Yz5xQi74kEjwILLwHJPhqRNhMBfaETmRz8BEAAakhcXwSBZNZFJ/uHxpI4fuyFRo z3KoNf0UeVqxLW0vWM2SBitvoPlX/LyRKM/Avr4w7QSgqNA30dRtty6GIpynG6Wu REWhYKzawhnNF09NSyHK/7PPqQgL8+3et4naoyTBfHryA1rSlAZmOAH9xWhbfTzH mWUazRp0kRQWQ/HCwQF4ZvXpE52K6U3OWhei440tJEPZDmrdKNrgFwxrBCUBWHuV ZP9N/SST52uzJS2t5oQ89jb8aH3zBz0bwwWNQgMBo1MV73JCsrO3RMyaWWSXNGCE fJ99JKkCgYEA+C/S61CAEd7eLBguQrY6EkyROf+SMVxD5DjXShpk/SsSuXY76Wu2 tpY0dNOjIGk1DIPmGdRtMcOg1RYDFcPF67lj6gwBgXk2qREUtdIzQ/X+3nVCaTCU /JuXQHTVnWYuYqT8Nd+IytKc4LrFWNpPDar0a6DSvd3QWQ95Tyg/f2UCgYEA1uom myPZxQRmXOwvm+u5ogA1NzCGOxMzpV/Ay2ahqC4as5AsnsL5xgIwYmGCpITYelQp 8FcQLgvHIHKZjHSSH/qxUvJelcthHp3WDoj2yeiH88AI56xN4pbSYHEZzq6/jyhN qykopsLpz67Qz2tn/on3DmjSrMcPqV1nblkHs+sCgYBnlM4al8ZbrwBattzXyuYB rSMPabLCFxfesDpqGwn6/3cZIFdw3ButqJLMD2gNptsVFhd6wEWyd0swo7c15jc8 Ymtoywn113kQpqhWGhx7SLfOcHH/JN+JbgZ6SEi/IF5LnUAF2/1jaPNAd7LVmodT 1P2dzckmpOTHxsWCW/HkYQKBgGn7uKQjLt5gyBYlB2lt+vJwBc48qMVzN7HjIZFt AGWOru5EOCzm3AQQykmJ6sI1HQhefvweA0Wh20YeHajNR85rc40DJy/ZxwAxOAGc +48glALZfcq6BwKp+/9BZ0esl50CdCLnPjvWvTUE8caIIhW9dc9uVA6OcCPGgx5A 23KXAoGAB1+qBe3rZZ7ke5PFNstASj4PqcwmZRxu7P7Xy6ziHsLTKvyx665IWd+F fdrFYWWP5tj+7CGzvLtD0nruAdGyECtmSCclH3iCmjjAWHQiqiZT4ShGzprkQj9d bsuhZ95e3mK7liSVujXl5neFWetyoj4MqA1OWjiNaEEUQ02NOlo= -----END RSA PRIVATE KEY----- mosquitto-1.6.9/test/broker/0000775000175000017500000000000013626052637015070 5ustar rogerrogermosquitto-1.6.9/test/broker/12-prop-subpub-content-type.py0000775000175000017500000000102613626052637022571 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # Does the Content Type property get sent through? # MQTT v5 import prop_subpub_helper as helper from mosq_test_helper import * props_out = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "text") props_out = props_out+mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS, 1) props_in = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "text") helper.prop_subpub_helper(props_out, props_in) mosquitto-1.6.9/test/broker/12-prop-maximum-packet-size-broker.py0000775000175000017500000000245013626052637024020 0ustar rogerroger#!/usr/bin/env python3 # Check whether the broker disconnects a client nicely when they send a too large packet. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("max_packet_size 30\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MAXIMUM_PACKET_SIZE, 30) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="0123456789012345678901234567890", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(reason_code=149, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, use_conf=True) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "disconnect") rc = 0 finally: broker.terminate() broker.wait() os.remove(conf_file) (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-tls-psk-pub.py0000775000175000017500000000362313626052637020057 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write("psk_file 08-tls-psk-pub.psk\n") f.write("\n") f.write("port %d\n" % (port1)) f.write("psk_hint hint\n") f.write("\n") f.write("listener %d\n" % (port2)) f.write("log_type all\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("no-psk-test-client", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "psk/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish(topic="psk/test", payload="message", qos=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port2) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port2) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./c/08-tls-psk-pub.test', str(port1)], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if pub.wait(): raise ValueError (stdo, stde) = pub.communicate() if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/04-retain-qos1-qos0.py0000775000175000017500000000251713626052637020716 0ustar rogerroger#!/usr/bin/env python3 # Test whether a retained PUBLISH to a topic with QoS 1 is retained. # Subscription is made with QoS 0 so the retained message should also have QoS # 0. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 6 publish_packet = mosq_test.gen_publish("retain/qos1/test", qos=1, mid=mid, payload="retained message", retain=True) puback_packet = mosq_test.gen_puback(mid) mid = 18 subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos1/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish0_packet = mosq_test.gen_publish("retain/qos1/test", qos=0, payload="retained message", retain=True) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish0", publish0_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos1-bad-pubrec.py0000775000175000017500000000361513626052637022054 0ustar rogerroger#!/usr/bin/env python3 # Test what the broker does if receiving a PUBREC in response to a QoS 1 PUBLISH. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1) suback_packet = mosq_test.gen_suback(mid, 1) helper_connect = mosq_test.gen_connect("helper", keepalive=keepalive) helper_connack = mosq_test.gen_connack(rc=0) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") puback1s_packet = mosq_test.gen_puback(mid) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") pubrec1r_packet = mosq_test.gen_pubrec(mid) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, puback1s_packet, "puback 1s") helper.close() if mosq_test.expect_packet(sock, "publish 1r", publish1r_packet): sock.send(pubrec1r_packet) sock.send(pingreq_packet) p = sock.recv(len(pingresp_packet)) if len(p) == 0: rc = 0 sock.close() except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-acl-change.py0000775000175000017500000001023413626052637017655 0ustar rogerroger#!/usr/bin/env python3 # Check whether messages deliver or not after some access is revoked. from mosq_test_helper import * import signal def write_config(filename, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("port %d\n" % (port)) f.write("acl_file %s\n" % (filename.replace('.conf', '.acl'))) def write_acl(filename, en): with open(filename, 'w') as f: f.write('user username\n') f.write('topic readwrite topic/one\n') if en: f.write('topic readwrite topic/two\n') keepalive = 60 username = "username" connect1_packet = mosq_test.gen_connect("acl-check", keepalive=keepalive, username=username, clean_session=False) connack1a_packet = mosq_test.gen_connack(rc=0) connack1b_packet = mosq_test.gen_connack(rc=0, flags=1) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid=mid, topic="topic/one", qos=1) suback1_packet = mosq_test.gen_suback(mid=mid, qos=1) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid=mid, topic="topic/two", qos=1) suback2_packet = mosq_test.gen_suback(mid=mid, qos=1) disconnect_packet = mosq_test.gen_disconnect() connect2_packet = mosq_test.gen_connect("helper", keepalive=keepalive, username=username) connack2_packet = mosq_test.gen_connack(rc=0) mid = 1 publish1s_packet = mosq_test.gen_publish(topic="topic/one", mid=mid, qos=1, payload="message1") puback1s_packet = mosq_test.gen_puback(mid) mid = 2 publish2s_packet = mosq_test.gen_publish(topic="topic/two", mid=mid, qos=1, payload="message2") puback2s_packet = mosq_test.gen_puback(mid) mid = 1 publish1r_packet = mosq_test.gen_publish(topic="topic/one", mid=mid, qos=1, payload="message1") puback1r_packet = mosq_test.gen_puback(mid) mid = 2 publish3s_packet = mosq_test.gen_publish(topic="topic/one", mid=mid, qos=1, payload="message3") puback3s_packet = mosq_test.gen_puback(mid) mid = 3 publish3r_packet = mosq_test.gen_publish(topic="topic/one", mid=mid, qos=1, payload="message3") puback3r_packet = mosq_test.gen_puback(mid) mid = 3 publish4s_packet = mosq_test.gen_publish(topic="topic/two", mid=mid, qos=1, payload="message4") puback4s_packet = mosq_test.gen_puback(mid) rc = 1 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, "false") acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl(acl_file, True) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: keepalive = 60 # Connect, subscribe, then disconnect sock = mosq_test.do_client_connect(connect1_packet, connack1a_packet, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") sock.send(disconnect_packet) sock.close() # Helper publish to topic/one and topic/two, will be queued for other client sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, port=port) mosq_test.do_send_receive(sock, publish1s_packet, puback1s_packet, "puback1") mosq_test.do_send_receive(sock, publish2s_packet, puback2s_packet, "puback2") sock.close() # Reload ACLs with topic/two now disabled write_acl(acl_file, False) broker.send_signal(signal.SIGHUP) sock = mosq_test.do_client_connect(connect1_packet, connack1b_packet, port=port) sock.settimeout(10) mosq_test.expect_packet(sock, "publish1r", publish1r_packet) # We don't expect messages to topic/two any more, so we don't expect the queued one mosq_test.do_send_receive(sock, publish3s_packet, puback3s_packet, "puback3") mosq_test.expect_packet(sock, "publish3r", publish3r_packet) # Send this, don't expect it to succeed mosq_test.do_send_receive(sock, publish4s_packet, puback4s_packet, "puback4") # Check for non delivery with a ping mosq_test.do_ping(sock) sock.close() rc = 0 finally: os.remove(conf_file) os.remove(acl_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) port = mosq_test.get_port() mosquitto-1.6.9/test/broker/03-publish-qos1-queued-bytes.py0000775000175000017500000001225313626052637022631 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with an offline subscriber results in a queued message import Queue import random import string import subprocess import socket import threading import time try: import paho.mqtt.client import paho.mqtt.publish except ImportError: print("WARNING: paho.mqtt module not available, skipping byte count test.") exit(0) from mosq_test_helper import * rc = 1 port = mosq_test.get_port() def registerOfflineSubscriber(): """Just a durable client to trigger queuing""" client = paho.mqtt.client.Client("sub-qos1-offline", clean_session=False) client.connect("localhost", port=port) client.subscribe("test/publish/queueing/#", 1) client.loop() client.disconnect() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) class BrokerMonitor(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose) self.rq, self.cq = args self.stored = -1 self.stored_bytes = -1 self.dropped = -1 def store_count(self, client, userdata, message): self.stored = int(message.payload) def store_bytes(self, client, userdata, message): self.stored_bytes = int(message.payload) def publish_dropped(self, client, userdata, message): self.dropped = int(message.payload) def run(self): client = paho.mqtt.client.Client("broker-monitor") client.connect("localhost", port=port) client.message_callback_add("$SYS/broker/store/messages/count", self.store_count) client.message_callback_add("$SYS/broker/store/messages/bytes", self.store_bytes) client.message_callback_add("$SYS/broker/publish/messages/dropped", self.publish_dropped) client.subscribe("$SYS/broker/store/messages/#") client.subscribe("$SYS/broker/publish/messages/dropped") while True: expect_drops = cq.get() self.cq.task_done() if expect_drops == "quit": break first = time.time() while self.stored < 0 or self.stored_bytes < 0 or (expect_drops and self.dropped < 0): client.loop(timeout=0.5) if time.time() - 10 > first: print("ABORT TIMEOUT") break if expect_drops: self.rq.put((self.stored, self.stored_bytes, self.dropped)) else: self.rq.put((self.stored, self.stored_bytes, 0)) self.stored = -1 self.stored_bytes = -1 self.dropped = -1 client.disconnect() rq = Queue.Queue() cq = Queue.Queue() brokerMonitor = BrokerMonitor(args=(rq,cq)) class StoreCounts(): def __init__(self): self.stored = 0 self.bstored = 0 self.drops = 0 self.diff_stored = 0 self.diff_bstored = 0 self.diff_drops = 0 def update(self, tup): self.diff_stored = tup[0] - self.stored self.stored = tup[0] self.diff_bstored = tup[1] - self.bstored self.bstored = tup[1] self.diff_drops = tup[2] - self.drops self.drops = tup[2] def __repr__(self): return "s: %d (%d) b: %d (%d) d: %d (%d)" % (self.stored, self.diff_stored, self.bstored, self.diff_bstored, self.drops, self.diff_drops) try: registerOfflineSubscriber() time.sleep(2.5) # Wait for first proper dump of stats brokerMonitor.start() counts = StoreCounts() cq.put(True) # Expect a dropped count (of 0, initial) counts.update(rq.get()) # Initial start print("rq.get (INITIAL) gave us: ", counts) rq.task_done() # publish 10 short messages, should be no drops print("publishing 10 short") cq.put(False) # expect no updated drop count msgs_short10 = [("test/publish/queueing/%d" % x, ''.join(random.choice(string.hexdigits) for _ in range(10)), 1, False) for x in range(1, 10 + 1)] paho.mqtt.publish.multiple(msgs_short10, port=port) counts.update(rq.get()) # Initial start print("rq.get (short) gave us: ", counts) rq.task_done() if counts.diff_stored != 10 or counts.diff_bstored < 100: raise ValueError if counts.diff_drops != 0: raise ValueError # publish 10 mediums (40bytes). should fail after 8, when it finally crosses 400 print("publishing 10 medium") cq.put(True) # expect a drop count msgs_medium10 = [("test/publish/queueing/%d" % x, ''.join(random.choice(string.hexdigits) for _ in range(40)), 1, False) for x in range(1, 10 + 1)] paho.mqtt.publish.multiple(msgs_medium10, port=port) counts.update(rq.get()) # Initial start print("rq.get (medium) gave us: ", counts) rq.task_done() if counts.diff_stored != 8 or counts.diff_bstored < 320: raise ValueError if counts.diff_drops != 2: raise ValueError rc = 0 finally: cq.put("quit") brokerMonitor.join() rq.join() cq.join() broker.terminate() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos1.py0000775000175000017500000000237313626052637020052 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. from mosq_test_helper import * rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") if mosq_test.expect_packet(sock, "publish2", publish_packet2): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-unpwd-success.py0000775000175000017500000000210613626052637022730 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is successful with correct username and password # when using a simple auth_plugin. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="test-username", password="cnwTICONIURW") connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/12-prop-response-topic.py0000775000175000017500000000432413626052637021620 0ustar rogerroger#!/usr/bin/env python3 # client 1 subscribes to normal-topic # client 2 susbscribes to response-topic # client 2 publishes message to normal-topic with response-topic property # client 1 receives message, publishes a response on response-topic # client 2 receives message, checks payload from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet1 = mosq_test.gen_connect("client1", proto_ver=5, keepalive=keepalive) connect_packet2 = mosq_test.gen_connect("client2", proto_ver=5, keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet1 = mosq_test.gen_subscribe(mid=1, topic="normal/topic", qos=0, proto_ver=5) subscribe_packet2 = mosq_test.gen_subscribe(mid=1, topic="response/topic", qos=0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid=1, qos=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") publish_packet2 = mosq_test.gen_publish(topic="normal/topic", qos=0, payload="2", proto_ver=5, properties=props) publish_packet1 = mosq_test.gen_publish(topic="response/topic", qos=0, payload="22", proto_ver=5) disconnect_client_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) disconnect_server_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=130) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect_packet1, connack_packet, port=port) sock2 = mosq_test.do_client_connect(connect_packet2, connack_packet, port=port) mosq_test.do_send_receive(sock1, subscribe_packet1, suback_packet, "subscribe1") mosq_test.do_send_receive(sock2, subscribe_packet2, suback_packet, "subscribe2") sock2.send(publish_packet2) if mosq_test.expect_packet(sock1, "publish1", publish_packet2): # FIXME - it would be better to extract the property and payload, even though we know them sock1.send(publish_packet1) if mosq_test.expect_packet(sock2, "publish2", publish_packet1): rc = 0 sock1.close() sock2.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-defer-unpwd-fail.py0000775000175000017500000000205713626052637023263 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection fail when using a auth_plugin that defer authentication. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="test-username@v2", password="doesNotMatter") connack_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-defer-unpwd-success.py0000775000175000017500000000224313626052637024015 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is successful with correct username and password # when using a two auth_plugin (first will defer, second will accept). from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin.so\n") f.write("auth_plugin c/auth_plugin_v2.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="test-username@v2", password="doesNotMatter") connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-c2b-qos2-len.py0000775000175000017500000000366113626052637021443 0ustar rogerroger#!/usr/bin/env python3 # Check whether the broker handles a v5 PUBREL with all combinations # of with/without reason code and properties. from mosq_test_helper import * def len_test(test, pubrel_packet): port = mosq_test.get_port() rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("qos2/len/test", qos=2, mid=mid, payload="len-message", proto_ver=5) pubrec_packet = mosq_test.gen_pubrec(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") mosq_test.do_ping(sock) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if rc != 0: print(test) exit(rc) # No reason code, no properties pubrel_packet = mosq_test.gen_pubrel(1) len_test("qos2 len 2", pubrel_packet) # Reason code, no properties pubrel_packet = mosq_test.gen_pubrel(1, proto_ver=5, reason_code=0x00) len_test("qos2 len 3", pubrel_packet) # Reason code, empty properties pubrel_packet = mosq_test.gen_pubrel(1, proto_ver=5, reason_code=0x00, properties="") len_test("qos2 len 4", pubrel_packet) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") pubrel_packet = mosq_test.gen_pubrel(1, proto_ver=5, reason_code=0x00, properties=props) len_test("qos2 len >5", pubrel_packet) mosquitto-1.6.9/test/broker/01-connect-uname-password-denied.py0000775000175000017500000000207513626052637023511 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is denied if it provides a correct username but # incorrect password. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="user", password="password9") connack_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-unsubscribe-invalid-no-topic.py0000775000175000017500000000167013626052637023366 0ustar rogerroger#!/usr/bin/env python3 # Test whether a UNSUBSCRIBE with no topic results in a disconnect. MQTT-3.10.3-2 from mosq_test_helper import * def gen_unsubscribe_invalid_no_topic(mid): pack_format = "!BBH" return struct.pack(pack_format, 162, 2, mid) rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-invalid-no-topic-test", keepalive=keepalive, proto_ver=4) connack_packet = mosq_test.gen_connack(rc=0) unsubscribe_packet = gen_unsubscribe_invalid_no_topic(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, unsubscribe_packet, b"", "disconnect") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-unsubscribe-qos1.py0000775000175000017500000000155513626052637021077 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 1 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 79 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos1/test") unsuback_packet = mosq_test.gen_unsuback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-password-success.py0000775000175000017500000000207413626052637023730 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is denied if it provides a correct username but # incorrect password. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="user", password="password") connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos0-topic-alias-unknown.py0000775000175000017500000000177413626052637023755 0ustar rogerroger#!/usr/bin/env python3 # Test whether "topic alias" works to the broker # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("sub-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS, 3) publish1_packet = mosq_test.gen_publish("", qos=0, payload="message", proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(reason_code=148, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) sock.send(publish1_packet) if mosq_test.expect_packet(sock, "disconnect", disconnect_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/04-retain-qos0-clear.py0000775000175000017500000000407713626052637021124 0ustar rogerroger#!/usr/bin/env python3 # Test whether a retained PUBLISH is cleared when a zero length retained # message is published to a topic. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-clear-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("retain/clear/test", qos=0, payload="retained message", retain=True) retain_clear_packet = mosq_test.gen_publish("retain/clear/test", qos=0, payload=None, retain=True) mid_sub = 592 subscribe_packet = mosq_test.gen_subscribe(mid_sub, "retain/clear/test", 0) suback_packet = mosq_test.gen_suback(mid_sub, 0) mid_unsub = 593 unsubscribe_packet = mosq_test.gen_unsubscribe(mid_unsub, "retain/clear/test") unsuback_packet = mosq_test.gen_unsuback(mid_unsub) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=4, port=port) # Send retained message sock.send(publish_packet) # Subscribe to topic, we should get the retained message back. mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish", publish_packet): # Now unsubscribe from the topic before we clear the retained # message. mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") # Now clear the retained message. sock.send(retain_clear_packet) # Subscribe to topic, we shouldn't get anything back apart # from the SUBACK. mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") time.sleep(1) # If we do get something back, it should be before this ping, so if # this succeeds then we're ok. mosq_test.do_ping(sock) # This is the expected event rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-no-auth.py0000775000175000017500000000267613626052637021506 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet using an SSL connection. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") rc = 0 ssock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos0-subscription-id.py0000775000175000017500000001073713626052637023170 0ustar rogerroger#!/usr/bin/env python3 # Does setting and updating subscription identifiers work as expected? # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 1) subscribe1_packet = mosq_test.gen_subscribe(mid, "subpub/id1", 0, proto_ver=5, properties=props) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) mid = 2 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 14) subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/+/id2", 0, proto_ver=5, properties=props) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) mid = 3 subscribe3_packet = mosq_test.gen_subscribe(mid, "subpub/noid", 0, proto_ver=5) suback3_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) # Updated version of subscribe1, now without a subscription identifier mid = 4 subscribe1u_packet = mosq_test.gen_subscribe(mid, "subpub/id1", 0, proto_ver=5) suback1u_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) # Updated version of subscribe2, with a new subscription identifier mid = 5 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 19) subscribe2u_packet = mosq_test.gen_subscribe(mid, "subpub/+/id2", 0, proto_ver=5, properties=props) suback2u_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) # Updated version of subscribe3, now with a subscription identifier mid = 6 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 21) subscribe3u_packet = mosq_test.gen_subscribe(mid, "subpub/noid", 0, proto_ver=5, properties=props) suback3u_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish("subpub/id1", qos=0, payload="message1", proto_ver=5) props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 1) publish1r_packet = mosq_test.gen_publish("subpub/id1", qos=0, payload="message1", proto_ver=5, properties=props) publish2_packet = mosq_test.gen_publish("subpub/test/id2", qos=0, payload="message2", proto_ver=5) props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 14) publish2r_packet = mosq_test.gen_publish("subpub/test/id2", qos=0, payload="message2", proto_ver=5, properties=props) publish3_packet = mosq_test.gen_publish("subpub/noid", qos=0, payload="message3", proto_ver=5) # Updated version of publish1r, now with no id publish1ru_packet = mosq_test.gen_publish("subpub/id1", qos=0, payload="message1", proto_ver=5) # Updated verison of publish2r, with updated id props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 19) publish2ru_packet = mosq_test.gen_publish("subpub/test/id2", qos=0, payload="message2", proto_ver=5, properties=props) # Updated version of publish3r, now with an id props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 21) publish3ru_packet = mosq_test.gen_publish("subpub/noid", qos=0, payload="message3", proto_ver=5, properties=props) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") mosq_test.do_send_receive(sock, subscribe3_packet, suback3_packet, "suback3") mosq_test.do_send_receive(sock, publish3_packet, publish3_packet, "publish3") mosq_test.do_send_receive(sock, publish2_packet, publish2r_packet, "publish2") mosq_test.do_send_receive(sock, publish1_packet, publish1r_packet, "publish1") # Now update the subscription identifiers mosq_test.do_send_receive(sock, subscribe1u_packet, suback1u_packet, "suback1u") mosq_test.do_send_receive(sock, subscribe2u_packet, suback2u_packet, "suback2u") mosq_test.do_send_receive(sock, subscribe3u_packet, suback3u_packet, "suback3u") mosq_test.do_send_receive(sock, publish2_packet, publish2ru_packet, "publish2u") mosq_test.do_send_receive(sock, publish3_packet, publish3ru_packet, "publish3u") mosq_test.do_send_receive(sock, publish1_packet, publish1ru_packet, "publish1u") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-qos2-max-inflight.py0000775000175000017500000000260213626052637022602 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow. # With max_inflight_messages set to 1 from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("max_inflight_messages 1\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 312 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, timeout=10) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-v2-unpwd-fail.py0000775000175000017500000000210113626052637022513 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is successful with correct username and password # when using a simple auth_plugin. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v2.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="test-username", password="wrong") connack_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos0-retain-as-publish.py0000775000175000017500000000363613626052637023401 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic with retain-as-published set works as expected. # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 530 subscribe1_packet = mosq_test.gen_subscribe(mid, "subpub/normal", 0, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) mid = 531 subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/rap", 0 | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish("subpub/normal", qos=0, retain=True, payload="message", proto_ver=5) publish2_packet = mosq_test.gen_publish("subpub/rap", qos=0, retain=True, payload="message", proto_ver=5) publish1r_packet = mosq_test.gen_publish("subpub/normal", qos=0, retain=False, payload="message", proto_ver=5) publish2r_packet = mosq_test.gen_publish("subpub/rap", qos=0, retain=True, payload="message", proto_ver=5) mid = 1 publish3_packet = mosq_test.gen_publish("subpub/receive", qos=1, mid=mid, payload="success", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") mosq_test.do_send_receive(sock, publish1_packet, publish1r_packet, "publish1") mosq_test.do_send_receive(sock, publish2_packet, publish2r_packet, "publish2") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-delay-session-expiry.py0000775000175000017500000000353313626052637022737 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client that connects with a will delay that is longer than # their session expiry interval has their will published. # MQTT 5 # https://github.com/eclipse/mosquitto/issues/1401 from mosq_test_helper import * rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 4) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 2) connect2_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, properties=connect_props, will_topic="will/test", will_payload=b"will delay", will_qos=2, will_properties=will_props) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port, connack_error="connack1") mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=30, port=port, connack_error="connack2") time.sleep(1) sock2.close() # Wait for session to expire time.sleep(3) if mosq_test.expect_packet(sock1, "publish", publish_packet): rc = 0 sock1.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-br2b-disconnect-qos2-helper.py0000775000175000017500000000146713626052637024247 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 312 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="helper connack") sock.send(publish_packet) if mosq_test.expect_packet(sock, "helper pubrec", pubrec_packet): sock.send(pubrel_packet) if mosq_test.expect_packet(sock, "helper pubcomp", pubcomp_packet): rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-pubrec-error.py0000775000175000017500000000365413626052637022463 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBREC with reason code >= 0x80 is handled correctly from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qo2-timeout-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/pubrec/+", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 1 publish_1_packet = mosq_test.gen_publish("qos2/pubrec/rejected", qos=2, mid=mid, payload="rejected-message", proto_ver=5) pubrec_1_packet = mosq_test.gen_pubrec(mid, proto_ver=5, reason_code=0x80) mid = 2 publish_2_packet = mosq_test.gen_publish("qos2/pubrec/accepted", qos=2, mid=mid, payload="accepted-message", proto_ver=5) pubrec_2_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_2_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_2_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./02-subpub-qos2-pubrec-error-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish 1", publish_1_packet): sock.send(pubrec_1_packet) if mosq_test.expect_packet(sock, "publish 2", publish_2_packet): mosq_test.do_send_receive(sock, pubrec_2_packet, pubrel_2_packet, "pubrel 2") sock.send(pubcomp_2_packet) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-identity.py0000775000175000017500000000322613626052637021754 0ustar rogerroger#!/usr/bin/env python3 # Client connects with a certificate to a server that has use_identity_as_username=true. Shouldn't be rejected. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("listener %d\n" %(port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("\n") f.write("use_identity_as_username true\n") f.write("require_certificate true\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-identity-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client.crt", keyfile="../ssl/client.key", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") rc = 0 ssock.close() finally: os.remove(conf_file) time.sleep(0.5) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-duplicate-v5.py0000775000175000017500000000140613626052637021615 0ustar rogerroger#!/usr/bin/env python3 # Test whether a duplicate CONNECT is rejected. MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.settimeout(3) sock.send(connect_packet) data = sock.recv(1) if len(data) == 0: rc = 0 except socket.error: rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos1-nolocal.py0000775000175000017500000000361313626052637021475 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic does not receive its own message # sent to that topic if no local is set. # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 530 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1 | mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 531 subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/receive", 1, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) puback_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 301 publish2_packet = mosq_test.gen_publish("subpub/receive", qos=1, mid=mid, payload="success", proto_ver=5) puback2_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 1 publish3_packet = mosq_test.gen_publish("subpub/receive", qos=1, mid=mid, payload="success", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") mosq_test.do_send_receive(sock, publish2_packet, puback2_packet, "puback2") if mosq_test.expect_packet(sock, "publish3", publish3_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-password-denied-no-will.py0000775000175000017500000000406013626052637025064 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is denied if it provides a correct username but # incorrect password. The client has a will, but it should not be sent. Check that. from mosq_test_helper import * def write_config(filename, port, pw_file): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("password_file %s\n" % (pw_file)) f.write("allow_anonymous false\n") def write_pwfile(filename): with open(filename, 'w') as f: # Username user, password password f.write('user:$6$vZY4TS+/HBxHw38S$vvjVFECzb8dyuu/mruD2QKTfdFn0WmKxbc+1TsdB0L8EdHk3v9JRmfjHd56+VaTnUcSZOZ/hzkdvWCtxlX7AUQ==\n') pw_file = os.path.basename(__file__).replace('.py', '.pwfile') port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, pw_file) write_pwfile(pw_file) rc = 1 keepalive = 10 connect1_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="user", password="password", will_topic="will/test", will_payload=b"will msg") connack1_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, topic="will/test", qos=0) suback_packet = mosq_test.gen_suback(mid, 0) connect2_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="user", password="password9") connack2_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet) sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, port=port) sock2.close() # If we receive a will here, this is an error mosq_test.do_ping(sock1) sock1.close() rc = 0 finally: os.remove(conf_file) os.remove(pw_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-v5.py0000775000175000017500000000352313626052637020401 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # MQTT v5 from mosq_test_helper import * rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 301 publish_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=5) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=5) pubrec_packet2 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet2 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet2 = mosq_test.gen_pubcomp(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") if mosq_test.expect_packet(sock, "publish2", publish_packet2): mosq_test.do_send_receive(sock, pubrec_packet2, pubrel_packet2, "pubrel2") # Broker side of flow complete so can quit here. rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-delay-reconnect.py0000775000175000017500000000432713626052637021720 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client with a will delay handles correctly on the client reconnecting # First connection is durable, second is clean session, and without a will, so the will should not be received. # MQTT 5 from mosq_test_helper import * def do_test(): rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 3) connect2a_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, will_topic="will/test", will_payload=b"will delay", will_properties=props, clean_session=False) connack2a_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2b_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, clean_session=True) connack2b_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2a_packet, connack2a_packet, timeout=30, port=port) sock2.close() time.sleep(1) sock2 = mosq_test.do_client_connect(connect2b_packet, connack2b_packet, timeout=30, port=port) time.sleep(3) # The client2 has reconnected within the original will delay interval, which has now # passed, but it should have been deleted anyway. Disconnect and see # whether we get the old will. We should not. sock2.close() mosq_test.do_ping(sock1) rc = 0 sock1.close() sock2.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() mosquitto-1.6.9/test/broker/07-will-null-helper.py0000775000175000017500000000066213626052637021071 0ustar rogerroger#!/usr/bin/env python3 # Connect a client with a will, then disconnect without DISCONNECT. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive, will_topic="will/null/test") connack_packet = mosq_test.gen_connack(rc=0) port = mosq_test.get_port() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-1322.py0000775000175000017500000001301413626052637020432 0ustar rogerroger#!/usr/bin/env python3 # Test for issue 1322: ## restart mosquitto #sudo systemctl restart mosquitto.service # ## listen on topic1 #mosquitto_sub -t "topic1" # ## publish to topic1 without clean session #mosquitto_pub -t "topic1" -q 2 -c --id "foobar" -m "message1" ## message1 on topic1 is received as expected # ## publish to topic2 without clean session ## IMPORTANT: no subscription to this topic is present on broker! #mosquitto_pub -t "topic2" -q 2 -c --id "foobar" -m "message2" ## this goes nowhere, as no subscriber present # ## publish to topic1 without clean session #mosquitto_pub -t "topic1" -q 2 -c --id "foobar" -m "message3" ## message3 on topic1 IS NOT RECEIVED # ## listen on topic2 #mosquitto_sub -t "topic2" # ## publish to topic1 without clean session #mosquitto_pub -t "topic1" -q 2 -c --id "foobar" -m "message4" ## message2 on topic2 is received incorrectly # ## publish to topic1 without clean session #mosquitto_pub -t "topic1" -q 2 -c --id "foobar" -m "message5" ## message5 on topic1 is received as expected (message4 was dropped) from mosq_test_helper import * rc = 1 keepalive = 60 pub_connect_packet = mosq_test.gen_connect("pub", keepalive=keepalive, clean_session=False) pub_connack1_packet = mosq_test.gen_connack(rc=0) pub_connack2_packet = mosq_test.gen_connack(rc=0, flags=1) sub1_connect_packet = mosq_test.gen_connect("sub1", keepalive=keepalive) sub1_connack_packet = mosq_test.gen_connack(rc=0) sub2_connect_packet = mosq_test.gen_connect("sub2", keepalive=keepalive) sub2_connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "topic1", 0) suback1_packet = mosq_test.gen_suback(mid, 0) mid = 1 subscribe2_packet = mosq_test.gen_subscribe(mid, "topic2", 0) suback2_packet = mosq_test.gen_suback(mid, 0) # All publishes have the same mid mid = 1 pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) publish1s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message1") publish2s_packet = mosq_test.gen_publish("topic2", qos=2, mid=mid, payload="message2") publish3s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message3") publish4s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message4") publish5s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message5") publish1r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message1") publish2r_packet = mosq_test.gen_publish("topic2", qos=0, payload="message2") publish3r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message3") publish4r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message4") publish5r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message5") port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sub1 = mosq_test.do_client_connect(sub1_connect_packet, sub1_connack_packet, timeout=10, port=port) mosq_test.do_send_receive(sub1, subscribe1_packet, suback1_packet, "suback1") pub = mosq_test.do_client_connect(pub_connect_packet, pub_connack1_packet, timeout=10, port=port) mosq_test.do_send_receive(pub, publish1s_packet, pubrec_packet, "pubrec1") mosq_test.do_send_receive(pub, pubrel_packet, pubcomp_packet, "pubcomp1") pub.close() if mosq_test.expect_packet(sub1, "publish1", publish1r_packet): pub = mosq_test.do_client_connect(pub_connect_packet, pub_connack2_packet, timeout=10, port=port) mosq_test.do_send_receive(pub, publish2s_packet, pubrec_packet, "pubrec2") mosq_test.do_send_receive(pub, pubrel_packet, pubcomp_packet, "pubcomp2") pub.close() # We expect nothing on sub1 mosq_test.do_ping(sub1, error_string="pingresp1") pub = mosq_test.do_client_connect(pub_connect_packet, pub_connack2_packet, timeout=10, port=port) mosq_test.do_send_receive(pub, publish3s_packet, pubrec_packet, "pubrec3") mosq_test.do_send_receive(pub, pubrel_packet, pubcomp_packet, "pubcomp3") pub.close() if mosq_test.expect_packet(sub1, "publish3", publish3r_packet): sub2 = mosq_test.do_client_connect(sub2_connect_packet, sub2_connack_packet, timeout=10, port=port) mosq_test.do_send_receive(sub2, subscribe2_packet, suback2_packet, "suback2") pub = mosq_test.do_client_connect(pub_connect_packet, pub_connack2_packet, timeout=10, port=port) mosq_test.do_send_receive(pub, publish4s_packet, pubrec_packet, "pubrec4") mosq_test.do_send_receive(pub, pubrel_packet, pubcomp_packet, "pubcomp4") pub.close() # We expect nothing on sub2 mosq_test.do_ping(sub2, error_string="pingresp2") if mosq_test.expect_packet(sub1, "publish4", publish4r_packet): pub = mosq_test.do_client_connect(pub_connect_packet, pub_connack2_packet, timeout=10, port=port) mosq_test.do_send_receive(pub, publish5s_packet, pubrec_packet, "pubrec5") mosq_test.do_send_receive(pub, pubrel_packet, pubcomp_packet, "pubcomp5") pub.close() # We expect nothing on sub2 mosq_test.do_ping(sub2, error_string="pingresp2") if mosq_test.expect_packet(sub1, "publish5", publish5r_packet): rc = 0 sub2.close() sub1.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-fail-persist-resend-qos2.py0000775000175000017500000000566313626052637023676 0ustar rogerroger#!/usr/bin/env python3 # Test whether a bridge can cope with an unknown PUBACK from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge-u-test\n") f.write("remote_clientid bridge-u-test\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# out\n") f.write("\n") f.write("cleansession true\n") f.write("notifications false\n") f.write("restart_timeout 5\n") f.write("try_private false\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-u-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 180 mid_unknown = 2000 publish_packet = mosq_test.gen_publish("bridge/unknown/qos2", qos=1, payload="bridge-message", mid=mid) puback_packet = mosq_test.gen_puback(mid) pubrec_packet_unknown1 = mosq_test.gen_pubrec(mid_unknown+1) pubrel_packet_unknown1 = mosq_test.gen_pubrel(mid_unknown+1) pubrel_packet_unknown2 = mosq_test.gen_pubrel(mid_unknown+2) pubcomp_packet_unknown2 = mosq_test.gen_pubcomp(mid_unknown+2) pubcomp_packet_unknown3 = mosq_test.gen_pubcomp(mid_unknown+3) unsubscribe_packet = mosq_test.gen_unsubscribe(1, "bridge/#") unsuback_packet = mosq_test.gen_unsuback(1) if os.environ.get('MOSQ_USE_VALGRIND') is not None: sleep_time = 5 else: sleep_time = 0.5 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port1)) sock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) time.sleep(sleep_time) try: (conn, address) = sock.accept() conn.settimeout(20) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "unsubscribe", unsubscribe_packet): conn.send(unsuback_packet) # Send the unexpected pubrec packet conn.send(pubrec_packet_unknown1) if mosq_test.expect_packet(conn, "pubrel", pubrel_packet_unknown1): conn.send(pubrel_packet_unknown2) if mosq_test.expect_packet(conn, "pubcomp", pubcomp_packet_unknown2): conn.send(pubcomp_packet_unknown3) # Send a legitimate publish packet to verify everything is still ok conn.send(publish_packet) if mosq_test.expect_packet(conn, "puback", puback_packet): rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-bad-pubcomp.py0000775000175000017500000000410213626052637022232 0ustar rogerroger#!/usr/bin/env python3 # Test what the broker does if receiving a PUBCOMP in response to a QoS 2 PUBLISH. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2) suback_packet = mosq_test.gen_suback(mid, 2) helper_connect = mosq_test.gen_connect("helper", keepalive=keepalive) helper_connack = mosq_test.gen_connack(rc=0) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubrec1s_packet = mosq_test.gen_pubrec(mid) pubrel1s_packet = mosq_test.gen_pubrel(mid) pubcomp1s_packet = mosq_test.gen_pubcomp(mid) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubcomp1r_packet = mosq_test.gen_pubcomp(mid) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, pubrec1s_packet, "pubrec 1s") mosq_test.do_send_receive(helper, pubrel1s_packet, pubcomp1s_packet, "pubcomp 1s") helper.close() if mosq_test.expect_packet(sock, "publish 1r", publish1r_packet): sock.send(pubcomp1r_packet) sock.send(pingreq_packet) p = sock.recv(len(pingresp_packet)) if len(p) == 0: rc = 0 sock.close() except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-duplicate.py0000775000175000017500000000134413626052637021266 0ustar rogerroger#!/usr/bin/env python3 # Test whether a duplicate CONNECT is rejected. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.settimeout(3) sock.send(connect_packet) data = sock.recv(1) if len(data) == 0: rc = 0 except socket.error: rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-cert-auth-revoked.py0000775000175000017500000000325013626052637023451 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("require_certificate true\n") f.write("crlfile ../ssl/crl.pem\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-revoked-test", keepalive=keepalive) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client-revoked.crt", keyfile="../ssl/client-revoked.key", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) try: ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, "", "connack") except ssl.SSLError as err: if err.errno == 1 and "certificate revoked" in err.strerror: rc = 0 else: broker.terminate() print(err.strerror) raise ValueError(err.errno) finally: os.remove(conf_file) time.sleep(0.5) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-pattern-matching-helper.py0000775000175000017500000000074313626052637022413 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = int(sys.argv[2]) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish(sys.argv[1], qos=0, retain=True, payload="message") sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack", port=port) sock.send(publish_packet) rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-no-password-denied.pwfile0000664000175000017500000000016213626052637024751 0ustar rogerrogeruser:$6$Ut1cUS9PG8+gC3vn$tOjCfSJJDe1Alu9HktxxyyzwN4+6mAMSWGRAF9gmMN8pzcGTPVEYYMAZpCEp96Oz2ZRRz5YKM6lPMf1tUbb6zA== mosquitto-1.6.9/test/broker/10-listener-mount-point.py0000775000175000017500000000306213626052637022000 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port1)) f.write("\n") f.write("listener %d\n" % (port2)) f.write("mount_point mount/\n") f.write("\n") f.write("log_type debug\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test2", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish("mount/test", qos=0, payload="mount point") broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port1) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port1) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./10-listener-mount-point-helper.py', str(port2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-extended-auth-unsupported.py0000775000175000017500000000161313626052637023021 0ustar rogerroger#!/usr/bin/env python3 # Test whether an unsupported extended auth is rejected. from mosq_test_helper import * port = mosq_test.get_port() rc = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "unsupported") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "test") connect_packet = mosq_test.gen_connect("client-params-test", keepalive=42, proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/11-persistent-subscription-v5.py0000775000175000017500000000461513626052637023144 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 mid = 530 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 100) connect_packet = mosq_test.gen_connect( "persistent-subscription-test", keepalive=keepalive, clean_session=False, proto_ver=5, properties=props ) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=5) # session present subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) puback_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) (stdo1, stde1) = ("", "") try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") broker.terminate() broker.wait() (stdo1, stde1) = broker.communicate() sock.close() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=20, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") if mosq_test.expect_packet(sock, "publish2", publish_packet2): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-receive-maximum-helper.py0000775000175000017500000000354113626052637024421 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test-helper", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message1", proto_ver=5) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 2 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message2", proto_ver=5) pubrec_packet2 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet2 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet2 = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 3 publish_packet3 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message3", proto_ver=5) pubrec_packet3 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet3 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet3 = mosq_test.gen_pubcomp(mid, proto_ver=5) port = mosq_test.get_port() try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") mosq_test.do_send_receive(sock, publish_packet2, pubrec_packet2, "pubrec2") mosq_test.do_send_receive(sock, pubrel_packet2, pubcomp_packet2, "pubcomp2") mosq_test.do_send_receive(sock, publish_packet3, pubrec_packet3, "pubrec3") mosq_test.do_send_receive(sock, pubrel_packet3, pubcomp_packet3, "pubcomp3") rc = 0 sock.close() finally: if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/12-prop-assigned-client-identifier.py0000775000175000017500000000306513626052637024040 0ustar rogerroger#!/usr/bin/env python3 # Test whether sending a non zero session expiry interval in DISCONNECT after # having sent a zero session expiry interval is treated correctly in MQTT v5. from mosq_test_helper import * def do_test(clean_start): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect(None, proto_ver=5, keepalive=keepalive, clean_session=clean_start) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_ASSIGNED_CLIENT_IDENTIFIER, "auto-00000000-0000-0000-0000-000000000000") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 1) disconnect_client_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) disconnect_server_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=130) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10) sock.connect(("localhost", port)) sock.send(connect_packet) connack_recvd = sock.recv(len(connack_packet)) if connack_recvd[0:12] == connack_packet[0:12]: # FIXME - this test could be tightened up a lot rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(True) do_test(False) exit(0) mosquitto-1.6.9/test/broker/07-will-invalid-utf8.py0000775000175000017500000000141313626052637021147 0ustar rogerroger#!/usr/bin/env python3 # Test whether a will topic with invalid UTF-8 fails from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("will-invalid-utf8", keepalive=keepalive, will_topic="invalid/utf8") b = list(struct.unpack("B"*len(connect_packet), connect_packet)) b[40] = 0 # Topic should never have a 0x0000 connect_packet = struct.pack("B"*len(b), *b) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", timeout=30, port=port) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-bad-puback-1.py0000775000175000017500000000407613626052637022202 0ustar rogerroger#!/usr/bin/env python3 # Test what the broker does if receiving a PUBACK in response to a QoS 2 PUBLISH. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2) suback_packet = mosq_test.gen_suback(mid, 2) helper_connect = mosq_test.gen_connect("helper", keepalive=keepalive) helper_connack = mosq_test.gen_connack(rc=0) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubrec1s_packet = mosq_test.gen_pubrec(mid) pubrel1s_packet = mosq_test.gen_pubrel(mid) pubcomp1s_packet = mosq_test.gen_pubcomp(mid) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") puback1r_packet = mosq_test.gen_puback(mid) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, pubrec1s_packet, "pubrec 1s") mosq_test.do_send_receive(helper, pubrel1s_packet, pubcomp1s_packet, "pubcomp 1s") helper.close() if mosq_test.expect_packet(sock, "publish 1r", publish1r_packet): sock.send(puback1r_packet) sock.send(pingreq_packet) p = sock.recv(len(pingresp_packet)) if len(p) == 0: rc = 0 sock.close() except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-invalid-id-0-311.py0000775000175000017500000000123213626052637021767 0ustar rogerroger#!/usr/bin/env python3 # Test whether a CONNECT with a zero length client id results in the correct CONNACK packet. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("", keepalive=keepalive, proto_ver=4) connack_packet = mosq_test.gen_connack(rc=0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-pattern-matching.py0000775000175000017500000000537713626052637021146 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def pattern_test(sub_topic, pub_topic): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pattern-sub-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish(pub_topic, qos=0, payload="message") publish_retained_packet = mosq_test.gen_publish(pub_topic, qos=0, retain=True, payload="message") mid = 312 subscribe_packet = mosq_test.gen_subscribe(mid, sub_topic, 0) suback_packet = mosq_test.gen_suback(mid, 0) mid = 234; unsubscribe_packet = mosq_test.gen_unsubscribe(mid, sub_topic) unsuback_packet = mosq_test.gen_unsuback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-pattern-matching-helper.py', pub_topic, str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() if mosq_test.expect_packet(sock, "publish", publish_packet): mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish retained", publish_retained_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print(stdo.decode('utf-8')) sys.exit(rc) return rc pattern_test("#", "test/topic") pattern_test("#", "/test/topic") pattern_test("foo/#", "foo/bar/baz") pattern_test("foo/+/baz", "foo/bar/baz") pattern_test("foo/+/baz/#", "foo/bar/baz") pattern_test("foo/+/baz/#", "foo/bar/baz/bar") pattern_test("foo/foo/baz/#", "foo/foo/baz/bar") pattern_test("foo/#", "foo") pattern_test("foo/#", "foo/") pattern_test("/#", "/foo") pattern_test("test/topic/", "test/topic/") pattern_test("test/topic/+", "test/topic/") pattern_test("+/+/+/+/+/+/+/+/+/+/test", "one/two/three/four/five/six/seven/eight/nine/ten/test") pattern_test("#", "test////a//topic") pattern_test("#", "/test////a//topic") pattern_test("foo/#", "foo//bar///baz") pattern_test("foo/+/baz", "foo//baz") pattern_test("foo/+/baz//", "foo//baz//") pattern_test("foo/+/baz/#", "foo//baz") pattern_test("foo/+/baz/#", "foo//baz/bar") pattern_test("foo//baz/#", "foo//baz/bar") pattern_test("foo/foo/baz/#", "foo/foo/baz/bar") pattern_test("/#", "////foo///bar") exit(0) mosquitto-1.6.9/test/broker/02-subpub-qos0.py0000775000175000017500000000202313626052637020041 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos0", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish("subpub/qos0", qos=0, payload="message") port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, publish_packet, "publish") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2.py0000775000175000017500000000332013626052637020044 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. from mosq_test_helper import * rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 301 publish_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubrec_packet2 = mosq_test.gen_pubrec(mid) pubrel_packet2 = mosq_test.gen_pubrel(mid) pubcomp_packet2 = mosq_test.gen_pubcomp(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") if mosq_test.expect_packet(sock, "publish2", publish_packet2): mosq_test.do_send_receive(sock, pubrec_packet2, pubrel_packet2, "pubrel2") sock.send(pubcomp_packet2) # Broker side of flow complete so can quit here. rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-context-params.py0000775000175000017500000000264213626052637023077 0ustar rogerroger#!/usr/bin/env python3 # Test whether message parameters are passed to the plugin acl check function. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_context_params.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 connect_packet = mosq_test.gen_connect("client-params-test", keepalive=42, username="client-username") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "param/topic", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 3 publish_packet = mosq_test.gen_publish(topic="param/topic", qos=1, payload="payload contents", retain=1, mid=mid) puback_packet = mosq_test.gen_puback(mid) mid = 1 publish_packet_recv = mosq_test.gen_publish(topic="param/topic", qos=1, payload="payload contents", retain=0, mid=mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-hup-disconnect.py0000775000175000017500000000463013626052637021417 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client connected with a client certificate when # use_identity_as_username is true is then disconnected when a SIGHUP is # received. # https://github.com/eclipse/mosquitto/issues/1402 from mosq_test_helper import * import signal if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, pw_file, port, option): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("require_certificate true\n") f.write("%s true\n" % (option)) f.write("password_file %s\n" % (pw_file)) def write_pwfile(filename): with open(filename, 'w') as f: # Username "test client", password test f.write('test client:$6$njERlZMi/7DzNB9E$iiavfuXvUm8iyDZArTy7smTxh07GXXOrOsqxfW6gkOYVXHGk+W+i/8d3xDxrMwEPygEBhoA8A/gjQC0N2M4Lkw==\n') def do_test(option): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') pw_file = os.path.basename(__file__).replace('.py', '.pwfile') write_config(conf_file, pw_file, port, option) write_pwfile(pw_file) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client.crt", keyfile="../ssl/client.key", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) ssock.connect(("localhost", port)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") broker.send_signal(signal.SIGHUP) time.sleep(1) # This will fail if we've been disconnected mosq_test.do_ping(ssock) rc = 0 ssock.close() finally: os.remove(conf_file) os.remove(pw_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("use_identity_as_username") do_test("use_subject_as_username") exit(0) mosquitto-1.6.9/test/broker/09-extended-auth-single.py0000775000175000017500000000701213626052637021711 0ustar rogerroger#!/usr/bin/env python3 # Multi tests for extended auth with a single step. # * Error in plugin # * No matching authentication method # * Matching authentication method, but auth rejected # * Matching authentication method, auth succeeds # * Matching authentication method, auth succeeds, new auth data sent back to client from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_extended_single.so\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 # Single, error in plugin props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "error") connect1_packet = mosq_test.gen_connect("client-params-test1", keepalive=42, proto_ver=5, properties=props) # Single, no matching authentication method props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "non-matching") connect2_packet = mosq_test.gen_connect("client-params-test2", keepalive=42, proto_ver=5, properties=props) connack2_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) # Single step, matching method, failure props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "single") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "baddata") connect3_packet = mosq_test.gen_connect("client-params-test3", keepalive=42, proto_ver=5, properties=props) connack3_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, properties=None) # Single step, matching method, success props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "single") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "data") connect4_packet = mosq_test.gen_connect("client-params-test5", keepalive=42, proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "single") connack4_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) # Single step, matching method, success, auth data back to client props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "somedata") connect5_packet = mosq_test.gen_connect("client-params-test6", keepalive=42, proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "atademos") connack5_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect1_packet, b"", timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect3_packet, connack3_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect4_packet, connack4_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect5_packet, connack5_packet, timeout=20, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subhier-crash.py0000775000175000017500000000264013626052637020425 0ustar rogerroger#!/usr/bin/env python3 # Test related to https://github.com/eclipse/mosquitto/issues/505 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subhier-crash", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "topic/a", 0) suback1_packet = mosq_test.gen_suback(mid, 0) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "topic/b", 0) suback2_packet = mosq_test.gen_suback(mid, 0) mid = 3 unsubscribe1_packet = mosq_test.gen_unsubscribe(mid, "topic/a") unsuback1_packet = mosq_test.gen_unsuback(mid) disconnect_packet = mosq_test.gen_disconnect() port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) def test(): sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback 1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback 2") mosq_test.do_send_receive(sock, unsubscribe1_packet, unsuback1_packet, "unsuback") sock.send(disconnect_packet) sock.close() try: time.sleep(0.5) test() # Repeat test to check broker is still there test() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-unsubscribe-qos0.py0000775000175000017500000000163613626052637021076 0ustar rogerroger#!/usr/bin/env python3 # Test whether a UNSUBSCRIBE to a topic with QoS 0 results in the correct UNSUBACK packet. # This doesn't assume a subscription exists. from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos0/test") unsuback_packet = mosq_test.gen_unsuback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-delay-recover.py0000775000175000017500000000430013626052637021374 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client with a will delay recovers on the client reconnecting # MQTT 5 from mosq_test_helper import * def do_test(clean_session): rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 30) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 3) connect2_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, will_topic="will/test", will_payload=b"will delay", will_properties=props, clean_session=clean_session, properties=connect_props) connack2a_packet = mosq_test.gen_connack(rc=0, proto_ver=5) if clean_session == True: connack2b_packet = mosq_test.gen_connack(rc=0, proto_ver=5) else: connack2b_packet = mosq_test.gen_connack(rc=0, proto_ver=5, flags=1) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2a_packet, timeout=30, port=port) sock2.close() time.sleep(1) sock2 = mosq_test.do_client_connect(connect2_packet, connack2b_packet, timeout=30, port=port) time.sleep(3) # The client2 has reconnected within the will delay interval, which has now # passed. We should not have received the will at this point. mosq_test.do_ping(sock1) rc = 0 sock1.close() sock2.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(clean_session=True) do_test(clean_session=False) mosquitto-1.6.9/test/broker/09-extended-auth-change-username.py0000775000175000017500000000637513626052637023505 0ustar rogerroger#!/usr/bin/env python3 # Check whether an extended auth plugin can change the username of a client. from mosq_test_helper import * def write_config(filename, acl_file, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("port %d\n" % (port)) f.write("acl_file %s\n" % (acl_file)) f.write("auth_plugin c/auth_plugin_extended_single.so\n") def write_acl(filename): with open(filename, 'w') as f: f.write('user new_username\n') f.write('topic readwrite topic/one\n') port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') acl_file = os.path.basename(__file__).replace('.py', '.acl') def do_test(per_listener): write_config(conf_file, acl_file, port, per_listener) write_acl(acl_file) rc = 1 # Connect without a username - this means no access connect1_packet = mosq_test.gen_connect("client-params-test1", keepalive=42, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "topic/one", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 2 publish1_packet = mosq_test.gen_publish("topic/one", qos=1, mid=mid, payload="message", proto_ver=5) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED) # Connect without a username, but have the plugin change it props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "change") connect2_packet = mosq_test.gen_connect("client-params-test2", keepalive=42, proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "change") connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) mid = 2 publish2s_packet = mosq_test.gen_publish("topic/one", qos=1, mid=mid, payload="message", proto_ver=5) puback2s_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 1 publish2r_packet = mosq_test.gen_publish("topic/one", qos=1, mid=mid, payload="message", proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback1") mosq_test.do_send_receive(sock, publish1_packet, puback1_packet, "puback1") mosq_test.do_ping(sock) sock.close() sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback2") mosq_test.do_send_receive(sock, publish2s_packet, puback2s_packet, "puback2") if mosq_test.expect_packet(sock, "publish2", publish2r_packet): mosq_test.do_ping(sock) rc = 0 sock.close() finally: os.remove(conf_file) os.remove(acl_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("true") do_test("false") exit(0) mosquitto-1.6.9/test/broker/12-prop-server-keepalive.py0000775000175000017500000000217313626052637022117 0ustar rogerroger#!/usr/bin/env python3 # Test whether sending a non zero session expiry interval in DISCONNECT after # having sent a zero session expiry interval is treated correctly in MQTT v5. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("\n") f.write("max_keepalive 60\n") port = mosq_test.get_port(1) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 61 connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_SERVER_KEEP_ALIVE, 60) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, use_conf=True) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-unsubscribe-qos2-multiple-v5.py0000775000175000017500000000235713626052637023262 0ustar rogerroger#!/usr/bin/env python3 # Test whether a v5 UNSUBSCRIBE to multiple topics with QoS 2 results in the # correct UNSUBACK packet, when one subscription exists and the other does not. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos2-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/two", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 3 unsubscribe_packet = mosq_test.gen_unsubscribe_multiple(mid, ["qos2/one", "qos2/two"], proto_ver=5) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=5, reason_code=[17, 0]) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-acl-pub.py0000775000175000017500000000406013626052637021451 0ustar rogerroger#!/usr/bin/env python3 # Bug specific test - if a QoS2 publish is denied, then we publish again with # the same mid to a topic that is allowed, does it work properly? from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect1_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="readwrite", clean_session=False) connack1_packet = mosq_test.gen_connack(rc=0) connect2_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="readwrite", clean_session=False) connack2_packet = mosq_test.gen_connack(rc=0,flags=1) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "readonly", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 2 publish1_packet = mosq_test.gen_publish("readonly", qos=2, mid=mid, payload="message") pubrec1_packet = mosq_test.gen_pubrec(mid) pubrel1_packet = mosq_test.gen_pubrel(mid) pubcomp1_packet = mosq_test.gen_pubcomp(mid) mid = 2 publish2_packet = mosq_test.gen_publish("writeable", qos=1, mid=mid, payload="message") puback2_packet = mosq_test.gen_puback(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish1_packet, pubrec1_packet, "pubrec1") sock.close() sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish2_packet, puback2_packet, "puback2") mosq_test.do_ping(sock) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-cert-auth-expired.py0000775000175000017500000000331213626052637023451 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet using an # SSL connection with client certificates required. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("require_certificate true\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client-expired.crt", keyfile="../ssl/client-expired.key", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) try: ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, "", "connack") except ssl.SSLError as err: if err.errno == 1: rc = 0 else: broker.terminate() raise ValueError(err.errno) finally: os.remove(conf_file) time.sleep(0.5) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-acl-sub-denied.py0000775000175000017500000000301513626052637022701 0ustar rogerroger#!/usr/bin/env python3 # Test topic subscription. All SUBSCRIBE requests are denied. Check this # produces the correct response, and check the client isn't disconnected (ref: # issue #1016). from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_acl_sub_denied.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("sub-denied-test", keepalive=keepalive, username="denied") connack_packet = mosq_test.gen_connack(rc=0) mid = 53 subscribe_packet = mosq_test.gen_subscribe(mid, "qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 128) mid_pub = 54 publish_packet = mosq_test.gen_publish("topic", qos=1, payload="test", mid=mid_pub) puback_packet = mosq_test.gen_puback(mid_pub) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/12-prop-maximum-packet-size-publish.py0000775000175000017500000000263713626052637024211 0ustar rogerroger#!/usr/bin/env python3 # Test whether maximum packet size is honoured on a PUBLISH to a client # MQTTv5 from mosq_test_helper import * rc = 1 keepalive = 10 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MAXIMUM_PACKET_SIZE, 20) connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish(topic="test/topic", qos=0, payload="12345678901234567890", proto_ver=5) publish2_packet = mosq_test.gen_publish(topic="test/topic", qos=0, payload="67890", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet) sock.send(publish1_packet) # We shouldn't receive the publish here because it is > MAXIMUM_PACKET_SIZE mosq_test.do_ping(sock, "pingresp1") mosq_test.do_send_receive(sock, publish2_packet, publish2_packet) mosq_test.do_ping(sock, "pingresp2") rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos0-long-topic.py0000775000175000017500000000310513626052637022114 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic, for long topics. from mosq_test_helper import * def do_test(topic, succeeds): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, topic, 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish(topic, qos=0, payload="message") port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) if succeeds == True: mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, publish_packet, "publish") else: mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("/"*200, True) # 200 max hierarchy limit do_test("abc/"*199+"d", True) # 200 max hierarchy limit, longer overall string than 200 do_test("/"*201, False) # Exceeds 200 max hierarchy limit do_test("abc/"*200+"d", False) # Exceeds 200 max hierarchy limit, longer overall string than 200 exit(0) mosquitto-1.6.9/test/broker/02-subscribe-dollar-v5.py0000775000175000017500000000246113626052637021453 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to $SYS or $share succeeds from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "$SYS/broker/missing", 0, proto_ver=proto_ver) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "$share/share/#", 0, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-1.6.9/test/broker/02-subscribe-qos1.py0000775000175000017500000000154313626052637020531 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 1 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 79 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-zero-length-id.py0000775000175000017500000002064413626052637022150 0ustar rogerroger#!/usr/bin/env python3 # Test whether a CONNECT with a zero length client id results in the correct behaviour. # MQTT v3.1.1 - zero length is allowed, unless allow_zero_length_clientid is false, and unless clean_start is False. # MQTT v5.0 - zero length is allowed, unless allow_zero_length_clientid is false from mosq_test_helper import * def write_config(filename, port1, port2, per_listener, allow_zero): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("port %d\n" % (port2)) if allow_zero != "": f.write("allow_zero_length_clientid %s\n" % (allow_zero)) f.write("listener %d\n" % (port1)) if allow_zero != "": f.write("allow_zero_length_clientid %s\n" % (allow_zero)) def do_test(per_listener, proto_ver, clean_start, allow_zero, client_port, expect_fail): conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, per_listener, allow_zero) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("", keepalive=keepalive, proto_ver=proto_ver, clean_session=clean_start) if proto_ver == 4: if expect_fail == True: connack_packet = mosq_test.gen_connack(rc=2, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: if expect_fail == True: connack_packet = mosq_test.gen_connack(rc=128, proto_ver=proto_ver, properties=None) else: props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_ASSIGNED_CLIENT_IDENTIFIER, "auto-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, properties=props) # Remove the "xxxx" part - this means the front part of the packet # is correct (so remaining length etc. is correct), but we don't # need to match against the random id. connack_packet = connack_packet[:-36] broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port1, use_conf=True) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=client_port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() os.remove(conf_file) if rc: print(stde.decode('utf-8')) print("per_listener:%s proto_ver:%d client_port:%d clean_start:%d allow_zero:%s" % (per_listener, proto_ver, client_port, clean_start, allow_zero)) print("port1:%d port2:%d" % (port1, port2)) exit(rc) (port1, port2) = mosq_test.get_port(2) test_v4 = True test_v5 = True if test_v4 == True: do_test(per_listener="false", proto_ver=4, client_port=port1, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="false", proto_ver=4, client_port=port1, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port1, clean_start=False, allow_zero="true", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port1, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port1, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="true", proto_ver=4, client_port=port1, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port1, clean_start=False, allow_zero="true", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port1, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port2, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="false", proto_ver=4, client_port=port2, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port2, clean_start=False, allow_zero="true", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port2, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port2, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="true", proto_ver=4, client_port=port2, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port2, clean_start=False, allow_zero="true", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port2, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port1, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="false", proto_ver=4, client_port=port1, clean_start=False, allow_zero="", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port1, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="true", proto_ver=4, client_port=port1, clean_start=False, allow_zero="", expect_fail=True) do_test(per_listener="false", proto_ver=4, client_port=port2, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="false", proto_ver=4, client_port=port2, clean_start=False, allow_zero="", expect_fail=True) do_test(per_listener="true", proto_ver=4, client_port=port2, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="true", proto_ver=4, client_port=port2, clean_start=False, allow_zero="", expect_fail=True) if test_v5 == True: do_test(per_listener="false", proto_ver=5, client_port=port1, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port1, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=5, client_port=port1, clean_start=False, allow_zero="true", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port1, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=5, client_port=port1, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port1, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=5, client_port=port1, clean_start=False, allow_zero="true", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port1, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=5, client_port=port2, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port2, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=5, client_port=port2, clean_start=False, allow_zero="true", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port2, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=5, client_port=port2, clean_start=True, allow_zero="true", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port2, clean_start=True, allow_zero="false", expect_fail=True) do_test(per_listener="true", proto_ver=5, client_port=port2, clean_start=False, allow_zero="true", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port2, clean_start=False, allow_zero="false", expect_fail=True) do_test(per_listener="false", proto_ver=5, client_port=port1, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port1, clean_start=False, allow_zero="", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port1, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port1, clean_start=False, allow_zero="", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port2, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="false", proto_ver=5, client_port=port2, clean_start=False, allow_zero="", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port2, clean_start=True, allow_zero="", expect_fail=False) do_test(per_listener="true", proto_ver=5, client_port=port2, clean_start=False, allow_zero="", expect_fail=False) exit(0) mosquitto-1.6.9/test/broker/02-subscribe-qos2.py0000775000175000017500000000154213626052637020531 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 2 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/test", 2) suback_packet = mosq_test.gen_suback(mid, 2) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/10-listener-mount-point-helper.py0000775000175000017500000000073113626052637023255 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("test", qos=0, payload="mount point") sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="helper connack") sock.send(publish_packet) rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/03-publish-qos1-retain-disabled.py0000775000175000017500000000262313626052637023244 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH with a retain set when retains are disabled results in # the correct DISCONNECT. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("retain_available false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 mid = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_RETAIN_AVAILABLE, 0) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", retain=True, proto_ver=5) puback_packet = mosq_test.gen_puback(mid, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(reason_code=154, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "disconnect") rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-br2b-disconnect-qos1.py0000775000175000017500000000577313626052637022775 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge resend a QoS=1 message correctly after a disconnect? from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# both 1\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 3 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1) suback2_packet = mosq_test.gen_suback(mid, 1) mid = 2 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", dup=True) puback_packet = mosq_test.gen_puback(mid) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(40) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): bridge.send(suback_packet) pub = subprocess.Popen(['./06-bridge-br2b-disconnect-qos1-helper.py', str(port2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if pub.wait(): exit(1) (stdo, stde) = pub.communicate() if mosq_test.expect_packet(bridge, "publish", publish_packet): bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "2nd connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet): bridge.send(suback2_packet) if mosq_test.expect_packet(bridge, "2nd publish", publish_dup_packet): rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-qos2-len-helper.py0000775000175000017500000000137413626052637022717 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("qos2/len/test", qos=2, mid=mid, payload="len-message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack", port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "helper pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "helper pubcomp") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subscribe-persistence-flipflop.py0000775000175000017500000000517413626052637024007 0ustar rogerroger#!/usr/bin/env python3 # Test switching between persistence and a clean session. # # Bug #874: # # # mosquitto_sub -i sub -t 'topic' -v -p 29883 -q 1 -d -c # ^C # mosquitto_sub -i sub -t 'topic' -v -p 29883 -q 1 -d # ^C # # SUBSCRIBE to topic is no longer respected by mosquitto # # run: # # mosquitto_sub -i sub -t 'topic' -v -p 29883 -q 1 -d -c # # and in a separate shell # # mosquitto_pub -i pub -t topic -m 'hello' -p 29883 -q 1 # # sub does not receive the message from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet_sub_persistent = mosq_test.gen_connect("flipflop-test", keepalive=keepalive, clean_session=False) connect_packet_sub_clean = mosq_test.gen_connect("flipflop-test", keepalive=keepalive, clean_session=True) connack_packet_sub = mosq_test.gen_connack(rc=0) connect_packet_pub = mosq_test.gen_connect("flipflop-test-pub", keepalive=keepalive) connack_packet_pub = mosq_test.gen_connack(rc=0) mid=1 subscribe_packet = mosq_test.gen_subscribe(mid, "flipflop/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid=1 publish_packet = mosq_test.gen_publish("flipflop/test", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # mosquitto_sub -i sub -t 'topic' -q 1 -d -c sub_sock = mosq_test.do_client_connect(connect_packet_sub_persistent, connack_packet_sub, port=port) mosq_test.do_send_receive(sub_sock, subscribe_packet, suback_packet, "subscribe persistent 1") # And disconnect sub_sock.close() # mosquitto_sub -i sub -t 'topic' -q 1 -d sub_sock = mosq_test.do_client_connect(connect_packet_sub_clean, connack_packet_sub, port=port) mosq_test.do_send_receive(sub_sock, subscribe_packet, suback_packet, "subscribe clean") # And disconnect sub_sock.close() # mosquitto_sub -i sub -t 'topic' -v -q 1 -d -c sub_sock = mosq_test.do_client_connect(connect_packet_sub_persistent, connack_packet_sub, port=port) mosq_test.do_send_receive(sub_sock, subscribe_packet, suback_packet, "subscribe persistent 2") # and in a separate shell # # mosquitto_pub -i pub -t topic -m 'hello' -p 29883 -q 1 pub_sock = mosq_test.do_client_connect(connect_packet_pub, connack_packet_pub, port=port) mosq_test.do_send_receive(pub_sock, publish_packet, puback_packet, "publish") if mosq_test.expect_packet(sub_sock, "publish receive", publish_packet): rc = 0 sub_sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-no-local.py0000775000175000017500000000274613626052637020637 0ustar rogerroger#!/usr/bin/env python3 # Check whether an incoming bridge connection receives its own messages. It # shouldn't because for v3.1 and v3.1.1 we have no-local set for all bridges. from mosq_test_helper import * port = mosq_test.get_port() def do_test(proto_ver_connect, proto_ver_msgs, sub_opts): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-test", keepalive=keepalive, proto_ver=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver_msgs) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "loop/test", 0 | sub_opts, proto_ver=proto_ver_msgs) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver_msgs) publish_packet = mosq_test.gen_publish("loop/test", qos=0, payload="message", proto_ver=proto_ver_msgs) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.send(publish_packet) mosq_test.do_ping(sock) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(128+3, 3, 0) do_test(128+4, 4, 0) do_test(5, 5, mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL) exit(0) mosquitto-1.6.9/test/broker/08-ssl-connect-no-identity.py0000775000175000017500000000306313626052637022365 0ustar rogerroger#!/usr/bin/env python3 # Client connects without a certificate to a server that has use_identity_as_username=true. Should be rejected. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("\n") f.write("use_identity_as_username true\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-no-identity-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=4) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") rc = 0 ssock.close() finally: os.remove(conf_file) time.sleep(2) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/04-retain-check-source-persist.py0000775000175000017500000000637313626052637023221 0ustar rogerroger#!/usr/bin/env python3 # Test for CVE-2018-12546, with the broker being stopped to write the persistence file. from mosq_test_helper import * import signal def write_config(filename, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("check_retain_source true\n") f.write("port %d\n" % (port)) f.write("acl_file %s\n" % (filename.replace('.conf', '.acl'))) f.write("persistence true\n") f.write("persistence_file %s\n" % (filename.replace('.conf', '.db'))) def write_acl_1(filename, username): with open(filename, 'w') as f: if username is not None: f.write('user %s\n' % (username)) f.write('topic readwrite test/topic\n') def write_acl_2(filename, username): with open(filename, 'w') as f: if username is not None: f.write('user %s\n' % (username)) f.write('topic read test/topic\n') def do_test(per_listener, username): conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, per_listener) persistence_file = os.path.basename(__file__).replace('.py', '.db') try: os.remove(persistence_file) except OSError: pass acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl_1(acl_file, username) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-check", keepalive=keepalive, username=username) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="retained message", retain=True) subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0) suback_packet = mosq_test.gen_suback(mid, 0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.send(publish_packet) sock.close() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 1") if mosq_test.expect_packet(sock, "publish", publish_packet): sock.close() # Remove "write" ability write_acl_2(acl_file, username) broker.terminate() broker.wait() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 2") # If we receive the retained message here, it is a failure. mosq_test.do_ping(sock) rc = 0 sock.close() finally: broker.terminate() broker.wait() os.remove(conf_file) os.remove(acl_file) os.remove(persistence_file) (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) port = mosq_test.get_port() do_test("true", username=None) do_test("true", username="test") do_test("false", username=None) do_test("false", username="test") mosquitto-1.6.9/test/broker/02-subpub-qos1-message-expiry-will.py0000775000175000017500000000511613626052637023755 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker reduces the message expiry interval when republishing a will. # MQTT v5 # Client connects with clean session set false, subscribes with qos=1, then disconnects # Helper publishes two messages, one with a short expiry and one with a long expiry # We wait until the short expiry will have expired but the long one not. # Client reconnects, expects delivery of the long expiry message with a reduced # expiry interval property. from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=5, clean_session=False, properties=props) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5, flags=1) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 10) helper_connect = mosq_test.gen_connect("helper", proto_ver=5, will_topic="subpub/qos1", will_qos=1, will_payload=b"message", will_properties=props, keepalive=2) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=5) #mid=2 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 10) publish2s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message2", proto_ver=5, properties=props) puback2s_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack1_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.close() helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) time.sleep(2) sock = mosq_test.do_client_connect(connect_packet, connack2_packet, timeout=20, port=port) packet = sock.recv(len(publish2s_packet)) for i in range(10, 5, -1): props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, i) publish2r_packet = mosq_test.gen_publish("subpub/qos1", mid=1, qos=1, payload="message", proto_ver=5, properties=props) if packet == publish2r_packet: rc = 0 break sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-qos1-max-inflight.py0000775000175000017500000000233613626052637022605 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 1 results in the correct packet flow. # With max_inflight_messages set to 1 from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("max_inflight_messages 1\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 311 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, timeout=10) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-timeout-qos2.py0000775000175000017500000000374013626052637022351 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 2 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qo2-timeout-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/timeout/test", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 1 publish_packet = mosq_test.gen_publish("qos2/timeout/test", qos=2, mid=mid, payload="timeout-message") publish_dup_packet = mosq_test.gen_publish("qos2/timeout/test", qos=2, mid=mid, payload="timeout-message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__)) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-publish-b2c-timeout-qos2-helper.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): # Wait for longer than 5 seconds to get republish with dup set # This is covered by the 8 second timeout if mosq_test.expect_packet(sock, "dup publish", publish_dup_packet): mosq_test.do_send_receive(sock, pubrec_packet, pubrel_packet, "pubrel") # Wait for longer than 5 seconds to get republish with dup set # This is covered by the 8 second timeout if mosq_test.expect_packet(sock, "dup pubrel", pubrel_packet): sock.send(pubcomp_packet) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/11-pub-props.py0000775000175000017500000000553513626052637017623 0ustar rogerroger#!/usr/bin/env python3 # Does a persisted PUBLISH keep its properties? from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect( "persistent-props-test", keepalive=keepalive, clean_session=True, proto_ver=5 ) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 1) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "/dev/null") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "2357289375902345") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "name", "value") publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5, properties=props, retain=True) puback_packet = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS, proto_ver=5) publish2_packet = mosq_test.gen_publish("subpub/qos1", qos=0, payload="message", proto_ver=5, properties=props, retain=True) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) (stdo1, stde1) = ("", "") try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish2", publish2_packet): broker.terminate() broker.wait() (stdo1, stde1) = broker.communicate() sock.close() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish2", publish2_packet): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) exit(rc) mosquitto-1.6.9/test/broker/01-connect-invalid-id-0.py0000775000175000017500000000130413626052637021465 0ustar rogerroger#!/usr/bin/env python3 # Test whether a CONNECT with a zero length client id results in the correct CONNACK packet. # MQTT V3.1 only - zero length is invalid. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("", keepalive=keepalive, proto_ver=3) connack_packet = mosq_test.gen_connack(rc=2) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-cert-auth.py0000775000175000017500000000302113626052637022010 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet using an SSL connection. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("require_certificate true\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client.crt", keyfile="../ssl/client.key", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") rc = 0 ssock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-timeout-qos2-helper.py0000775000175000017500000000146213626052637023625 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 312 publish_packet = mosq_test.gen_publish("qos2/timeout/test", qos=2, mid=mid, payload="timeout-message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack") mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "helper pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "helper pubcomp") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/07-will-delay-session-expiry2.py0000775000175000017500000000353413626052637023022 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client that connects with a will delay that is shorter than # their session expiry interval has their will published. # MQTT 5 # https://github.com/eclipse/mosquitto/issues/1401 from mosq_test_helper import * rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 2) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 4) connect2_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, properties=connect_props, will_topic="will/test", will_payload=b"will delay", will_qos=2, will_properties=will_props) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port, connack_error="connack1") mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=30, port=port, connack_error="connack2") time.sleep(1) sock2.close() # Wait for session to expire time.sleep(3) if mosq_test.expect_packet(sock1, "publish", publish_packet): rc = 0 sock1.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/c/0000775000175000017500000000000013626052637015312 5ustar rogerrogermosquitto-1.6.9/test/broker/c/auth_plugin_acl_sub_denied.c0000664000175000017500000000244213626052637022777 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { if(access == MOSQ_ACL_SUBSCRIBE){ return MOSQ_ERR_ACL_DENIED; }else{ return MOSQ_ERR_SUCCESS; } } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/auth_plugin_msg_params.c0000664000175000017500000000340213626052637022205 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { if(access == MOSQ_ACL_SUBSCRIBE){ return MOSQ_ERR_SUCCESS; } if(!msg->topic || strcmp(msg->topic, "param/topic")){ abort(); return MOSQ_ERR_ACL_DENIED; } if(!msg->payload || strncmp(msg->payload, "payload contents", strlen("payload contents"))){ abort(); return MOSQ_ERR_ACL_DENIED; } if(msg->payloadlen != strlen("payload contents")){ abort(); return MOSQ_ERR_ACL_DENIED; } if(msg->qos != 1){ abort(); return MOSQ_ERR_ACL_DENIED; } if(!msg->retain){ abort(); return MOSQ_ERR_ACL_DENIED; } return MOSQ_ERR_SUCCESS; } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/auth_plugin_v2.c0000664000175000017500000000336513626052637020413 0ustar rogerroger#include #include #include "mosquitto_plugin_v2.h" /* * Following constant come from mosquitto.h * * They are copied here to fix value of those constant at the time of MOSQ_AUTH_PLUGIN_VERSION == 2 */ enum mosq_err_t { MOSQ_ERR_SUCCESS = 0, MOSQ_ERR_AUTH = 11, MOSQ_ERR_ACL_DENIED = 12 }; int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, const char *clientid, const char *username, const char *topic, int access) { if(!strcmp(username, "readonly") && access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } int mosquitto_auth_unpwd_check(void *user_data, const char *username, const char *password) { if(!strcmp(username, "test-username") && password && !strcmp(password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(username, "readonly")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(username, "test-username@v2")){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_auth_psk_key_get(void *user_data, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/mosquitto_plugin_v2.h0000664000175000017500000001764513626052637021531 0ustar rogerroger/* Copyright (c) 2012-2014 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_PLUGIN_H #define MOSQUITTO_PLUGIN_H #define MOSQ_AUTH_PLUGIN_VERSION 2 #define MOSQ_ACL_NONE 0x00 #define MOSQ_ACL_READ 0x01 #define MOSQ_ACL_WRITE 0x02 struct mosquitto_auth_opt { char *key; char *value; }; /* * To create an authentication plugin you must include this file then implement * the functions listed below. The resulting code should then be compiled as a * shared library. Using gcc this can be achieved as follows: * * gcc -I -fPIC -shared plugin.c -o plugin.so * * On Mac OS X: * * gcc -I -fPIC -shared plugin.c -undefined dynamic_lookup -o plugin.so * */ /* ========================================================================= * * Utility Functions * * Use these functions from within your plugin. * * There are also very useful functions in libmosquitto. * * ========================================================================= */ /* * Function: mosquitto_log_printf * * Write a log message using the broker configured logging. * * Parameters: * level - Log message priority. Can currently be one of: * * MOSQ_LOG_INFO * MOSQ_LOG_NOTICE * MOSQ_LOG_WARNING * MOSQ_LOG_ERR * MOSQ_LOG_DEBUG * MOSQ_LOG_SUBSCRIBE (not recommended for use by plugins) * MOSQ_LOG_UNSUBSCRIBE (not recommended for use by plugins) * * These values are defined in mosquitto.h. * * fmt, ... - printf style format and arguments. */ void mosquitto_log_printf(int level, const char *fmt, ...); /* ========================================================================= * * Plugin Functions * * You must implement these functions in your plugin. * * ========================================================================= */ /* * Function: mosquitto_auth_plugin_version * * The broker will call this function immediately after loading the plugin to * check it is a supported plugin version. Your code must simply return * MOSQ_AUTH_PLUGIN_VERSION. */ int mosquitto_auth_plugin_version(void); /* * Function: mosquitto_auth_plugin_init * * Called after the plugin has been loaded and * has been called. This will only ever be called once and can be used to * initialise the plugin. * * Parameters: * * user_data : The pointer set here will be passed to the other plugin * functions. Use to hold connection information for example. * auth_opts : Pointer to an array of struct mosquitto_auth_opt, which * provides the plugin options defined in the configuration file. * auth_opt_count : The number of elements in the auth_opts array. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count); /* * Function: mosquitto_auth_plugin_cleanup * * Called when the broker is shutting down. This will only ever be called once. * Note that will be called directly before * this function. * * Parameters: * * user_data : The pointer provided in . * auth_opts : Pointer to an array of struct mosquitto_auth_opt, which * provides the plugin options defined in the configuration file. * auth_opt_count : The number of elements in the auth_opts array. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count); /* * Function: mosquitto_auth_security_init * * Called when the broker initialises the security functions when it starts up. * If the broker is requested to reload its configuration whilst running, * will be called, followed by this function. * In this situation, the reload parameter will be true. * * Parameters: * * user_data : The pointer provided in . * auth_opts : Pointer to an array of struct mosquitto_auth_opt, which * provides the plugin options defined in the configuration file. * auth_opt_count : The number of elements in the auth_opts array. * reload : If set to false, this is the first time the function has * been called. If true, the broker has received a signal * asking to reload its configuration. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_security_init(void *user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count, bool reload); /* * Function: mosquitto_auth_security_cleanup * * Called when the broker cleans up the security functions when it shuts down. * If the broker is requested to reload its configuration whilst running, * this function will be called, followed by . * In this situation, the reload parameter will be true. * * Parameters: * * user_data : The pointer provided in . * auth_opts : Pointer to an array of struct mosquitto_auth_opt, which * provides the plugin options defined in the configuration file. * auth_opt_count : The number of elements in the auth_opts array. * reload : If set to false, this is the first time the function has * been called. If true, the broker has received a signal * asking to reload its configuration. * * Return value: * Return 0 on success * Return >0 on failure. */ int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_auth_opt *auth_opts, int auth_opt_count, bool reload); /* * Function: mosquitto_auth_acl_check * * Called by the broker when topic access must be checked. access will be one * of MOSQ_ACL_READ (for subscriptions) or MOSQ_ACL_WRITE (for publish). Return * MOSQ_ERR_SUCCESS if access was granted, MOSQ_ERR_ACL_DENIED if access was * not granted, or MOSQ_ERR_UNKNOWN for an application specific error. */ int mosquitto_auth_acl_check(void *user_data, const char *clientid, const char *username, const char *topic, int access); /* * Function: mosquitto_auth_unpwd_check * * Called by the broker when a username/password must be checked. Return * MOSQ_ERR_SUCCESS if the user is authenticated, MOSQ_ERR_AUTH if * authentication failed, or MOSQ_ERR_UNKNOWN for an application specific * error. */ int mosquitto_auth_unpwd_check(void *user_data, const char *username, const char *password); /* * Function: mosquitto_psk_key_get * * Called by the broker when a client connects to a listener using TLS/PSK. * This is used to retrieve the pre-shared-key associated with a client * identity. * * Examine hint and identity to determine the required PSK (which must be a * hexadecimal string with no leading "0x") and copy this string into key. * * Parameters: * user_data : the pointer provided in . * hint : the psk_hint for the listener the client is connecting to. * identity : the identity string provided by the client * key : a string where the hex PSK should be copied * max_key_len : the size of key * * Return value: * Return 0 on success. * Return >0 on failure. * Return >0 if this function is not required. */ int mosquitto_auth_psk_key_get(void *user_data, const char *hint, const char *identity, char *key, int max_key_len); #endif mosquitto-1.6.9/test/broker/c/auth_plugin.c0000664000175000017500000000412413626052637017776 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { const char *username = mosquitto_client_username(client); if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_SUBSCRIBE &&!strchr(msg->topic, '#') && !strchr(msg->topic, '+')) { return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readwrite")){ if((!strcmp(msg->topic, "readonly") && access == MOSQ_ACL_READ) || !strcmp(msg->topic, "writeable")){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } }else{ return MOSQ_ERR_ACL_DENIED; } } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { if(!strcmp(username, "test-username") && password && !strcmp(password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(username, "readonly") || !strcmp(username, "readwrite")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(username, "test-username@v2")){ return MOSQ_ERR_PLUGIN_DEFER; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/auth_plugin_extended_single2.c0000664000175000017500000000414613626052637023305 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_start(void *user_data, struct mosquitto *client, const char *method, bool reauth, const void *data, uint16_t data_len, void **data_out, uint16_t *data_out_len) { int i; if(!strcmp(method, "error2")){ return MOSQ_ERR_INVAL; }else if(!strcmp(method, "non-matching2")){ return MOSQ_ERR_NOT_SUPPORTED; }else if(!strcmp(method, "single2")){ data_len = data_len>strlen("data")?strlen("data"):data_len; if(!memcmp(data, "data", data_len)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else if(!strcmp(method, "change2")){ return mosquitto_set_username(client, "new_username"); }else if(!strcmp(method, "mirror2")){ if(data_len > 0){ *data_out = malloc(data_len); if(!(*data_out)){ return MOSQ_ERR_NOMEM; } for(i=0; i #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { const char *username = mosquitto_client_username(client); if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_SUBSCRIBE &&!strchr(msg->topic, '#') && !strchr(msg->topic, '+')) { return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/08-tls-psk-bridge.c0000664000175000017500000000240713626052637020535 0ustar rogerroger#include #include #include #include #include #include static int run = -1; static int sent_mid; void on_log(struct mosquitto *mosq, void *obj, int level, const char *str) { printf("%s\n", str); } void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "psk/test", strlen("message"), "message", 1, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-tls-psk-bridge", true, NULL); mosquitto_tls_opts_set(mosq, 1, "tlsv1", NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); mosquitto_log_callback_set(mosq, on_log); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc) return rc; while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/broker/c/auth_plugin_extended_single.c0000664000175000017500000000414113626052637023216 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_start(void *user_data, struct mosquitto *client, const char *method, bool reauth, const void *data, uint16_t data_len, void **data_out, uint16_t *data_out_len) { int i; if(!strcmp(method, "error")){ return MOSQ_ERR_INVAL; }else if(!strcmp(method, "non-matching")){ return MOSQ_ERR_NOT_SUPPORTED; }else if(!strcmp(method, "single")){ data_len = data_len>strlen("data")?strlen("data"):data_len; if(!memcmp(data, "data", data_len)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else if(!strcmp(method, "change")){ return mosquitto_set_username(client, "new_username"); }else if(!strcmp(method, "mirror")){ if(data_len > 0){ *data_out = malloc(data_len); if(!(*data_out)){ return MOSQ_ERR_NOMEM; } for(i=0; i #include #include #include #include #include static int run = -1; static int sent_mid; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "psk/test", strlen("message"), "message", 0, false); } } void on_publish(struct mosquitto *mosq, void *obj, int mid) { if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } int main(int argc, char *argv[]) { int rc; int port; struct mosquitto *mosq; mosquitto_lib_init(); port = atoi(argv[1]); mosq = mosquitto_new("08-tls-psk-pub", true, NULL); mosquitto_tls_opts_set(mosq, 1, "tlsv1", NULL); rc = mosquitto_tls_psk_set(mosq, "deadbeef", "psk-id", NULL); if(rc){ mosquitto_destroy(mosq); return rc; } mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc){ mosquitto_destroy(mosq); return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-1.6.9/test/broker/c/auth_plugin_pwd.c0000664000175000017500000000276013626052637020654 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { if(!strcmp(username, "test-username") && password && !strcmp(password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(username, "readonly")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(username, "test-username@v2")){ return MOSQ_ERR_PLUGIN_DEFER; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/auth_plugin_context_params.c0000664000175000017500000000503013626052637023102 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { const char *tmp; tmp = mosquitto_client_address(client); if(!tmp || strcmp(tmp, "127.0.0.1")){ return MOSQ_ERR_AUTH; } if(!mosquitto_client_clean_session(client)){ fprintf(stderr, "mosquitto_auth_unpwd_check clean_session error: %d\n", mosquitto_client_clean_session(client)); return MOSQ_ERR_AUTH; } tmp = mosquitto_client_id(client); if(!tmp || strcmp(tmp, "client-params-test")){ fprintf(stderr, "mosquitto_auth_unpwd_check client_id error: %s\n", tmp); return MOSQ_ERR_AUTH; } if(mosquitto_client_keepalive(client) != 42){ fprintf(stderr, "mosquitto_auth_unpwd_check keepalive error: %d\n", mosquitto_client_keepalive(client)); return MOSQ_ERR_AUTH; } if(!mosquitto_client_certificate(client)){ // FIXME //return MOSQ_ERR_AUTH; } if(mosquitto_client_protocol(client) != mp_mqtt){ fprintf(stderr, "mosquitto_auth_unpwd_check protocol error: %d\n", mosquitto_client_protocol(client)); return MOSQ_ERR_AUTH; } if(mosquitto_client_sub_count(client)){ fprintf(stderr, "mosquitto_auth_unpwd_check sub_count error: %d\n", mosquitto_client_sub_count(client)); return MOSQ_ERR_AUTH; } tmp = mosquitto_client_username(client); if(!tmp || strcmp(tmp, "client-username")){ fprintf(stderr, "mosquitto_auth_unpwd_check username error: %s\n", tmp); return MOSQ_ERR_AUTH; } return MOSQ_ERR_SUCCESS; } int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len) { return MOSQ_ERR_AUTH; } mosquitto-1.6.9/test/broker/c/auth_plugin_extended_multiple.c0000664000175000017500000000404013626052637023566 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return MOSQ_AUTH_PLUGIN_VERSION; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_start(void *user_data, struct mosquitto *client, const char *method, bool reauth, const void *data, uint16_t data_len, void **data_out, uint16_t *data_out_len) { int i; if(!strcmp(method, "mirror")){ if(data_len > 0){ *data_out = malloc(data_len); if(!(*data_out)){ return MOSQ_ERR_NOMEM; } for(i=0; i 0){ len = strlen("supercalifragilisticexpialidocious")>data_len?data_len:strlen("supercalifragilisticexpialidocious"); if(!memcmp(data, "supercalifragilisticexpialidocious", len)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else{ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_NOT_SUPPORTED; } mosquitto-1.6.9/test/broker/c/Makefile0000664000175000017500000000132013626052637016746 0ustar rogerroger.PHONY: all test clean reallyclean CFLAGS=-I../../../lib -I../../../src -Wall -Werror PLUGIN_SRC = \ auth_plugin.c \ auth_plugin_pwd.c \ auth_plugin_acl.c \ auth_plugin_acl_sub_denied.c \ auth_plugin_v2.c \ auth_plugin_context_params.c \ auth_plugin_msg_params.c \ auth_plugin_extended_multiple.c \ auth_plugin_extended_single.c \ auth_plugin_extended_single2.c PLUGINS = ${PLUGIN_SRC:.c=.so} SRC = \ 08-tls-psk-pub.c \ 08-tls-psk-bridge.c TESTS = ${SRC:.c=.test} all : ${PLUGINS} ${TESTS} ${PLUGINS} : %.so: %.c $(CC) ${CFLAGS} -fPIC -shared $< -o $@ ${TESTS} : %.test: %.c $(CC) ${CFLAGS} $< -o $@ ../../../lib/libmosquitto.so.1 reallyclean : clean -rm -f *.orig clean : rm -f *.so *.test mosquitto-1.6.9/test/broker/04-retain-check-source.py0000775000175000017500000000472213626052637021526 0ustar rogerroger#!/usr/bin/env python3 # Test for CVE-2018-12546 from mosq_test_helper import * import signal def write_config(filename, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("check_retain_source true\n") f.write("port %d\n" % (port)) f.write("acl_file %s\n" % (filename.replace('.conf', '.acl'))) def write_acl_1(filename): with open(filename, 'w') as f: f.write('topic readwrite test/topic\n') def write_acl_2(filename): with open(filename, 'w') as f: f.write('topic read test/topic\n') def do_test(per_listener): conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, per_listener) acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl_1(acl_file) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-check", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="retained message", retain=True) subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0) suback_packet = mosq_test.gen_suback(mid, 0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.send(publish_packet) sock.close() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 1") if mosq_test.expect_packet(sock, "publish", publish_packet): sock.close() # Remove "write" ability write_acl_2(acl_file) broker.send_signal(signal.SIGHUP) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 2") # If we receive the retained message here, it is a failure. mosq_test.do_ping(sock) rc = 0 sock.close() finally: os.remove(conf_file) os.remove(acl_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) port = mosq_test.get_port() do_test("true") do_test("false") mosquitto-1.6.9/test/broker/04-retain-upgrade-outgoing-qos.py0000775000175000017500000000275513626052637023237 0ustar rogerroger#!/usr/bin/env python3 # Test whether a retained PUBLISH to a topic with QoS 0 is sent with subscriber QoS # when upgrade_outgoing_qos is true from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("upgrade_outgoing_qos true\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) publish_packet2 = mosq_test.gen_publish("retain/qos0/test", mid=1, qos=1, payload="retained message", retain=True) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.send(publish_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish", publish_packet2): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subscribe-qos0.py0000775000175000017500000000157013626052637020530 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 0 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: time.sleep(0.5) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-dollar-v5.py0000775000175000017500000000271113626052637021137 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to $ topics QoS 1 results in the expected PUBACK packet. from mosq_test_helper import * mid = 1 def helper(topic, reason_code): global mid publish_packet = mosq_test.gen_publish(topic, qos=1, mid=mid, payload="message", proto_ver=5) if reason_code == 0: puback_packet = mosq_test.gen_puback(mid, proto_ver=5) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=reason_code) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback%d"%(mid)) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) helper("$SYS/broker/uptime", mqtt5_rc.MQTT_RC_NOT_AUTHORIZED) helper("$SYS/broker/connection/me", mqtt5_rc.MQTT_RC_NOT_AUTHORIZED) helper("$SYS/broker/connection/me/state", mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) helper("$share/share/topic", mqtt5_rc.MQTT_RC_NOT_AUTHORIZED) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-cert-auth-crl.py0000775000175000017500000000273613626052637022602 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("require_certificate true\n") f.write("crlfile ../ssl/crl.pem\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", certfile="../ssl/client.crt", keyfile="../ssl/client.key", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") rc = 0 ssock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-v2-unpwd-success.py0000775000175000017500000000211013626052637023250 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is successful with correct username and password # when using a simple auth_plugin. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v2.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="test-username", password="cnwTICONIURW") connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-c2b-disconnect-qos2.py0000775000175000017500000000352513626052637023015 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-disco-test", keepalive=keepalive, clean_session=False, proto_ver=3) connack_packet = mosq_test.gen_connack(flags=0, rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/disconnect/test", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 1 publish_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubrel_dup_packet = mosq_test.gen_pubrel(mid, dup=True) pubcomp_packet = mosq_test.gen_pubcomp(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") # We're now going to disconnect and pretend we didn't receive the pubrec. sock.close() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.send(publish_dup_packet) if mosq_test.expect_packet(sock, "pubrec", pubrec_packet): mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") # Again, pretend we didn't receive this pubcomp sock.close() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, pubrel_dup_packet, pubcomp_packet, "pubcomp") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-reconnect-local-out-helper.py0000775000175000017500000000124313626052637024254 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("bridge/reconnect", qos=1, mid=1, payload="bridge-reconnect-message") puback_packet = mosq_test.gen_puback(mid=1) disconnect_packet = mosq_test.gen_disconnect() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="helper connack") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") sock.send(disconnect_packet) rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/06-bridge-fail-persist-resend-qos1.py0000775000175000017500000000457313626052637023674 0ustar rogerroger#!/usr/bin/env python3 # Test whether a bridge can cope with an unknown PUBACK from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge-u-test\n") f.write("remote_clientid bridge-u-test\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# out\n") f.write("\n") f.write("cleansession true\n") f.write("notifications false\n") f.write("restart_timeout 5\n") f.write("try_private false\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-u-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 180 mid_unknown = 2000 publish_packet = mosq_test.gen_publish("bridge/unknown/qos1", qos=1, payload="bridge-message", mid=mid) puback_packet = mosq_test.gen_puback(mid) puback_packet_unknown = mosq_test.gen_puback(mid_unknown) unsubscribe_packet = mosq_test.gen_unsubscribe(1, "bridge/#") unsuback_packet = mosq_test.gen_unsuback(1) if os.environ.get('MOSQ_USE_VALGRIND') is not None: sleep_time = 5 else: sleep_time = 0.5 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(10) sock.bind(('', port1)) sock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) time.sleep(sleep_time) try: (conn, address) = sock.accept() conn.settimeout(20) if mosq_test.expect_packet(conn, "connect", connect_packet): conn.send(connack_packet) if mosq_test.expect_packet(conn, "unsubscribe", unsubscribe_packet): conn.send(unsuback_packet) # Send the unexpected puback packet conn.send(puback_packet_unknown) # Send a legitimate publish packet to verify everything is still ok conn.send(publish_packet) if mosq_test.expect_packet(conn, "puback", puback_packet): rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-unsubscribe-qos2.py0000775000175000017500000000155413626052637021077 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 2 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos2/test") unsuback_packet = mosq_test.gen_unsuback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/12-prop-maximum-packet-size-publish-qos1.py0000775000175000017500000000317713626052637025072 0ustar rogerroger#!/usr/bin/env python3 # Test whether maximum packet size is honoured on a PUBLISH to a client # MQTTv5 from mosq_test_helper import * rc = 1 keepalive = 10 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MAXIMUM_PACKET_SIZE, 20) connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid=1 publish1_packet = mosq_test.gen_publish(topic="test/topic", mid=mid, qos=1, payload="12345678901234567890", proto_ver=5) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5) mid=2 publish2_packet = mosq_test.gen_publish(topic="test/topic", mid=mid, qos=1, payload="7890", proto_ver=5) puback2_packet = mosq_test.gen_puback(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet) mosq_test.do_send_receive(sock, publish1_packet, puback1_packet, "puback 1") # We shouldn't receive the publish here because it is > MAXIMUM_PACKET_SIZE mosq_test.do_ping(sock) mosq_test.do_send_receive(sock, publish2_packet, puback2_packet, "puback 2") if mosq_test.expect_packet(sock, "publish2", publish2_packet): rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-br2b-disconnect-qos2.py0000775000175000017500000001002113626052637022754 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge resend a QoS=1 message correctly after a disconnect? from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# both 2\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 3 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2) suback2_packet = mosq_test.gen_suback(mid, 2) mid = 4 subscribe3_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2) suback3_packet = mosq_test.gen_suback(mid, 2) mid = 2 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(40) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): bridge.send(suback_packet) pub = subprocess.Popen(['./06-bridge-br2b-disconnect-qos2-helper.py', str(port2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if pub.wait(): exit(1) (stdo, stde) = pub.communicate() if mosq_test.expect_packet(bridge, "publish", publish_packet): bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet): bridge.send(suback2_packet) if mosq_test.expect_packet(bridge, "2nd publish", publish_dup_packet): bridge.send(pubrec_packet) if mosq_test.expect_packet(bridge, "pubrel", pubrel_packet): bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "3rd subscribe", subscribe3_packet): bridge.send(suback3_packet) if mosq_test.expect_packet(bridge, "2nd pubrel", pubrel_packet): bridge.send(pubcomp_packet) rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-bad-puback-2.py0000775000175000017500000000435413626052637022202 0ustar rogerroger#!/usr/bin/env python3 # Test what the broker does if receiving a PUBACK in response to a QoS 2 PUBREL. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2) suback_packet = mosq_test.gen_suback(mid, 2) helper_connect = mosq_test.gen_connect("helper", keepalive=keepalive) helper_connack = mosq_test.gen_connack(rc=0) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubrec1s_packet = mosq_test.gen_pubrec(mid) pubrel1s_packet = mosq_test.gen_pubrel(mid) pubcomp1s_packet = mosq_test.gen_pubcomp(mid) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message") pubrec1r_packet = mosq_test.gen_pubrec(mid) pubrel1r_packet = mosq_test.gen_pubrel(mid) puback1r_packet = mosq_test.gen_puback(mid) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, pubrec1s_packet, "pubrec 1s") mosq_test.do_send_receive(helper, pubrel1s_packet, pubcomp1s_packet, "pubcomp 1s") helper.close() if mosq_test.expect_packet(sock, "publish 1r", publish1r_packet): mosq_test.do_send_receive(sock, pubrec1s_packet, pubrel1s_packet, "pubrel 1r") sock.send(puback1r_packet) sock.send(pingreq_packet) p = sock.recv(len(pingresp_packet)) if len(p) == 0: rc = 0 sock.close() except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-b2br-late-connection.py0000775000175000017500000000431413626052637023033 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge queue up messages correctly if the remote broker starts up late? from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# out 1\n") f.write("notifications false\n") f.write("bridge_attempt_unsubscribe false\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) c_connect_packet = mosq_test.gen_connect("client", keepalive=keepalive) c_connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("bridge/test", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(40) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: (bridge, address) = ssock.accept() bridge.settimeout(20) client = mosq_test.do_client_connect(c_connect_packet, c_connack_packet, timeout=20, port=port2) mosq_test.do_send_receive(client, publish_packet, puback_packet, "puback") client.close() # We've now sent a message to the broker that should be delivered to us via the bridge if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "publish", publish_packet): rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/12-prop-maximum-packet-size-publish-qos2.py0000775000175000017500000000400713626052637025064 0ustar rogerroger#!/usr/bin/env python3 # Test whether maximum packet size is honoured on a PUBLISH to a client # MQTTv5 from mosq_test_helper import * rc = 1 keepalive = 10 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MAXIMUM_PACKET_SIZE, 20) connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid=1 publish1_packet = mosq_test.gen_publish(topic="test/topic", mid=mid, qos=2, payload="12345678901234567890", proto_ver=5) pubrec1_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel1_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp1_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) mid=2 publish2_packet = mosq_test.gen_publish(topic="test/topic", mid=mid, qos=2, payload="7890", proto_ver=5) pubrec2_packet = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel2_packet = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp2_packet = mosq_test.gen_pubcomp(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet) mosq_test.do_send_receive(sock, publish1_packet, pubrec1_packet, "pubrec 1") mosq_test.do_send_receive(sock, pubrel1_packet, pubcomp1_packet, "pubcomp 1") # We shouldn't receive the publish here because it is > MAXIMUM_PACKET_SIZE mosq_test.do_ping(sock) mosq_test.do_send_receive(sock, publish2_packet, pubrec2_packet, "pubrec 2") mosq_test.do_send_receive(sock, pubrel2_packet, pubcomp2_packet, "pubcomp 2") if mosq_test.expect_packet(sock, "publish2", publish2_packet): rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-password-success-no-tls.py0000775000175000017500000000207413626052637025142 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is denied if it provides a correct username but # incorrect password. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="user", password="password") connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-receive-maximum-1.py0000775000175000017500000000511113626052637023275 0ustar rogerroger#!/usr/bin/env python3 # Does the broker respect receive maximum==1? # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 1 publish_packet1 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message1", proto_ver=5) pubrec_packet1 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet1 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet1 = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 2 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message2", proto_ver=5) pubrec_packet2 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet2 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet2 = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 3 publish_packet3 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message3", proto_ver=5) pubrec_packet3 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet3 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet3 = mosq_test.gen_pubcomp(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./02-subpub-qos2-receive-maximum-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() if mosq_test.expect_packet(sock, "publish1", publish_packet1): mosq_test.do_send_receive(sock, pubrec_packet1, pubrel_packet1, "pubrel1") sock.send(pubcomp_packet1) if mosq_test.expect_packet(sock, "publish2", publish_packet2): mosq_test.do_send_receive(sock, pubrec_packet2, pubrel_packet2, "pubrel2") sock.send(pubcomp_packet2) if mosq_test.expect_packet(sock, "publish3", publish_packet3): mosq_test.do_send_receive(sock, pubrec_packet3, pubrel_packet3, "pubrel3") sock.send(pubcomp_packet3) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-invalid-id-utf8.py0000775000175000017500000000145013626052637022216 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client id with invalid UTF-8 fails. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("connect-invalid-utf8", keepalive=keepalive) b = list(struct.unpack("B"*len(connect_packet), connect_packet)) b[21] = 0 # Client id should never have a 0x0000 connect_packet = struct.pack("B"*len(b), *b) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: time.sleep(0.5) sock = mosq_test.do_client_connect(connect_packet, b"", port=port) # Exception occurs if connack packet returned rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-acl-empty-file.py0000775000175000017500000000344213626052637020506 0ustar rogerroger#!/usr/bin/env python3 # Test for CVE-2018-xxxxx from mosq_test_helper import * import signal def write_config(filename, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("port %d\n" % (port)) f.write("acl_file %s\n" % (filename.replace('.conf', '.acl'))) def write_acl(filename): with open(filename, 'w') as f: f.write('#comment\n') f.write('\n') def do_test(port, per_listener): conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, per_listener) acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl(acl_file) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("acl-check", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="message") subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0) suback_packet = mosq_test.gen_suback(mid, 0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.send(publish_packet) # If we receive the message, this will fail. mosq_test.do_ping(sock) rc = 0 sock.close() finally: os.remove(conf_file) os.remove(acl_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) port = mosq_test.get_port() do_test(port, "false") do_test(port, "true") mosquitto-1.6.9/test/broker/12-prop-response-topic-correlation-data.py0000775000175000017500000000452713626052637025053 0ustar rogerroger#!/usr/bin/env python3 # client 1 subscribes to normal-topic # client 2 susbscribes to response-topic # client 2 publishes message to normal-topic with response-topic property and correlation-data property # client 1 receives message, publishes a response on response-topic # client 2 receives message, checks payload from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet1 = mosq_test.gen_connect("client1", proto_ver=5, keepalive=keepalive) connect_packet2 = mosq_test.gen_connect("client2", proto_ver=5, keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet1 = mosq_test.gen_subscribe(mid=1, topic="normal/topic", qos=0, proto_ver=5) subscribe_packet2 = mosq_test.gen_subscribe(mid=1, topic="response/topic", qos=0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid=1, qos=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "45vyvynq30q3vt4 nuy893b4v3") publish_packet2 = mosq_test.gen_publish(topic="normal/topic", qos=0, payload="2", proto_ver=5, properties=props) publish_packet1 = mosq_test.gen_publish(topic="response/topic", qos=0, payload="22", proto_ver=5) disconnect_client_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) disconnect_server_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=130) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect_packet1, connack_packet, port=port) sock2 = mosq_test.do_client_connect(connect_packet2, connack_packet, port=port) mosq_test.do_send_receive(sock1, subscribe_packet1, suback_packet, "subscribe1") mosq_test.do_send_receive(sock2, subscribe_packet2, suback_packet, "subscribe2") sock2.send(publish_packet2) if mosq_test.expect_packet(sock1, "publish1", publish_packet2): # FIXME - it would be better to extract the property and payload, even though we know them sock1.send(publish_packet1) if mosq_test.expect_packet(sock2, "publish2", publish_packet1): rc = 0 sock1.close() sock2.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/12-prop-topic-alias-invalid.py0000775000175000017500000000226413626052637022500 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker handles a topic alias of >max_topic_alias correctly. # MQTTv5 from mosq_test_helper import * def do_test(value): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS, value) publish_packet = mosq_test.gen_publish(topic="test/topic", qos=0, payload="12345678901234567890", proto_ver=5, properties=props) disconnect_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.MQTT_RC_TOPIC_ALIAS_INVALID, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.send(publish_packet) if mosq_test.expect_packet(sock, "disconnect", disconnect_packet): rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(11) mosquitto-1.6.9/test/broker/02-subpub-qos0-v5.py0000775000175000017500000000213613626052637020376 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # MQTT v5 from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos0", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("subpub/qos0", qos=0, payload="message", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, publish_packet, "publish") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-acl-access-variants.py0000775000175000017500000000746213626052637021527 0ustar rogerroger#!/usr/bin/env python3 # Check access from mosq_test_helper import * def write_config(filename, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("port %d\n" % (port)) f.write("acl_file %s\n" % (filename.replace('.conf', '.acl'))) def write_acl(filename, global_en, user_en, pattern_en): with open(filename, 'w') as f: if global_en: f.write('topic readwrite topic/global\n') if user_en: f.write('user username\n') f.write('topic readwrite topic/username\n') if pattern_en: f.write('pattern readwrite pattern/%u\n') def single_test(port, per_listener, username, topic, expect_deny): rc = 1 conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, per_listener) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: keepalive = 60 connect_packet = mosq_test.gen_connect("acl-check", keepalive=keepalive, username=username) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid=mid, topic=topic, qos=1) suback_packet = mosq_test.gen_suback(mid=mid, qos=1) mid = 2 publish1s_packet = mosq_test.gen_publish(topic=topic, mid=mid, qos=1, payload="message") puback1s_packet = mosq_test.gen_puback(mid) mid=1 publish1r_packet = mosq_test.gen_publish(topic=topic, mid=mid, qos=1, payload="message") sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish1s_packet, puback1s_packet, "puback") if expect_deny: mosq_test.do_ping(sock) else: mosq_test.expect_packet(sock, "publish1r", publish1r_packet) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) def acl_test(port, per_listener, global_en, user_en, pattern_en): acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl(acl_file, global_en=global_en, user_en=user_en, pattern_en=pattern_en) if global_en: single_test(port, per_listener, username=None, topic="topic/global", expect_deny=False) single_test(port, per_listener, username="username", topic="topic/global", expect_deny=True) if user_en: single_test(port, per_listener, username=None, topic="topic/username", expect_deny=True) single_test(port, per_listener, username="username", topic="topic/username", expect_deny=False) if pattern_en: single_test(port, per_listener, username=None, topic="pattern/username", expect_deny=True) single_test(port, per_listener, username="username", topic="pattern/username", expect_deny=False) def do_test(port, per_listener): try: acl_test(port, per_listener, global_en=False, user_en=False, pattern_en=True) acl_test(port, per_listener, global_en=False, user_en=True, pattern_en=False) acl_test(port, per_listener, global_en=True, user_en=False, pattern_en=False) acl_test(port, per_listener, global_en=False, user_en=True, pattern_en=True) acl_test(port, per_listener, global_en=True, user_en=False, pattern_en=True) acl_test(port, per_listener, global_en=True, user_en=True, pattern_en=True) finally: acl_file = os.path.basename(__file__).replace('.py', '.acl') os.remove(acl_file) port = mosq_test.get_port() do_test(port, "true") do_test(port, "false") mosquitto-1.6.9/test/broker/12-prop-subpub-payload-format.py0000775000175000017500000000106213626052637023057 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # Does the Payload Format Indicator property get sent through? # MQTT v5 import prop_subpub_helper as helper from mosq_test_helper import * props_out = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 0xed) props_out = props_out+mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS, 1) props_in = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 0xed) helper.prop_subpub_helper(props_out, props_in) mosquitto-1.6.9/test/broker/09-auth-bad-method.py0000775000175000017500000000155213626052637020641 0ustar rogerroger#!/usr/bin/env python3 # Test whether sending an Authentication Method produces the correct response # when no auth methods are defined. from mosq_test_helper import * rc = 1 keepalive = 10 props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "basic") connect_packet = mosq_test.gen_connect("connect-test", proto_ver=5, keepalive=keepalive, properties=props) connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-tls-psk-bridge.py0000775000175000017500000000542013626052637020522 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config1(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write("\n") f.write("psk_file 08-tls-psk-bridge.psk\n") f.write("\n") f.write("port %d\n" % (port1)) f.write("\n") f.write("listener %d\n" % (port2)) f.write("psk_hint hint\n") def write_config2(filename, port2, port3): with open(filename, 'w') as f: f.write("port %d\n" % (port3)) f.write("\n") f.write("connection bridge-psk\n") f.write("address localhost:%d\n" % (port2)) f.write("topic psk/test out\n") f.write("bridge_identity psk-test\n") f.write("bridge_psk deadbeef\n") (port1, port2, port3) = mosq_test.get_port(3) conf_file1 = "08-tls-psk-bridge.conf" conf_file2 = "08-tls-psk-bridge.conf2" write_config1(conf_file1, port1, port2) write_config2(conf_file2, port2, port3) env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' try: pp = env['PYTHONPATH'] except KeyError: pp = '' env['PYTHONPATH'] = '../../lib/python:'+pp rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("no-psk-test-client", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "psk/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish(topic="psk/test", payload="message", qos=0) bridge_cmd = ['../../src/mosquitto', '-c', '08-tls-psk-bridge.conf2'] broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port1) bridge = mosq_test.start_broker(filename=os.path.basename(__file__)+'_bridge', cmd=bridge_cmd, port=port3) pub = None try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=30, port=port1) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./c/08-tls-psk-bridge.test', str(port3)], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if pub.wait(): raise ValueError (stdo, stde) = pub.communicate() if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: os.remove(conf_file1) os.remove(conf_file2) time.sleep(1) broker.terminate() broker.wait() time.sleep(1) bridge.terminate() bridge.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) (stdo, stde) = bridge.communicate() print(stde.decode('utf-8')) if pub: (stdo, stde) = pub.communicate() print(stdo.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-disconnect-qos2-helper.py0000775000175000017500000000154113626052637024266 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow. from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 312 publish_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack", port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "helper pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "helper pubcomp") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/01-connect-invalid-reserved.py0000775000175000017500000000144113626052637022555 0ustar rogerroger#!/usr/bin/env python3 # Test whether a CONNECT with reserved set to 1 results in a disconnect. MQTT-3.1.2-3 from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-invalid-test", keepalive=keepalive, connect_reserved=True, proto_ver=4) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", port=port) sock.close() rc = 0 except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-tls-psk-bridge.psk0000664000175000017500000000002213626052637020655 0ustar rogerrogerpsk-test:deadbeef mosquitto-1.6.9/test/broker/03-publish-b2c-timeout-qos1-helper.py0000775000175000017500000000121313626052637023616 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test.gen_publish("qos1/timeout/test", qos=1, mid=mid, payload="timeout-message") puback_packet = mosq_test.gen_puback(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "helper puback") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos0-send-retain.py0000775000175000017500000000651013626052637022255 0ustar rogerroger#!/usr/bin/env python3 # Test whether "send retain" subscribe options work # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 530 subscribe1_packet = mosq_test.gen_subscribe(mid, "subpub/always", 0 | mqtt5_opts.MQTT_SUB_OPT_SEND_RETAIN_ALWAYS, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) mid = 531 subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/new", 0 | mqtt5_opts.MQTT_SUB_OPT_SEND_RETAIN_NEW, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) mid = 532 subscribe3_packet = mosq_test.gen_subscribe(mid, "subpub/never", 0 | mqtt5_opts.MQTT_SUB_OPT_SEND_RETAIN_NEVER, proto_ver=5) suback3_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish("subpub/always", qos=0, retain=True, payload="message", proto_ver=5) publish2_packet = mosq_test.gen_publish("subpub/new", qos=0, retain=True, payload="message", proto_ver=5) publish3_packet = mosq_test.gen_publish("subpub/never", qos=0, retain=True, payload="message", proto_ver=5) publish1r1_packet = mosq_test.gen_publish("subpub/always", qos=0, retain=True, payload="message", proto_ver=5) publish1r2_packet = mosq_test.gen_publish("subpub/always", qos=0, retain=True, payload="message", proto_ver=5) publish2r1_packet = mosq_test.gen_publish("subpub/new", qos=0, retain=True, payload="message", proto_ver=5) publish2r2_packet = mosq_test.gen_publish("subpub/new", qos=0, retain=False, payload="message", proto_ver=5) publish3r1_packet = mosq_test.gen_publish("subpub/never", qos=0, retain=False, payload="message", proto_ver=5) publish3r2_packet = mosq_test.gen_publish("subpub/never", qos=0, retain=False, payload="message", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) sock.send(publish1_packet) sock.send(publish2_packet) sock.send(publish3_packet) # Don't expect a message after this mosq_test.do_send_receive(sock, subscribe3_packet, suback3_packet, "suback3") # Don't expect a message after this mosq_test.do_send_receive(sock, subscribe3_packet, suback3_packet, "suback3") # Expect a message after this, because it is the first subscribe mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") if mosq_test.expect_packet(sock, "publish2r1", publish2r1_packet): # Don't expect a message after this, it is the second subscribe mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") # Always expect a message after this mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") if mosq_test.expect_packet(sock, "publish1r1", publish1r1_packet): # Always expect a message after this mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") if mosq_test.expect_packet(sock, "publish1r1", publish1r2_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subscribe-invalid-utf8.py0000775000175000017500000000200713626052637022154 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with an invalid UTF-8 topic fails from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-invalid-utf8", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "invalid/utf8", 0) b = list(struct.unpack("B"*len(subscribe_packet), subscribe_packet)) b[13] = 0 # Topic should never have a 0x0000 subscribe_packet = struct.pack("B"*len(b), *b) suback_packet = mosq_test.gen_suback(mid, 0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: time.sleep(0.5) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-password-success-no-tls.pwfile0000664000175000017500000000001613626052637025767 0ustar rogerrogeruser:password mosquitto-1.6.9/test/broker/05-session-expiry-v5.py0000775000175000017500000000774413626052637021234 0ustar rogerroger#!/usr/bin/env python3 # MQTT v5. Test whether session expiry interval works correctly. from mosq_test_helper import * rc = 1 keepalive = 60 # This client exists to test possible fixed size int overflow and sorting of the session intervals # https://github.com/eclipse/mosquitto/issues/1525 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 4294967294) connect0_packet = mosq_test.gen_connect("overflow", keepalive=keepalive, clean_session=False, proto_ver=5, properties=props) connack0_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 1) connect_packet = mosq_test.gen_connect("clean-qos2-test", keepalive=keepalive, clean_session=False, proto_ver=5, properties=props) connack1_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=5) connack2_packet = mosq_test.gen_connack(flags=1, rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 3) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) disconnect2_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # Connect client with wildly different session expiry, this should impact # on the test if all is well sock0 = mosq_test.do_client_connect(connect0_packet, connack0_packet, port=port, connack_error="connack 0") # Immediately disconnect, this should now be queued to expire sock0.close() # First connect, clean start is false, we expect a normal connack sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port, connack_error="connack 1") # Forceful disconnect sock.close() # Immediate second connect, clean start is false, we expect a connack with # previous state sock = mosq_test.do_client_connect(connect_packet, connack2_packet, port=port, connack_error="connack 2") sock.close() # Session should expire in one second, so sleep longer time.sleep(2) # Third connect, clean start is false, session should have expired so we # expect a normal connack sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port, connack_error="connack 3") # Send DISCONNECT with new session expiry, then close sock.send(disconnect_packet) sock.close() # Immediate reconnect, clean start is false, we expect a connack with # previous state sock = mosq_test.do_client_connect(connect_packet, connack2_packet, port=port, connack_error="connack 4") # Send DISCONNECT with new session expiry, then close sock.send(disconnect_packet) sock.close() # Session should expire in three seconds if it has been updated, sleep for # 2 to check it is updated from 1 second. time.sleep(2) # Immediate reconnect, clean start is false, we expect a connack with # previous state sock = mosq_test.do_client_connect(connect_packet, connack2_packet, port=port, connack_error="connack 5") # Send DISCONNECT with new session expiry, then close sock.send(disconnect_packet) sock.close() # Session should expire in three seconds, so sleep longer time.sleep(4) # Third connect, clean start is false, session should have expired so we # expect a normal connack sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port, connack_error="connack 6") # Send DISCONNECT with 0 session expiry, then close sock.send(disconnect2_packet) sock.close() # Immediate reconnect, session should have been removed. sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port, connack_error="connack 7") sock.close() rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-null-topic.py0000775000175000017500000000146413626052637020731 0ustar rogerroger#!/usr/bin/env python3 import struct from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("will-null-topic", keepalive=keepalive, will_topic="", will_payload=struct.pack("!4sB7s", b"will", 0, b"message")) connack_packet = mosq_test.gen_connack(rc=2) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", timeout=30, port=port) rc = 0 sock.close() except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-extended-auth-single2.py0000775000175000017500000000770013626052637021777 0ustar rogerroger#!/usr/bin/env python3 # Multi tests for extended auth with a single step - multiple plugins at once. # * Error in plugin # * No matching authentication method # * Matching authentication method, but auth rejected # * Matching authentication method, auth succeeds # * Matching authentication method, auth succeeds, new auth data sent back to client from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_extended_single.so\n") f.write("auth_plugin c/auth_plugin_extended_single2.so\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') def do_test(suffix): write_config(conf_file, port) rc = 1 # Single, error in plugin props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "error%s" % (suffix)) connect1_packet = mosq_test.gen_connect("client-params-test1", keepalive=42, proto_ver=5, properties=props) # Single, no matching authentication method props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "non-matching%s" % (suffix)) connect2_packet = mosq_test.gen_connect("client-params-test2", keepalive=42, proto_ver=5, properties=props) connack2_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) # Single step, matching method, failure props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "single%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "baddata") connect3_packet = mosq_test.gen_connect("client-params-test3", keepalive=42, proto_ver=5, properties=props) connack3_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, properties=None) # Single step, matching method, success props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "single%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "data") connect4_packet = mosq_test.gen_connect("client-params-test5", keepalive=42, proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "single%s" % (suffix)) connack4_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) # Single step, matching method, success, auth data back to client props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "somedata") connect5_packet = mosq_test.gen_connect("client-params-test6", keepalive=42, proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "atademos") connack5_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect1_packet, b"", timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect3_packet, connack3_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect4_packet, connack4_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect5_packet, connack5_packet, timeout=20, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("") do_test("2") exit(0) mosquitto-1.6.9/test/broker/09-pwfile-parse-invalid.py0000775000175000017500000001513113626052637021716 0ustar rogerroger#!/usr/bin/env python3 # Test for CVE-2018-xxxxx. from mosq_test_helper import * import signal def write_config(filename, port, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("port %d\n" % (port)) f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) f.write("allow_anonymous false") def write_pwfile(filename, bad_line1, bad_line2): with open(filename, 'w') as f: if bad_line1 is not None: f.write('%s\n' % (bad_line1)) # Username test, password test f.write('test:$6$njERlZMi/7DzNB9E$iiavfuXvUm8iyDZArTy7smTxh07GXXOrOsqxfW6gkOYVXHGk+W+i/8d3xDxrMwEPygEBhoA8A/gjQC0N2M4Lkw==\n') # Username empty, password 0 length f.write('empty:$6$o+53eGXtmlfHeYrg$FY7X9DNQ4uU1j0NiPmGOOSU05ZSzhqNmNhXIof/0nLpVb1zDhcRHdaC72E3YryH7dtTiG/r6jH6C8J+30cZBgA==\n') if bad_line2 is not None: f.write('%s\n' % (bad_line2)) def do_test(port, connack_rc, username, password): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("username-password-check", keepalive=keepalive, username=username, password=password) connack_packet = mosq_test.gen_connack(rc=connack_rc) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) rc = 0 sock.close() finally: if rc: raise AssertionError def username_password_tests(port): broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: do_test(port, connack_rc=0, username='test', password='test') do_test(port, connack_rc=5, username='test', password='bad') do_test(port, connack_rc=5, username='test', password='') do_test(port, connack_rc=5, username='test', password=None) do_test(port, connack_rc=5, username='empty', password='test') do_test(port, connack_rc=5, username='empty', password='bad') do_test(port, connack_rc=5, username='empty', password='') do_test(port, connack_rc=5, username='empty', password=None) do_test(port, connack_rc=5, username='bad', password='test') do_test(port, connack_rc=5, username='bad', password='bad') do_test(port, connack_rc=5, username='bad', password='') do_test(port, connack_rc=5, username='bad', password=None) do_test(port, connack_rc=5, username='', password='test') do_test(port, connack_rc=5, username='', password='bad') do_test(port, connack_rc=5, username='', password='') do_test(port, connack_rc=5, username='', password=None) do_test(port, connack_rc=5, username=None, password='test') do_test(port, connack_rc=5, username=None, password='bad') do_test(port, connack_rc=5, username=None, password='') do_test(port, connack_rc=5, username=None, password=None) except ValueError: pass finally: broker.terminate() broker.wait() def all_tests(port): # Valid file, single user write_pwfile(pw_file, bad_line1=None, bad_line2=None) username_password_tests(port) # Invalid file, first line blank write_pwfile(pw_file, bad_line1='', bad_line2=None) username_password_tests(port) # Invalid file, last line blank write_pwfile(pw_file, bad_line1=None, bad_line2='') username_password_tests(port) # Invalid file, first and last line blank write_pwfile(pw_file, bad_line1='', bad_line2='') username_password_tests(port) # Invalid file, first line 'comment' write_pwfile(pw_file, bad_line1='#comment', bad_line2=None) username_password_tests(port) # Invalid file, last line 'comment' write_pwfile(pw_file, bad_line1=None, bad_line2='#comment') username_password_tests(port) # Invalid file, first and last line 'comment' write_pwfile(pw_file, bad_line1='#comment', bad_line2='#comment') username_password_tests(port) # Invalid file, first line blank and last line 'comment' write_pwfile(pw_file, bad_line1='', bad_line2='#comment') username_password_tests(port) # Invalid file, first line incomplete write_pwfile(pw_file, bad_line1='bad:', bad_line2=None) username_password_tests(port) # Invalid file, first line incomplete, but with "password" write_pwfile(pw_file, bad_line1='bad:bad', bad_line2=None) username_password_tests(port) # Invalid file, first line incomplete, partial password hash write_pwfile(pw_file, bad_line1='bad:$', bad_line2=None) username_password_tests(port) # Invalid file, first line incomplete, partial password hash write_pwfile(pw_file, bad_line1='bad:$6', bad_line2=None) username_password_tests(port) # Invalid file, first line incomplete, partial password hash write_pwfile(pw_file, bad_line1='bad:$6$', bad_line2=None) username_password_tests(port) # Valid file, first line incomplete, has valid salt but no password hash write_pwfile(pw_file, bad_line1='bad:$6$njERlZMi/7DzNB9E', bad_line2=None) username_password_tests(port) # Valid file, first line incomplete, has valid salt but no password hash write_pwfile(pw_file, bad_line1='bad:$6$njERlZMi/7DzNB9E$', bad_line2=None) username_password_tests(port) # Valid file, first line has invalid hash designator write_pwfile(pw_file, bad_line1='bad:$5$njERlZMi/7DzNB9E$iiavfuXvUm8iyDZArTy7smTxh07GXXOrOsqxfW6gkOYVXHGk+W+i/8d3xDxrMwEPygEBhoA8A/gjQC0N2M4Lkw==', bad_line2=None) username_password_tests(port) # Invalid file, missing username but valid password hash write_pwfile(pw_file, bad_line1=':$6$njERlZMi/7DzNB9E$iiavfuXvUm8iyDZArTy7smTxh07GXXOrOsqxfW6gkOYVXHGk+W+i/8d3xDxrMwEPygEBhoA8A/gjQC0N2M4Lkw==', bad_line2=None) username_password_tests(port) # Valid file, valid username but password salt not base64 write_pwfile(pw_file, bad_line1='bad:$6$njER{ZMi/7DzNB9E$iiavfuXvUm8iyDZArTy7smTxh07GXXOrOsqxfW6gkOYVXHGk+W+i/8d3xDxrMwEPygEBhoA8A/gjQC0N2M4Lkw==', bad_line2=None) username_password_tests(port) # Valid file, valid username but password hash not base64 write_pwfile(pw_file, bad_line1='bad:$6$njERlZMi/7DzNB9E$iiavfuXv{}8iyDZArTy7smTxh07GXXOrOsqxfW6gkOYVXHGk+W+i/8d3xDxrMwEPygEBhoA8A/gjQC0N2M4Lkw==', bad_line2=None) username_password_tests(port) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') pw_file = os.path.basename(__file__).replace('.py', '.pwfile') try: write_config(conf_file, port, "false") all_tests(port) write_config(conf_file, port, "true") all_tests(port) finally: os.remove(conf_file) os.remove(pw_file) sys.exit(0) mosquitto-1.6.9/test/broker/03-publish-b2c-disconnect-qos1.py0000775000175000017500000000425213626052637023012 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-disco-test", keepalive=keepalive, clean_session=False) connack1_packet = mosq_test.gen_connack(flags=0, rc=0) connack2_packet = mosq_test.gen_connack(flags=1, rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/disconnect/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 1 publish_packet = mosq_test.gen_publish("qos1/disconnect/test", qos=1, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("qos1/disconnect/test", qos=1, mid=mid, payload="disconnect-message", dup=True) puback_packet = mosq_test.gen_puback(mid) mid = 3266 publish2_packet = mosq_test.gen_publish("qos1/outgoing", qos=1, mid=mid, payload="outgoing-message") puback2_packet = mosq_test.gen_puback(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-publish-b2c-disconnect-qos1-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): # Send our outgoing message. When we disconnect the broker # should get rid of it and assume we're going to retry. sock.send(publish2_packet) sock.close() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(60) # 60 seconds timeout is much longer than 5 seconds message retry. sock.connect(("localhost", port)) mosq_test.do_send_receive(sock, connect_packet, connack2_packet, "connack") if mosq_test.expect_packet(sock, "dup publish", publish_dup_packet): sock.send(puback_packet) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-disconnect-qos2.py0000775000175000017500000000460113626052637023011 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-disco-test", keepalive=keepalive, clean_session=False) connack1_packet = mosq_test.gen_connack(flags=0, rc=0) connack2_packet = mosq_test.gen_connack(flags=1, rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/disconnect/test", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 1 publish_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) mid = 3266 publish2_packet = mosq_test.gen_publish("qos1/outgoing", qos=1, mid=mid, payload="outgoing-message") puback2_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-publish-b2c-disconnect-qos2-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) hrc = pub.wait() (stdo, stde) = pub.communicate() if hrc: exit(hrc) # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): # Send our outgoing message. When we disconnect the broker # should get rid of it and assume we're going to retry. sock.send(publish2_packet) sock.close() sock = mosq_test.do_client_connect(connect_packet, connack2_packet, port=port) if mosq_test.expect_packet(sock, "dup publish", publish_dup_packet): mosq_test.do_send_receive(sock, pubrec_packet, pubrel_packet, "pubrel") sock.close() sock = mosq_test.do_client_connect(connect_packet, connack2_packet, port=port) if mosq_test.expect_packet(sock, "dup pubrel", pubrel_packet): sock.send(pubcomp_packet) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-success-v5.py0000775000175000017500000000126113626052637021312 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet for MQTT v5. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", proto_ver=5, keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/04-retain-qos0-repeated.py0000775000175000017500000000300713626052637021617 0ustar rogerroger#!/usr/bin/env python3 # Test whether a retained PUBLISH to a topic with QoS 0 is actually retained # and delivered when multiple sub/unsub operations are carried out. from mosq_test_helper import * rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-rep-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) unsub_mid = 13 unsubscribe_packet = mosq_test.gen_unsubscribe(unsub_mid, "retain/qos0/test") unsuback_packet = mosq_test.gen_unsuback(unsub_mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) sock.send(publish_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish", publish_packet): mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-shared-qos0-v5.py0000775000175000017500000001466013626052637020351 0ustar rogerroger#!/usr/bin/env python3 # Test whether shared subscriptions work # Client 1 subscribes to #, non shared. Should receive everything. # Client 2 subscribes to $share/one/share-test # Client 3 subscribes to $share/one/share-test and $share/two/share-test # Client 4 subscribes to $share/two/share-test # Client 5 subscribes to $share/one/share-test # A publish to "share-test" should always go to client 1. # The first publish should also go to client 2 (share one) and client 3 (share two) # The second publish should also go to client 3 (share one) and client 4 (share two) # The third publish should also go to client 3 (share two) and client 5 (share one) from mosq_test_helper import * rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("client1", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2_packet = mosq_test.gen_connect("client2", keepalive=keepalive, proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect3_packet = mosq_test.gen_connect("client3", keepalive=keepalive, proto_ver=5) connack3_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect4_packet = mosq_test.gen_connect("client4", keepalive=keepalive, proto_ver=5) connack4_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect5_packet = mosq_test.gen_connect("client5", keepalive=keepalive, proto_ver=5) connack5_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe1_packet = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) subscribe2_packet = mosq_test.gen_subscribe(mid, "$share/one/share-test", 0, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) subscribe3a_packet = mosq_test.gen_subscribe(mid, "$share/one/share-test", 0, proto_ver=5) suback3a_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) subscribe3b_packet = mosq_test.gen_subscribe(mid, "$share/two/share-test", 0, proto_ver=5) suback3b_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) subscribe4_packet = mosq_test.gen_subscribe(mid, "$share/two/share-test", 0, proto_ver=5) suback4_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) subscribe5_packet = mosq_test.gen_subscribe(mid, "$share/one/share-test", 0, proto_ver=5) suback5_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish("share-test", qos=0, payload="message1", proto_ver=5) publish2_packet = mosq_test.gen_publish("share-test", qos=0, payload="message2", proto_ver=5) publish3_packet = mosq_test.gen_publish("share-test", qos=0, payload="message3", proto_ver=5) mid = 2 unsubscribe1_packet = mosq_test.gen_unsubscribe(mid, "#", proto_ver=5) unsuback1_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe2_packet = mosq_test.gen_unsubscribe(mid, "$share/one/share-test", proto_ver=5) unsuback2_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe3a_packet = mosq_test.gen_unsubscribe(mid, "$share/one/share-test", proto_ver=5) unsuback3a_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe3b_packet = mosq_test.gen_unsubscribe(mid, "$share/two/share-test", proto_ver=5) unsuback3b_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe4_packet = mosq_test.gen_unsubscribe(mid, "$share/two/share-test", proto_ver=5) unsuback4_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe5_packet = mosq_test.gen_unsubscribe(mid, "$share/one/share-test", proto_ver=5) unsuback5_packet = mosq_test.gen_unsuback(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=20, port=port) sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) sock3 = mosq_test.do_client_connect(connect3_packet, connack3_packet, timeout=20, port=port) sock4 = mosq_test.do_client_connect(connect4_packet, connack4_packet, timeout=20, port=port) sock5 = mosq_test.do_client_connect(connect5_packet, connack5_packet, timeout=20, port=port) mosq_test.do_send_receive(sock1, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock2, subscribe2_packet, suback2_packet, "suback2") mosq_test.do_send_receive(sock3, subscribe3a_packet, suback3a_packet, "suback3a") mosq_test.do_send_receive(sock3, subscribe3b_packet, suback3b_packet, "suback3b") mosq_test.do_send_receive(sock4, subscribe4_packet, suback4_packet, "suback4") mosq_test.do_send_receive(sock5, subscribe5_packet, suback5_packet, "suback5") sock1.send(publish1_packet) if mosq_test.expect_packet(sock1, "publish1 1", publish1_packet): if mosq_test.expect_packet(sock2, "publish1 2", publish1_packet): if mosq_test.expect_packet(sock3, "publish1 3", publish1_packet): sock1.send(publish2_packet) if mosq_test.expect_packet(sock1, "publish2 1", publish2_packet): if mosq_test.expect_packet(sock3, "publish2 3", publish2_packet): if mosq_test.expect_packet(sock4, "publish2 4", publish2_packet): sock1.send(publish3_packet) if mosq_test.expect_packet(sock1, "publish3 1", publish3_packet): if mosq_test.expect_packet(sock3, "publish3 3", publish3_packet): if mosq_test.expect_packet(sock5, "publish3 5", publish3_packet): mosq_test.do_send_receive(sock1, unsubscribe1_packet, unsuback1_packet, "unsuback1") mosq_test.do_send_receive(sock2, unsubscribe2_packet, unsuback2_packet, "unsuback2") mosq_test.do_send_receive(sock3, unsubscribe3a_packet, unsuback3a_packet, "unsuback3a") mosq_test.do_send_receive(sock3, unsubscribe3b_packet, unsuback3b_packet, "unsuback3b") mosq_test.do_send_receive(sock4, unsubscribe4_packet, unsuback4_packet, "unsuback4") mosq_test.do_send_receive(sock5, unsubscribe5_packet, unsuback5_packet, "unsuback5") rc = 0 sock1.close() sock2.close() sock3.close() sock4.close() sock5.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-invalid-id-missing.py0000775000175000017500000000123413626052637023001 0ustar rogerroger#!/usr/bin/env python3 # Test whether a CONNECT with a zero length client id results in the correct CONNACK packet. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect(None, keepalive=keepalive, proto_ver=3) connack_packet = mosq_test.gen_connack(rc=2) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-per-listener-settings.py0000775000175000017500000001041113626052637023366 0ustar rogerroger#!/usr/bin/env python3 # Test remapping of topic name for incoming message from mosq_test_helper import * def write_config(filename, port1, port2, port3): with open(filename, 'w') as f: f.write("per_listener_settings true\n") f.write("port %d\n" % (port2)) f.write("listener %d 127.0.0.1\n" % (port3)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("bridge_attempt_unsubscribe false\n") f.write("topic # in 0 local/topic/ remote/topic/\n") f.write("topic prefix/# in 0 local2/topic/ remote2/topic/\n") f.write("topic +/value in 0 local3/topic/ remote3/topic/\n") f.write("topic ic/+ in 0 local4/top remote4/tip\n") f.write("topic clients/total in 0 test/mosquitto/org $SYS/broker/\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2, port3) = mosq_test.get_port(3) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, port3) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive) client_connack_packet = mosq_test.gen_connack(rc=0) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(4) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) def test(bridge, sock): if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) mid = 0 patterns = [ "remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value", "remote4/tipic/+", "$SYS/broker/clients/total", ] for pattern in ("remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value"): mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, pattern, 0) suback_packet = mosq_test.gen_suback(mid, 0) if not mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): return 1 bridge.send(suback_packet) mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) suback_packet = mosq_test.gen_suback(mid, 0) sock.send(subscribe_packet) if not mosq_test.expect_packet(sock, "suback", suback_packet): return 1 cases = [ ('local/topic/something', 'remote/topic/something'), ('local/topic/some/t/h/i/n/g', 'remote/topic/some/t/h/i/n/g'), ('local/topic/value', 'remote/topic/value'), # Don't work, #40 must be fixed before # ('local/topic', 'remote/topic'), ('local2/topic/prefix/something', 'remote2/topic/prefix/something'), ('local3/topic/something/value', 'remote3/topic/something/value'), ('local4/topic/something', 'remote4/tipic/something'), ('test/mosquitto/orgclients/total', '$SYS/broker/clients/total'), ] for (local_topic, remote_topic) in cases: mid += 1 remote_publish_packet = mosq_test.gen_publish( remote_topic, qos=0, mid=mid, payload='' ) local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='' ) bridge.send(remote_publish_packet) match = mosq_test.expect_packet(sock, "publish", local_publish_packet) if not match: print("Fail on cases local_topic=%r, remote_topic=%r" % ( local_topic, remote_topic, )) return 1 return 0 try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = test(bridge, sock) sock.close() bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-invalid-utf8.py0000775000175000017500000000147713626052637022740 0ustar rogerroger#!/usr/bin/env python3 # Test whether a username with invalid UTF-8 fails. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("connect-invalid-utf8", keepalive=keepalive, username="invalid/utf8") b = list(struct.unpack("B"*len(connect_packet), connect_packet)) b[43] = 0 # Username should never have a 0x0000 connect_packet = struct.pack("B"*len(b), *b) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: time.sleep(0.5) sock = mosq_test.do_client_connect(connect_packet, b"", port=port) # Exception occurs if connack packet returned rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/mosq_test_helper.py0000664000175000017500000000072313626052637021021 0ustar rogerrogerimport inspect, os, sys # From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],".."))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) import mosq_test import mqtt5_opts import mqtt5_props import mqtt5_rc import socket import ssl import struct import subprocess import time import errno mosquitto-1.6.9/test/broker/01-connect-anon-denied.py0000775000175000017500000000175213626052637021500 0ustar rogerroger#!/usr/bin/env python3 # Test whether an anonymous connection is correctly denied. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-anon-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/05-clean-session-qos1-helper.py0000775000175000017500000000121513626052637022567 0ustar rogerroger#!/usr/bin/env python3 # Test whether a clean session client has a QoS 1 message queued for it. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test.gen_publish("qos1/clean_session/test", qos=1, mid=mid, payload="clean-session-message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-password-denied.pwfile0000664000175000017500000000016213626052637024337 0ustar rogerrogeruser:$6$vZY4TS+/HBxHw38S$vvjVFECzb8dyuu/mruD2QKTfdFn0WmKxbc+1TsdB0L8EdHk3v9JRmfjHd56+VaTnUcSZOZ/hzkdvWCtxlX7AUQ== mosquitto-1.6.9/test/broker/11-persistent-subscription-no-local.py0000775000175000017500000000671513626052637024321 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # And whether the no-local option is persisted. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 100) connect_packet = mosq_test.gen_connect( "persistent-subscription-test", keepalive=keepalive, clean_session=False, proto_ver=5, properties=props ) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=5) # session present mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "subpub/nolocal", 5, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/local", 1, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 1 publish1_packet = mosq_test.gen_publish("subpub/nolocal", qos=1, mid=mid, payload="message", proto_ver=5) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 2 publish2s_packet = mosq_test.gen_publish("subpub/local", qos=1, mid=mid, payload="message", proto_ver=5) puback2s_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 1 publish2a_packet = mosq_test.gen_publish("subpub/local", qos=1, mid=mid, payload="message", proto_ver=5) puback2a_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 2 publish2b_packet = mosq_test.gen_publish("subpub/local", qos=1, mid=mid, payload="message", proto_ver=5) puback2b_packet = mosq_test.gen_puback(mid, proto_ver=5) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) (stdo1, stde1) = ("", "") try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") mosq_test.do_send_receive(sock, publish1_packet, puback1_packet, "puback1a") mosq_test.do_send_receive(sock, publish2s_packet, puback2s_packet, "puback2a") if mosq_test.expect_packet(sock, "publish2a", publish2a_packet): sock.send(puback2a_packet) broker.terminate() broker.wait() (stdo1, stde1) = broker.communicate() sock.close() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=20, port=port) mosq_test.do_send_receive(sock, publish1_packet, puback1_packet, "puback1b") mosq_test.do_send_receive(sock, publish2s_packet, puback2s_packet, "puback2b") if mosq_test.expect_packet(sock, "publish2b", publish2b_packet): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-qos1-len.py0000775000175000017500000000440413626052637021436 0ustar rogerroger#!/usr/bin/env python3 # Check whether the broker handles a v5 PUBACK with all combinations # of with/without reason code and properties. from mosq_test_helper import * def len_test(test, puback_packet): port = mosq_test.get_port() rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/len/test", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("qos1/len/test", qos=1, mid=mid, payload="len-message", proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-publish-b2c-qos1-len-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): sock.send(puback_packet) mosq_test.do_ping(sock) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if rc != 0: print(test) exit(rc) # No reason code, no properties puback_packet = mosq_test.gen_puback(1) len_test("qos1 len 2", puback_packet) # Reason code, no properties puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00) len_test("qos1 len 3", puback_packet) # Reason code, empty properties puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00, properties="") len_test("qos1 len 4", puback_packet) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00, properties=props) len_test("qos1 len >5", puback_packet) mosquitto-1.6.9/test/broker/03-publish-qos1-queued-bytes.conf0000664000175000017500000000010413626052637023113 0ustar rogerrogersys_interval 1 max_queued_messages 0 max_queued_bytes 400 port 1888 mosquitto-1.6.9/test/broker/test.py0000775000175000017500000001647113626052637016435 0ustar rogerroger#!/usr/bin/env python3 import mosq_test_helper import ptest tests = [ #(ports required, 'path'), (1, './01-connect-anon-denied.py'), (1, './01-connect-bad-packet.py'), (1, './01-connect-disconnect-v5.py'), (1, './01-connect-duplicate-v5.py'), (1, './01-connect-duplicate.py'), (1, './01-connect-invalid-id-0-311.py'), (1, './01-connect-invalid-id-0.py'), (1, './01-connect-invalid-id-missing.py'), (1, './01-connect-invalid-id-utf8.py'), (1, './01-connect-invalid-protonum.py'), (1, './01-connect-invalid-reserved.py'), (1, './01-connect-success-v5.py'), (1, './01-connect-success.py'), (1, './01-connect-uname-invalid-utf8.py'), (1, './01-connect-uname-no-flag.py'), (1, './01-connect-uname-no-password-denied.py'), (1, './01-connect-uname-password-denied-no-will.py'), (1, './01-connect-uname-password-denied.py'), (1, './01-connect-uname-password-success.py'), (1, './01-connect-uname-pwd-no-flag.py'), (2, './01-connect-zero-length-id.py'), (1, './02-shared-qos0-v5.py'), (1, './02-subhier-crash.py'), (1, './02-subpub-qos0-long-topic.py'), (1, './02-subpub-qos0-retain-as-publish.py'), (1, './02-subpub-qos0-send-retain.py'), (1, './02-subpub-qos0-subscription-id.py'), (1, './02-subpub-qos0-topic-alias-unknown.py'), (1, './02-subpub-qos0-topic-alias.py'), (1, './02-subpub-qos0-v5.py'), (1, './02-subpub-qos0.py'), (1, './02-subpub-qos1-bad-pubcomp.py'), (1, './02-subpub-qos1-bad-pubrec.py'), (1, './02-subpub-qos1-message-expiry-retain.py'), (1, './02-subpub-qos1-message-expiry-will.py'), (1, './02-subpub-qos1-message-expiry.py'), (1, './02-subpub-qos1-nolocal.py'), (1, './02-subpub-qos1-v5.py'), (1, './02-subpub-qos1.py'), (1, './02-subpub-qos2-1322.py'), (1, './02-subpub-qos2-bad-puback-1.py'), (1, './02-subpub-qos2-bad-puback-2.py'), (1, './02-subpub-qos2-bad-pubcomp.py'), (1, './02-subpub-qos2-pubrec-error.py'), (1, './02-subpub-qos2-receive-maximum-1.py'), (1, './02-subpub-qos2-receive-maximum-2.py'), (1, './02-subpub-qos2-v5.py'), (1, './02-subpub-qos2.py'), (1, './02-subscribe-dollar-v5.py'), (1, './02-subscribe-invalid-utf8.py'), (1, './02-subscribe-long-topic.py'), (1, './02-subscribe-persistence-flipflop.py'), (1, './02-subscribe-qos0.py'), (1, './02-subscribe-qos1.py'), (1, './02-subscribe-qos2.py'), (1, './02-unsubscribe-invalid-no-topic.py'), (1, './02-unsubscribe-qos0.py'), (1, './02-unsubscribe-qos1.py'), (1, './02-unsubscribe-qos2-multiple-v5.py'), (1, './02-unsubscribe-qos2-multiple.py'), (1, './02-unsubscribe-qos2-v5.py'), (1, './02-unsubscribe-qos2.py'), #(1, './03-publish-qos1-queued-bytes.py'), (1, './03-pattern-matching.py'), (1, './03-publish-b2c-disconnect-qos1.py'), (1, './03-publish-b2c-disconnect-qos2.py'), (1, './03-publish-b2c-qos1-len.py'), (1, './03-publish-b2c-qos2-len.py'), (1, './03-publish-c2b-disconnect-qos2.py'), (1, './03-publish-c2b-qos2-len.py'), (1, './03-publish-dollar-v5.py'), (1, './03-publish-dollar.py'), (1, './03-publish-invalid-utf8.py'), (1, './03-publish-long-topic.py'), (1, './03-publish-qos1-no-subscribers-v5.py'), (1, './03-publish-qos1-retain-disabled.py'), (1, './03-publish-qos1.py'), (1, './03-publish-qos2-max-inflight.py'), (1, './03-publish-qos2.py'), (1, './04-retain-check-source-persist.py'), (1, './04-retain-check-source.py'), (1, './04-retain-qos0-clear.py'), (1, './04-retain-qos0-fresh.py'), (1, './04-retain-qos0-repeated.py'), (1, './04-retain-qos0.py'), (1, './04-retain-qos1-qos0.py'), (1, './04-retain-upgrade-outgoing-qos.py'), (2, './04-retain-check-source-persist-diff-port.py'), (1, './05-clean-session-qos1.py'), (1, './05-session-expiry-v5.py'), (2, './06-bridge-b2br-disconnect-qos1.py'), (2, './06-bridge-b2br-disconnect-qos2.py'), (2, './06-bridge-b2br-late-connection-retain.py'), (2, './06-bridge-b2br-late-connection.py'), (2, './06-bridge-b2br-remapping.py'), (2, './06-bridge-br2b-disconnect-qos1.py'), (2, './06-bridge-br2b-disconnect-qos2.py'), (2, './06-bridge-br2b-remapping.py'), (2, './06-bridge-fail-persist-resend-qos1.py'), (2, './06-bridge-fail-persist-resend-qos2.py'), (1, './06-bridge-no-local.py'), (3, './06-bridge-per-listener-settings.py'), (2, './06-bridge-reconnect-local-out.py'), (1, './07-will-delay-reconnect.py'), (1, './07-will-delay-recover.py'), (1, './07-will-delay-session-expiry.py'), (1, './07-will-delay-session-expiry2.py'), (1, './07-will-delay.py'), (1, './07-will-disconnect-with-will.py'), (1, './07-will-invalid-utf8.py'), (1, './07-will-no-flag.py'), (1, './07-will-null-topic.py'), (1, './07-will-null.py'), (1, './07-will-properties.py'), (1, './07-will-qos0.py'), (1, './07-will-reconnect-1273.py'), (2, './08-ssl-bridge.py'), (2, './08-ssl-connect-cert-auth-crl.py'), (2, './08-ssl-connect-cert-auth-expired.py'), (2, './08-ssl-connect-cert-auth-revoked.py'), (2, './08-ssl-connect-cert-auth-without.py'), (2, './08-ssl-connect-cert-auth.py'), (2, './08-ssl-connect-identity.py'), (2, './08-ssl-connect-no-auth-wrong-ca.py'), (2, './08-ssl-connect-no-auth.py'), (2, './08-ssl-connect-no-identity.py'), (1, './08-ssl-hup-disconnect.py'), (2, './08-tls-psk-pub.py'), (3, './08-tls-psk-bridge.py'), (1, './09-acl-access-variants.py'), (1, './09-acl-change.py'), (1, './09-acl-empty-file.py'), (1, './09-auth-bad-method.py'), (1, './09-extended-auth-change-username.py'), (1, './09-extended-auth-multistep-reauth.py'), (1, './09-extended-auth-multistep.py'), (1, './09-extended-auth-single.py'), (1, './09-extended-auth-unsupported.py'), (1, './09-plugin-auth-acl-pub.py'), (1, './09-plugin-auth-acl-sub-denied.py'), (1, './09-plugin-auth-acl-sub.py'), (1, './09-plugin-auth-context-params.py'), (1, './09-plugin-auth-defer-unpwd-fail.py'), (1, './09-plugin-auth-defer-unpwd-success.py'), (1, './09-plugin-auth-msg-params.py'), (1, './09-plugin-auth-unpwd-fail.py'), (1, './09-plugin-auth-unpwd-success.py'), (1, './09-plugin-auth-v2-unpwd-fail.py'), (1, './09-plugin-auth-v2-unpwd-success.py'), (1, './09-pwfile-parse-invalid.py'), (2, './10-listener-mount-point.py'), (1, './11-message-expiry.py'), (1, './11-persistent-subscription.py'), (1, './11-persistent-subscription-v5.py'), (1, './11-persistent-subscription-no-local.py'), (1, './11-pub-props.py'), (1, './11-subscription-id.py'), (1, './12-prop-assigned-client-identifier.py'), (1, './12-prop-maximum-packet-size-broker.py'), (1, './12-prop-maximum-packet-size-connect.py'), (1, './12-prop-maximum-packet-size-publish-qos1.py'), (1, './12-prop-maximum-packet-size-publish-qos2.py'), (1, './12-prop-maximum-packet-size-publish.py'), (1, './12-prop-response-topic-correlation-data.py'), (1, './12-prop-response-topic.py'), (1, './12-prop-server-keepalive.py'), (1, './12-prop-session-expiry-invalid.py'), (1, './12-prop-subpub-content-type.py'), (1, './12-prop-subpub-payload-format.py'), (1, './12-prop-topic-alias-invalid.py'), ] ptest.run_tests(tests) mosquitto-1.6.9/test/broker/02-unsubscribe-qos2-multiple.py0000775000175000017500000000161213626052637022723 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to multiple topics with QoS 2 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) unsubscribe_packet = mosq_test.gen_unsubscribe_multiple(mid, ["qos2/one", "qos2/two"]) unsuback_packet = mosq_test.gen_unsuback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-unpwd-fail.py0000775000175000017500000000207713626052637022202 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is successful with correct username and password # when using a simple auth_plugin. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="test-username", password="wrong") connack_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-pwd-no-flag.py0000775000175000017500000000151413626052637022531 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is disconnected if it provides a password but the # password flag is 0. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-test", keepalive=keepalive, username="user", password="pw") b = list(struct.unpack("B"*len(connect_packet), connect_packet)) b[9] = 66 # Remove password flag connect_packet = struct.pack("B"*len(b), *b) connack_packet = mosq_test.gen_connack(rc=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-success.py0000775000175000017500000000121313626052637020757 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-br2b-remapping.py0000775000175000017500000000740313626052637021735 0ustar rogerroger#!/usr/bin/env python3 # Test remapping of topic name for outgoing message from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("bridge_attempt_unsubscribe false\n") f.write("topic # out 0 local/topic/ remote/topic/\n") f.write("topic prefix/# out 0 local2/topic/ remote2/topic/\n") f.write("topic +/value out 0 local3/topic/ remote3/topic/\n") f.write("topic ic/+ out 0 local4/top remote4/tip\n") f.write("# this one is invalid\n") f.write("topic +/value out 0 local5/top remote5/tip\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive) client_connack_packet = mosq_test.gen_connack(rc=0) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(4) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) def test(bridge, sock): if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) cases = [ ('local/topic/something', 'remote/topic/something'), ('local/topic/some/t/h/i/n/g', 'remote/topic/some/t/h/i/n/g'), ('local/topic/value', 'remote/topic/value'), # Don't work, #40 must be fixed before # ('local/topic', 'remote/topic'), ('local2/topic/something', None), # don't match topic pattern ('local2/topic/prefix/something', 'remote2/topic/prefix/something'), ('local3/topic/something/value', 'remote3/topic/something/value'), ('local4/topic/something', 'remote4/tipic/something'), ('local5/topic/something', None), ] mid = 3 for (local_topic, remote_topic) in cases: mid += 1 local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='' ) sock.send(local_publish_packet) if remote_topic: remote_publish_packet = mosq_test.gen_publish( remote_topic, qos=0, mid=mid, payload='' ) match = mosq_test.expect_packet(bridge, "publish", remote_publish_packet) if not match: print("Fail on cases local_topic=%r, remote_topic=%r" % ( local_topic, remote_topic, )) return 1 else: time.sleep(1) mosq_test.do_ping(bridge, "FAIL: Received data when nothing is expected\nFail on cases local_topic=%r, remote_topic=%r" % ( local_topic, remote_topic, )) return 0 try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = test(bridge, sock) sock.close() bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos0-topic-alias.py0000775000175000017500000000333213626052637022250 0ustar rogerroger#!/usr/bin/env python3 # Test whether "topic alias" works to the broker # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 connect1_packet = mosq_test.gen_connect("sub-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/alias", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS, 3) publish1_packet = mosq_test.gen_publish("subpub/alias", qos=0, payload="message", proto_ver=5, properties=props) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS, 3) publish2s_packet = mosq_test.gen_publish("", qos=0, payload="message", proto_ver=5, properties=props) publish2r_packet = mosq_test.gen_publish("subpub/alias", qos=0, payload="message", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=5, port=port) sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=5, port=port) sock1.send(publish1_packet) mosq_test.do_send_receive(sock2, subscribe_packet, suback_packet, "suback") sock1.send(publish2s_packet) if mosq_test.expect_packet(sock2, "publish2r", publish2r_packet): rc = 0 sock1.close() sock2.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/readme.txt0000664000175000017500000000063013626052637017065 0ustar rogerroger----- Broker Tests ----- This folder contains a number of tests to exercise the functionality of the broker. Feel free to add more. Numbering is as follows: 01: Connection tests 02: Subscribe/unsubscribe tests 03: Publish tests 04: Retained message tests 05: Session management tests 06: Bridge tests 07: Will tests 08: TLS tests 09: Auth tests 10: Listener tests 11: Persistence tests 12: Property tests mosquitto-1.6.9/test/broker/04-retain-check-source-persist-diff-port.py0000775000175000017500000000762313626052637025110 0ustar rogerroger#!/usr/bin/env python3 # Test for CVE-2018-12546, with the broker being stopped to write the persistence file, plus subscriber on different port. from mosq_test_helper import * import os.path import signal def write_config(filename, port1, port2, per_listener): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener)) f.write("check_retain_source true\n") f.write("port %d\n" % (port1)) f.write("acl_file %s\n" % (filename.replace('.conf', '.acl'))) f.write("persistence true\n") f.write("persistence_file %s\n" % (filename.replace('.conf', '.db'))) f.write("listener %d\n" % (port2)) def write_acl_1(filename, username): with open(filename, 'w') as f: if username is not None: f.write('user %s\n' % (username)) f.write('topic readwrite test/topic\n') def write_acl_2(filename, username): with open(filename, 'w') as f: if username is not None: f.write('user %s\n' % (username)) f.write('topic read test/topic\n') def do_test(per_listener, username): conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, per_listener) persistence_file = os.path.basename(__file__).replace('.py', '.db') try: os.remove(persistence_file) except OSError: pass acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl_1(acl_file, username) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-check", keepalive=keepalive, username=username) connack_packet = mosq_test.gen_connack(rc=0) if per_listener == "true": u = None else: # If per listener is false, then the second client will be denied # unless we provide a username u = username connect2_packet = mosq_test.gen_connect("retain-recv", keepalive=keepalive, username=u) connack2_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="retained message", retain=True) subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0) suback_packet = mosq_test.gen_suback(mid, 0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port1) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port1) sock.send(publish_packet) sock.close() sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, port=port2) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 1") if mosq_test.expect_packet(sock, "publish", publish_packet): sock.close() # Remove "write" ability write_acl_2(acl_file, username) broker.terminate() broker.wait() if os.path.isfile(persistence_file) == False: raise FileNotFoundError("Persistence file not written") broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port1) sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, port=port2) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 2") # If we receive the retained message here, it is a failure. mosq_test.do_ping(sock) rc = 0 sock.close() finally: broker.terminate() broker.wait() os.remove(conf_file) os.remove(acl_file) try: os.remove(persistence_file) except FileNotFoundError: pass (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) (port1, port2) = mosq_test.get_port(2) do_test("true", username=None) do_test("true", username="test") do_test("false", username=None) do_test("false", username="test") mosquitto-1.6.9/test/broker/03-publish-b2c-disconnect-qos1-helper.py0000775000175000017500000000114613626052637024266 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test.gen_publish("qos1/disconnect/test", qos=1, mid=mid, payload="disconnect-message") puback_packet = mosq_test.gen_puback(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack", port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "helper puback") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/07-will-properties.py0000775000175000017500000001106713626052637021037 0ustar rogerroger#!/usr/bin/env python3 # Test for bug #1244. This occurs if a V5 will message is used where the first # Will property is one of: content-type, payload-format-indicator, # response-topic. These are the properties that are attached to the will for # later use, as opposed to e.g. will-delay-interval which is a value which is # read immediately and not passed from mosq_test_helper import * def do_test(will_props, recvd_props): rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe1_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) connect2_packet = mosq_test.gen_connect("will-test", keepalive=keepalive, proto_ver=5, will_topic="will/test", will_payload=b"will payload", will_properties=will_props) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/test", qos=0, payload="will payload", proto_ver=5, properties=recvd_props) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port) mosq_test.do_send_receive(sock1, subscribe1_packet, suback1_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=30, port=port) sock2.close() if mosq_test.expect_packet(sock1, "publish", publish_packet): rc = 0 sock1.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) # Single test property will_props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") #do_test(will_props, will_props) # Multiple test properties will_props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 0) #do_test(will_props, will_props) # Multiple test properties, with property that is removed will_props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 0) will_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 0) recv_props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") recv_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 0) #do_test(will_props, recv_props) # Multiple test properties, with property that is removed *first* will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 0) will_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "data") recv_props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") recv_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "data") #do_test(will_props, recv_props) # All properties, plus multiple user properties (excluding # message-expiry-interval, for ease of testing reasons) will_props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key1", "value1") will_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "data") will_props += mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 0) will_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 1) will_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "application/test") will_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key2", "value2") recv_props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key1", "value1") recv_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, "response/topic") recv_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "data") recv_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 1) recv_props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CONTENT_TYPE, "application/test") recv_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key2", "value2") do_test(will_props, recv_props) mosquitto-1.6.9/test/broker/01-connect-uname-no-flag.py0000775000175000017500000000147413626052637021746 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is disconnected if it provides a username but the # username flag is 0. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-test", keepalive=keepalive, username="user") b = list(struct.unpack("B"*len(connect_packet), connect_packet)) b[9] = 2 # Remove username flag connect_packet = struct.pack("B"*len(b), *b) connack_packet = mosq_test.gen_connack(rc=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/08-tls-psk-pub.psk0000664000175000017500000000002013626052637020205 0ustar rogerrogerpsk-id:deadbeef mosquitto-1.6.9/test/broker/07-will-no-flag.py0000775000175000017500000000162713626052637020167 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is disconnected if it sets the will flag but does # not provide a will payload. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("will-no-payload", keepalive=keepalive, will_topic="will/topic", will_qos=1, will_retain=True) b = list(struct.unpack("B"*len(connect_packet), connect_packet)) bmod = b[0:len(b)-2] bmod[1] = bmod[1] - 2 # Reduce remaining length by two to remove final two payload length values connect_packet = struct.pack("B"*len(bmod), *bmod) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/04-retain-qos0-fresh.py0000775000175000017500000000225713626052637021143 0ustar rogerroger#!/usr/bin/env python3 # Test whether a retained PUBLISH to a topic with QoS 0 is sent with # retain=false to an already subscribed client. from mosq_test_helper import * rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-fresh-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True) publish_fresh_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message") subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, publish_fresh_packet, "publish") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-qos2.py0000775000175000017500000000202413626052637020213 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 312 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/prop_subpub_helper.py0000775000175000017500000000267013626052637021351 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # Does a given property get sent through? # MQTT v5 from mosq_test_helper import * def prop_subpub_helper(props_out, props_in): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos0", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet_out = mosq_test.gen_publish("subpub/qos0", qos=0, payload="message", proto_ver=5, properties=props_out) publish_packet_expected = mosq_test.gen_publish("subpub/qos0", qos=0, payload="message", proto_ver=5, properties=props_in) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet_out, publish_packet_expected, "publish") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-anon-denied.pwfile0000664000175000017500000000016213626052637022325 0ustar rogerrogeruser:$6$kyuI0x+unN8lbv9U$b6c3O8U/3fCJLEg7/qDHnE9oOE6gu8JqwBXNLAPBQInJuHhpB3teOaSxb3Lx9O+ukglIRPOI0NCENcincSPCvQ== mosquitto-1.6.9/test/broker/02-subpub-qos1-message-expiry.py0000775000175000017500000000547313626052637023016 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker reduces the message expiry interval when republishing. # MQTT v5 # Client connects with clean session set false, subscribes with qos=1, then disconnects # Helper publishes two messages, one with a short expiry and one with a long expiry # We wait until the short expiry will have expired but the long one not. # Client reconnects, expects delivery of the long expiry message with a reduced # expiry interval property. from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=5, clean_session=False, properties=props) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5, flags=1) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) helper_connect = mosq_test.gen_connect("helper", proto_ver=5) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=5) mid=1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 1) publish1s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message1", proto_ver=5, properties=props) puback1s_packet = mosq_test.gen_puback(mid) mid=2 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 10) publish2s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message2", proto_ver=5, properties=props) puback2s_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack1_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.close() helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, puback1s_packet, "puback 1") mosq_test.do_send_receive(helper, publish2s_packet, puback2s_packet, "puback 2") time.sleep(2) sock = mosq_test.do_client_connect(connect_packet, connack2_packet, timeout=20, port=port) packet = sock.recv(len(publish2s_packet)) for i in range(9, 5, -1): props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, i) publish2r_packet = mosq_test.gen_publish("subpub/qos1", mid=2, qos=1, payload="message2", proto_ver=5, properties=props) if packet == publish2r_packet: rc = 0 break sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/05-clean-session-qos1.py0000775000175000017500000000315113626052637021313 0ustar rogerroger#!/usr/bin/env python3 # Test whether a clean session client has a QoS 1 message queued for it. from mosq_test_helper import * rc = 1 mid = 109 keepalive = 60 connect_packet = mosq_test.gen_connect("clean-qos2-test", keepalive=keepalive, clean_session=False) connack1_packet = mosq_test.gen_connack(flags=0, rc=0) connack2_packet = mosq_test.gen_connack(flags=1, rc=0) disconnect_packet = mosq_test.gen_disconnect() subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/clean_session/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 1 publish_packet = mosq_test.gen_publish("qos1/clean_session/test", qos=1, mid=mid, payload="clean-session-message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack1_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.send(disconnect_packet) sock.close() pub = subprocess.Popen(['./05-clean-session-qos1-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Now reconnect and expect a publish message. sock = mosq_test.do_client_connect(connect_packet, connack2_packet, timeout=30, port=port) if mosq_test.expect_packet(sock, "publish", publish_packet): sock.send(puback_packet) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/11-subscription-id.py0000775000175000017500000000566013626052637021011 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client message maintains its subscription id when persisted and restored. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 100) connect_packet = mosq_test.gen_connect( "persistent-subscription-test", keepalive=keepalive, clean_session=False, proto_ver=5, properties=props ) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=5) # session present mid = 1 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 53) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=5, properties=props) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 1 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 53) publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5, properties=props) helper_connect_packet = mosq_test.gen_connect("helper", keepalive=keepalive, clean_session=True, proto_ver=5) helper_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 helper_publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) helper_puback_packet = mosq_test.gen_puback(mid, proto_ver=5) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) (stdo1, stde1) = ("", "") try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.close() sock = mosq_test.do_client_connect(helper_connect_packet, helper_connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, helper_publish_packet, helper_puback_packet, "helper puback") sock.close() broker.terminate() broker.wait() (stdo1, stde1) = broker.communicate() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=20, port=port) if mosq_test.expect_packet(sock, "publish2", publish_packet2): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) pass exit(rc) mosquitto-1.6.9/test/broker/09-extended-auth-multistep.py0000775000175000017500000000356613626052637022470 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_extended_multiple.so\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "step1") connect_packet = mosq_test.gen_connect("client-params-test", keepalive=42, proto_ver=5, properties=props) # Server to client props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "1pets") auth1_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_CONTINUE_AUTHENTICATION, properties=props) # Client to server props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "supercalifragilisticexpialidocious") auth2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, auth1_packet, timeout=20, port=port, connack_error="auth1") mosq_test.do_send_receive(sock, auth2_packet, connack_packet) rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-qos1-no-subscribers-v5.py0000775000175000017500000000570113626052637023505 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 1 results in the correct PUBACK # packet when there are no subscribers. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 publish1_packet = mosq_test.gen_publish("pub", qos=1, mid=mid, payload="message", proto_ver=5) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid = 2 publish2_packet = mosq_test.gen_publish("pub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) puback2_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid = 3 publish3_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=5) puback3_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid = 4 publish4_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=5, retain=True) puback4_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid = 5 publish1b_packet = mosq_test.gen_publish("pub", qos=1, mid=mid, payload="message", proto_ver=5) puback1b_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid = 6 publish2b_packet = mosq_test.gen_publish("pub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) puback2b_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid = 7 publish3b_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=5) puback3b_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) # None of the pub/qos1/test topic tree exists here mosq_test.do_send_receive(sock, publish1_packet, puback1_packet, "puback1a") mosq_test.do_send_receive(sock, publish2_packet, puback2_packet, "puback2a") mosq_test.do_send_receive(sock, publish3_packet, puback3_packet, "puback3a") # This publish sets a retained message, which means the topic tree exists mosq_test.do_send_receive(sock, publish4_packet, puback4_packet, "puback4") # So now test again mosq_test.do_send_receive(sock, publish1b_packet, puback1b_packet, "puback1b") mosq_test.do_send_receive(sock, publish2b_packet, puback2b_packet, "puback2b") mosq_test.do_send_receive(sock, publish3b_packet, puback3b_packet, "puback3b") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-extended-auth-multistep-reauth.py0000775000175000017500000000741413626052637023752 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_extended_multiple.so\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 # First auth # ========== props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "step1") connect1_packet = mosq_test.gen_connect("client-params-test", keepalive=42, proto_ver=5, properties=props) # Server to client props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "1pets") auth1_1_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_CONTINUE_AUTHENTICATION, properties=props) # Client to server props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "supercalifragilisticexpialidocious") auth1_2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) # Second auth # =========== props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "step1") reauth2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_REAUTHENTICATE, properties=props) # Server to client props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "1pets") auth2_1_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_CONTINUE_AUTHENTICATION, properties=props) # Client to server props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "supercalifragilisticexpialidocious") auth2_2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "mirror") auth2_3_packet = mosq_test.gen_auth(reason_code=0, properties=props) # Third auth - bad due to different method # ======================================== props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_METHOD, "badmethod") props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_AUTHENTICATION_DATA, "step1") reauth3_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.MQTT_RC_REAUTHENTICATE, properties=props) # Server to client disconnect3_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.MQTT_RC_PROTOCOL_ERROR, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect1_packet, auth1_1_packet, timeout=20, port=port, connack_error="auth1") mosq_test.do_send_receive(sock, auth1_2_packet, connack1_packet, "connack1") mosq_test.do_ping(sock, "pingresp1") mosq_test.do_send_receive(sock, reauth2_packet, auth2_1_packet, "auth2_1") mosq_test.do_send_receive(sock, auth2_2_packet, auth2_3_packet, "auth2_3") mosq_test.do_ping(sock, "pingresp2") mosq_test.do_send_receive(sock, reauth3_packet, disconnect3_packet, "disconnect3") rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/09-plugin-auth-msg-params.py0000775000175000017500000000320213626052637022172 0ustar rogerroger#!/usr/bin/env python3 # Test whether message parameters are passed to the plugin acl check function. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_msg_params.so\n") f.write("allow_anonymous true\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("msg-param-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "param/topic", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 3 publish_packet = mosq_test.gen_publish(topic="param/topic", qos=1, payload="payload contents", retain=1, mid=mid) puback_packet = mosq_test.gen_puback(mid) mid = 1 publish_packet_recv = mosq_test.gen_publish(topic="param/topic", qos=1, payload="payload contents", retain=0, mid=mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") if mosq_test.expect_packet(sock, "publish receive", publish_packet_recv): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-disconnect-v5.py0000775000175000017500000000420613626052637021775 0ustar rogerroger#!/usr/bin/env python3 # loop through the different v5 DISCONNECT reason_code/properties options. from mosq_test_helper import * def disco_test(test, disconnect_packet): global rc sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, port=port) mosq_test.do_send_receive(sock1, subscribe1_packet, suback1_packet, "suback1") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, port=port) sock2.send(disconnect_packet) sock2.close() # If this fails then we probably received the will mosq_test.do_ping(sock1) rc -= 1 rc = 4 keepalive = 10 connect1_packet = mosq_test.gen_connect("sub", proto_ver=5, keepalive=keepalive) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) connect2_packet = mosq_test.gen_connect("connect-disconnect-test", proto_ver=5, keepalive=keepalive, will_topic="failure", will_payload=b"failure") connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # No reason code, no properties, len=0 disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) disco_test("disco len=0", disconnect_packet) # Reason code, no properties, len=1 disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=0) disco_test("disco len=1", disconnect_packet) # Reason code, empty properties, len=2 disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=0, properties="") disco_test("disco len=2", disconnect_packet) # Reason code, one property, len>2 props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=0, properties=props) disco_test("disco len>2", disconnect_packet) finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if rc != 0: print(test) exit(rc) mosquitto-1.6.9/test/broker/12-prop-session-expiry-invalid.py0000775000175000017500000000225613626052637023275 0ustar rogerroger#!/usr/bin/env python3 # Test whether sending a non zero session expiry interval in DISCONNECT after # having sent a zero session expiry interval is treated correctly in MQTT v5. from mosq_test_helper import * rc = 1 keepalive = 10 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 1) disconnect_client_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) disconnect_server_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=130) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, disconnect_client_packet, disconnect_server_packet, "disconnect") sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-invalid-protonum.py0000775000175000017500000000126313626052637022623 0ustar rogerroger#!/usr/bin/env python3 # Test whether a CONNECT with an invalid protocol number results in the correct CONNACK packet. from mosq_test_helper import * rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-invalid-test", keepalive=keepalive, proto_ver=0) connack_packet = mosq_test.gen_connack(rc=1) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-pubrec-error-helper.py0000775000175000017500000000227613626052637023737 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_1_packet = mosq_test.gen_publish("qos2/pubrec/rejected", qos=2, mid=mid, payload="rejected-message") pubrec_1_packet = mosq_test.gen_pubrec(mid) pubrel_1_packet = mosq_test.gen_pubrel(mid) pubcomp_1_packet = mosq_test.gen_pubcomp(mid) mid = 2 publish_2_packet = mosq_test.gen_publish("qos2/pubrec/accepted", qos=2, mid=mid, payload="accepted-message") pubrec_2_packet = mosq_test.gen_pubrec(mid) pubrel_2_packet = mosq_test.gen_pubrel(mid) pubcomp_2_packet = mosq_test.gen_pubcomp(mid) port = mosq_test.get_port() sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack", port=port) mosq_test.do_send_receive(sock, publish_1_packet, pubrec_1_packet, "helper pubrec") mosq_test.do_send_receive(sock, pubrel_1_packet, pubcomp_1_packet, "helper pubcomp") mosq_test.do_send_receive(sock, publish_2_packet, pubrec_2_packet, "helper pubrec") mosq_test.do_send_receive(sock, pubrel_2_packet, pubcomp_2_packet, "helper pubcomp") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-qos1-len-helper.py0000775000175000017500000000112513626052637022710 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("qos1/len/test", qos=1, mid=mid, payload="len-message") puback_packet = mosq_test.gen_puback(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, connack_error="helper connack", port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "helper puback") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos2-receive-maximum-2.py0000775000175000017500000000513113626052637023300 0ustar rogerroger#!/usr/bin/env python3 # Does the broker respect receive maximum==2? # MQTT v5 from mosq_test_helper import * rc = 1 keepalive = 60 props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 2) connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 1 publish_packet1 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message1", proto_ver=5) pubrec_packet1 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet1 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet1 = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 2 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message2", proto_ver=5) pubrec_packet2 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet2 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet2 = mosq_test.gen_pubcomp(mid, proto_ver=5) mid = 3 publish_packet3 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message3", proto_ver=5) pubrec_packet3 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet3 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet3 = mosq_test.gen_pubcomp(mid, proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./02-subpub-qos2-receive-maximum-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() if mosq_test.expect_packet(sock, "publish1", publish_packet1): if mosq_test.expect_packet(sock, "publish2", publish_packet2): mosq_test.do_send_receive(sock, pubrec_packet1, pubrel_packet1, "pubrel1") sock.send(pubcomp_packet1) if mosq_test.expect_packet(sock, "publish3", publish_packet3): mosq_test.do_send_receive(sock, pubrec_packet2, pubrel_packet2, "pubrel2") sock.send(pubcomp_packet2) mosq_test.do_send_receive(sock, pubrec_packet3, pubrel_packet3, "pubrel3") sock.send(pubcomp_packet3) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-delay.py0000775000175000017500000000353513626052637017742 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client will is transmitted with a delay correctly. # MQTT 5 from mosq_test_helper import * def do_test(clean_session): rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_WILL_DELAY_INTERVAL, 3) connect2_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, will_topic="will/test", will_payload=b"will delay", will_qos=2, will_properties=props, clean_session=clean_session) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=30, port=port) sock2.close() t_start = time.time() if mosq_test.expect_packet(sock1, "publish", publish_packet): t_finish = time.time() if t_finish - t_start > 2 and t_finish - t_start < 5: rc = 0 sock1.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(clean_session=True) do_test(clean_session=False) mosquitto-1.6.9/test/broker/07-will-reconnect-1273.py0000775000175000017500000000534513626052637021217 0ustar rogerroger#!/usr/bin/env python3 # Test whether a persistent client that disconnects with DISCONNECT has its # will published when it reconnects. It shouldn't. Bug 1273: # https://github.com/eclipse/mosquitto/issues/1273 from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 60 connect1_packet = mosq_test.gen_connect("will-sub", keepalive=keepalive, proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=proto_ver) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) if proto_ver == 5: props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 100) else: props = None connect2_packet = mosq_test.gen_connect("will-1273", keepalive=keepalive, will_topic="will/test", will_payload=b"will msg",clean_session=False, proto_ver=proto_ver, properties=props) connack2a_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack2b_packet = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) disconnect_packet = mosq_test.gen_disconnect(proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("will/test", qos=0, payload="alive", proto_ver=proto_ver) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # Connect and subscribe will-sub sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port, connack_error="connack1") mosq_test.do_send_receive(sock1, subscribe1_packet, suback1_packet, "suback") # Connect will-1273 sock2 = mosq_test.do_client_connect(connect2_packet, connack2a_packet, timeout=30, port=port) # Publish our "alive" message sock2.send(publish_packet) # Clean disconnect sock2.send(disconnect_packet) # will-1273 should get the "alive" mosq_test.expect_packet(sock1, "publish1", publish_packet) sock2.close() # Reconnect sock2 = mosq_test.do_client_connect(connect2_packet, connack2b_packet, timeout=30, port=port, connack_error="connack2") # will-1273 to publish "alive" again, and will-sub to receive it. sock2.send(publish_packet) mosq_test.expect_packet(sock1, "publish2", publish_packet) # Do a ping to make sure there are no other packets received. mosq_test.do_ping(sock1) rc = 0 sock1.close() sock2.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) exit(0) mosquitto-1.6.9/test/broker/08-ssl-bridge-helper.py0000775000175000017500000000104413626052637021201 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("bridge/ssl/test", qos=0, payload="message") disconnect_packet = mosq_test.gen_disconnect() sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="helper connack") sock.send(publish_packet) sock.send(disconnect_packet) sock.close() exit(0) mosquitto-1.6.9/test/broker/02-subpub-qos1-v5.py0000775000175000017500000000254013626052637020376 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. # MQTT v5 from mosq_test_helper import * rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) puback_packet = mosq_test.gen_puback(mid, proto_ver=5) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") if mosq_test.expect_packet(sock, "publish2", publish_packet2): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-long-topic.py0000775000175000017500000000172313626052637021407 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with 65535 hierarchy characters fails # This needs checking with MOSQ_USE_VALGRIND=1 to detect memory failures # https://github.com/eclipse/mosquitto/issues/1412 from mosq_test_helper import * rc = 1 mid = 19 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("/"*65535, qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, b"", "puback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos1-message-expiry-retain.py0000775000175000017500000000672313626052637024275 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker reduces the message expiry interval when republishing # a retained message, and eventually removes it. # MQTT v5 # Helper publishes a message, with a medium length expiry with retained set. It # publishes a second message with retained set but no expiry. # Client connects, subscribes, gets messages, disconnects. # We wait until the expiry will have expired. # Client connects, subscribes, doesn't get expired message, does get # non-expired message. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "subpub/expired", 1, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/kept", 1, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) helper_connect = mosq_test.gen_connect("helper", proto_ver=5) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=5) mid=1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 4) publish1_packet = mosq_test.gen_publish("subpub/expired", mid=mid, qos=1, retain=True, payload="message1", proto_ver=5, properties=props) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid=2 publish2s_packet = mosq_test.gen_publish("subpub/kept", mid=mid, qos=1, retain=True, payload="message2", proto_ver=5) puback2s_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) mid=1 publish2r_packet = mosq_test.gen_publish("subpub/kept", mid=mid, qos=1, retain=True, payload="message2", proto_ver=5) puback2r_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1_packet, puback1_packet, "puback 1") mosq_test.do_send_receive(helper, publish2s_packet, puback2s_packet, "puback 2") helper.close() sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback 1-1") if mosq_test.expect_packet(sock, "publish 1", publish1_packet): sock.send(puback1_packet) mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback 2-1") if mosq_test.expect_packet(sock, "publish 2", publish2s_packet): sock.send(puback2s_packet) sock.close() time.sleep(5) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback 1-2") # We shouldn't receive a publish here # This will fail if we do receive a publish mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback 2-2") if mosq_test.expect_packet(sock, "publish 2", publish2r_packet): sock.send(puback2r_packet) sock.close() rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-null.py0000775000175000017500000000224513626052637017613 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client will is transmitted correctly with a null character in the middle. from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "will/null/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish("will/null/test", qos=0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=30, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") will = subprocess.Popen(['./07-will-null-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) will.wait() (stdo, stde) = will.communicate() if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-c2b-timeout-qos2.py0000775000175000017500000000240313626052637022344 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet # flow. This test introduces delays into the flow in order to force the broker # to send duplicate PUBREC and PUBCOMP messages. from mosq_test_helper import * rc = 1 keepalive = 600 connect_packet = mosq_test.gen_connect("pub-qos2-timeout-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1926 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="timeout-message") pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__)) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") # Timeout is 8 seconds which means the broker should repeat the PUBREC. if mosq_test.expect_packet(sock, "pubrec", pubrec_packet): mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-bad-packet.py0000775000175000017500000000162013626052637021304 0ustar rogerroger#!/usr/bin/env python3 # Test whether a first packet of non-CONNECT is rejected. from mosq_test_helper import * rc = 1 mid = 2 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect(("localhost", port)) sock.send(publish_packet) data = sock.recv(1) sock.close() if len(data) == 0: rc = 0 except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/11-persistent-subscription.py0000775000175000017500000000430013626052637022603 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client subscribed to a topic receives its own message sent to that topic. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect( "persistent-subscription-test", keepalive=keepalive, clean_session=False, ) connack_packet = mosq_test.gen_connack(rc=0) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1) # session present subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) (stdo1, stde1) = ("", "") try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") broker.terminate() broker.wait() (stdo1, stde1) = broker.communicate() sock.close() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=20, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") if mosq_test.expect_packet(sock, "publish2", publish_packet2): rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) exit(rc) mosquitto-1.6.9/test/broker/08-ssl-bridge.py0000775000175000017500000000450513626052637017731 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_test\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# both 0\n") f.write("notifications false\n") f.write("restart_timeout 2\n") f.write("\n") f.write("bridge_cafile ../ssl/all-ca.crt\n") f.write("bridge_insecure true\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_test" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish("bridge/ssl/test", qos=0, payload="message") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/all-ca.crt", keyfile="../ssl/server.key", certfile="../ssl/server.crt", server_side=True) ssock.settimeout(20) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): bridge.send(suback_packet) pub = subprocess.Popen(['./08-ssl-bridge-helper.py', str(port2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() if mosq_test.expect_packet(bridge, "publish", publish_packet): rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/02-unsubscribe-qos2-v5.py0000775000175000017500000000167113626052637021427 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 2 results in the correct SUBACK packet. # MQTT 5 from mosq_test_helper import * rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos2-test", keepalive=keepalive, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos2/test", proto_ver=5) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=5, reason_code=17) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-b2br-remapping.py0000775000175000017500000001021713626052637021732 0ustar rogerroger#!/usr/bin/env python3 # Test remapping of topic name for incoming message from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("bridge_attempt_unsubscribe false\n") f.write("topic # in 0 local/topic/ remote/topic/\n") f.write("topic prefix/# in 0 local2/topic/ remote2/topic/\n") f.write("topic +/value in 0 local3/topic/ remote3/topic/\n") f.write("topic ic/+ in 0 local4/top remote4/tip\n") f.write("topic clients/total in 0 test/mosquitto/org $SYS/broker/\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive) client_connack_packet = mosq_test.gen_connack(rc=0) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(4) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) def test(bridge, sock): if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) mid = 0 patterns = [ "remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value", "remote4/tipic/+", "$SYS/broker/clients/total", ] for pattern in ("remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value"): mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, pattern, 0) suback_packet = mosq_test.gen_suback(mid, 0) if not mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): return 1 bridge.send(suback_packet) mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) suback_packet = mosq_test.gen_suback(mid, 0) sock.send(subscribe_packet) if not mosq_test.expect_packet(sock, "suback", suback_packet): return 1 cases = [ ('local/topic/something', 'remote/topic/something'), ('local/topic/some/t/h/i/n/g', 'remote/topic/some/t/h/i/n/g'), ('local/topic/value', 'remote/topic/value'), # Don't work, #40 must be fixed before # ('local/topic', 'remote/topic'), ('local2/topic/prefix/something', 'remote2/topic/prefix/something'), ('local3/topic/something/value', 'remote3/topic/something/value'), ('local4/topic/something', 'remote4/tipic/something'), ('test/mosquitto/orgclients/total', '$SYS/broker/clients/total'), ] for (local_topic, remote_topic) in cases: mid += 1 remote_publish_packet = mosq_test.gen_publish( remote_topic, qos=0, mid=mid, payload='' ) local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='' ) bridge.send(remote_publish_packet) match = mosq_test.expect_packet(sock, "publish", local_publish_packet) if not match: print("Fail on cases local_topic=%r, remote_topic=%r" % ( local_topic, remote_topic, )) return 1 return 0 try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = test(bridge, sock) sock.close() bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/06-bridge-reconnect-local-out.py0000775000175000017500000000572413626052637023007 0ustar rogerroger#!/usr/bin/env python3 # Test whether a bridge topics work correctly after reconnection. # Important point here is that persistence is enabled. from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db" % (port1)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# out\n") (port1, port2) = mosq_test.get_port(2) conf_file = '06-bridge-reconnect-local-out.conf' write_config(conf_file, port1, port2) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-reconnect-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 180 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 0) suback_packet = mosq_test.gen_suback(mid, 0) publish_packet = mosq_test.gen_publish("bridge/reconnect", qos=0, payload="bridge-reconnect-message") try: os.remove('mosquitto-%d.db' % (port1)) except OSError: pass broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port1, use_conf=False) local_cmd = ['../../src/mosquitto', '-c', '06-bridge-reconnect-local-out.conf'] local_broker = mosq_test.start_broker(cmd=local_cmd, filename=os.path.basename(__file__)+'_local1', use_conf=False, port=port2) if os.environ.get('MOSQ_USE_VALGRIND') is not None: time.sleep(5) else: time.sleep(0.5) local_broker.terminate() local_broker.wait() if os.environ.get('MOSQ_USE_VALGRIND') is not None: time.sleep(5) else: time.sleep(0.5) local_broker = mosq_test.start_broker(cmd=local_cmd, filename=os.path.basename(__file__)+'_local2', port=port2) if os.environ.get('MOSQ_USE_VALGRIND') is not None: time.sleep(5) else: time.sleep(0.5) pub = None try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port1) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./06-bridge-reconnect-local-out-helper.py', str(port2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: os.remove(conf_file) time.sleep(1) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) local_broker.terminate() local_broker.wait() if rc: (stdo, stde) = local_broker.communicate() print(stde.decode('utf-8')) if pub: (stdo, stde) = pub.communicate() print(stdo.decode('utf-8')) try: os.remove('mosquitto-%d.db' % (port1)) except OSError: pass exit(rc) mosquitto-1.6.9/test/broker/02-subpub-qos1-bad-pubcomp.py0000775000175000017500000000376513626052637022247 0ustar rogerroger#!/usr/bin/env python3 # Test what the broker does if receiving a PUBCOMP in response to a QoS 1 PUBLISH. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") helper_connect = mosq_test.gen_connect("helper", keepalive=keepalive) helper_connack = mosq_test.gen_connack(rc=0) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") puback1s_packet = mosq_test.gen_puback(mid) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message") pubcomp1r_packet = mosq_test.gen_pubcomp(mid) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, puback1s_packet, "puback 1s") helper.close() if mosq_test.expect_packet(sock, "publish 1r", publish1r_packet): sock.send(pubcomp1r_packet) sock.send(pingreq_packet) p = sock.recv(len(pingresp_packet)) if len(p) == 0: rc = 0 sock.close() except socket.error as e: if e.errno == errno.ECONNRESET: # Connection has been closed by peer, this is the expected behaviour rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-br2b-disconnect-qos1-helper.py0000775000175000017500000000114713626052637024241 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message") puback_packet = mosq_test.gen_puback(mid) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="helper connack") mosq_test.do_send_receive(sock, publish_packet, puback_packet, "helper puback") rc = 0 sock.close() exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-qos2-len.py0000775000175000017500000000553213626052637021442 0ustar rogerroger#!/usr/bin/env python3 # Check whether the broker handles a v5 PUBREC, PUBCOMP with all combinations # of with/without reason code and properties. from mosq_test_helper import * def len_test(test, pubrec_packet, pubcomp_packet): port = mosq_test.get_port() rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/len/test", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("qos2/len/test", qos=2, mid=mid, payload="len-message", proto_ver=5) pubrel_packet = mosq_test.gen_pubrel(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-publish-b2c-qos2-len-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): mosq_test.do_send_receive(sock, pubrec_packet, pubrel_packet, "pubrel") sock.send(pubcomp_packet) mosq_test.do_ping(sock) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if rc != 0: print(test) exit(rc) # No reason code, no properties pubrec_packet = mosq_test.gen_pubrec(1) pubcomp_packet = mosq_test.gen_pubcomp(1) len_test("qos2 len 2", pubrec_packet, pubcomp_packet) # Reason code, no properties pubrec_packet = mosq_test.gen_pubrec(1, proto_ver=5, reason_code=0x00) pubcomp_packet = mosq_test.gen_pubcomp(1, proto_ver=5, reason_code=0x00) len_test("qos2 len 3", pubrec_packet, pubcomp_packet) # Reason code, empty properties pubrec_packet = mosq_test.gen_pubrec(1, proto_ver=5, reason_code=0x00, properties="") pubcomp_packet = mosq_test.gen_pubcomp(1, proto_ver=5, reason_code=0x00, properties="") len_test("qos2 len 4", pubrec_packet, pubcomp_packet) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") pubrec_packet = mosq_test.gen_pubrec(1, proto_ver=5, reason_code=0x00, properties=props) props = mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "key", "value") pubcomp_packet = mosq_test.gen_pubcomp(1, proto_ver=5, reason_code=0x00, properties=props) len_test("qos2 len >5", pubrec_packet, pubcomp_packet) mosquitto-1.6.9/test/broker/09-plugin-auth-acl-sub.py0000775000175000017500000000267313626052637021464 0ustar rogerroger#!/usr/bin/env python3 # Test topic subscription. All topic are allowed but not using wildcard in subscribe. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin.so\n") f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="readonly") connack_packet = mosq_test.gen_connack(rc=0) mid = 53 subscribe_packet = mosq_test.gen_subscribe(mid, "qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) mid_fail = 54 subscribe_packet_fail = mosq_test.gen_subscribe(mid_fail, "#", 0) suback_packet_fail = mosq_test.gen_suback(mid_fail, 0x80) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, subscribe_packet_fail, suback_packet_fail, "suback") rc = 0 sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-b2br-disconnect-qos1.py0000775000175000017500000000615013626052637022763 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge resend a QoS=1 message correctly after a disconnect? from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# both 1\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1) suback2_packet = mosq_test.gen_suback(mid, 1) mid = 3 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", dup=True) puback_packet = mosq_test.gen_puback(mid) mid = 20 publish2_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message") puback2_packet = mosq_test.gen_puback(mid) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(40) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): bridge.send(suback_packet) bridge.send(publish_packet) # Bridge doesn't have time to respond but should expect us to retry # and so remove PUBACK. bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet): bridge.send(suback2_packet) # Send a different publish message to make sure the response isn't to the old one. bridge.send(publish2_packet) if mosq_test.expect_packet(bridge, "puback", puback2_packet): rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/08-ssl-connect-cert-auth-without.py0000775000175000017500000000276613626052637023530 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client can connect without an SSL certificate if one is required. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") f.write("require_certificate true\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-cert-test", keepalive=keepalive) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-root-ca.crt", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) try: ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, "", "connack") except ssl.SSLError as err: if err.errno == 1: rc = 0 except socket.error as err: if err.errno == errno.ECONNRESET: rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-dollar.py0000775000175000017500000000153013626052637020605 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic starting with $ succeeds from mosq_test_helper import * rc = 1 mid = 19 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-dollar-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("$test/test", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-disconnect-with-will.py0000775000175000017500000000324513626052637022711 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client will is transmitted when a client disconnects with DISCONNECT with will. # MQTT 5 from mosq_test_helper import * def do_test(): rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive, proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=5, will_topic="will/test", will_payload=b"will delay", will_qos=2) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(reason_code=4, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=30, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=30, port=port) sock2.send(disconnect_packet) if mosq_test.expect_packet(sock1, "publish", publish_packet): rc = 0 sock2.close() sock1.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() mosquitto-1.6.9/test/broker/01-connect-uname-no-password-denied.py0000775000175000017500000000205613626052637024122 0ustar rogerroger#!/usr/bin/env python3 # Test whether a connection is denied if it provides just a username when it # needs a username and password. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) f.write("allow_anonymous false\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-test", keepalive=keepalive, username="user") connack_packet = mosq_test.gen_connack(rc=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/02-subscribe-long-topic.py0000775000175000017500000000170713626052637021723 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with 65535 hierarchy characters fails # This needs checking with MOSQ_USE_VALGRIND=1 to detect memory failures # https://github.com/eclipse/mosquitto/issues/1412 from mosq_test_helper import * rc = 1 mid = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-long-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "/"*65535, 0) suback_packet = mosq_test.gen_suback(mid, 0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/11-message-expiry.py0000775000175000017500000000762113626052637020634 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker reduces the message expiry interval when republishing. # MQTT v5, with a broker restart and persistence. # Client connects with clean session set false, subscribes with qos=1, then disconnects # Helper publishes two messages, one with a short expiry and one with a long expiry # We wait until the short expiry will have expired but the long one not. # Client reconnects, expects delivery of the long expiry message with a reduced # expiry interval property. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=5, clean_session=False, properties=props) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5, flags=1) mid = 53 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) helper_connect = mosq_test.gen_connect("helper", proto_ver=5) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=5) mid=1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 5) publish1s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message1", proto_ver=5, properties=props) puback1s_packet = mosq_test.gen_puback(mid) mid=2 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 100) publish2s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message2", proto_ver=5, properties=props) puback2s_packet = mosq_test.gen_puback(mid) mid=3 publish3_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message3", proto_ver=5) puback3_packet = mosq_test.gen_puback(mid) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack1_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.close() helper = mosq_test.do_client_connect(helper_connect, helper_connack, timeout=20, port=port) mosq_test.do_send_receive(helper, publish1s_packet, puback1s_packet, "puback 1") mosq_test.do_send_receive(helper, publish2s_packet, puback2s_packet, "puback 2") mosq_test.do_send_receive(helper, publish3_packet, puback3_packet, "puback 3") broker.terminate() broker.wait() (stdo1, stde1) = broker.communicate() sock.close() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) time.sleep(7) sock = mosq_test.do_client_connect(connect_packet, connack2_packet, timeout=20, port=port) packet = sock.recv(len(publish2s_packet)) for i in range(100, 1, -1): props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, i) publish2r_packet = mosq_test.gen_publish("subpub/qos1", mid=2, qos=1, payload="message2", proto_ver=5, properties=props) if packet == publish2r_packet: mosq_test.expect_packet(sock, "publish3", publish3_packet) rc = 0 break sock.close() finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) exit(rc) mosquitto-1.6.9/test/broker/Makefile0000664000175000017500000001347413626052637016541 0ustar rogerrogerinclude ../../config.mk .PHONY: all check clean test ptest .NOTPARALLEL: all : check : test clean : -rm -f *.vglog *.db $(MAKE) -C c clean test-compile : $(MAKE) -C c ptest : test-compile ./test.py test : test-compile 01 02 03 04 05 06 07 08 09 10 11 12 01 : ./01-connect-anon-denied.py ./01-connect-bad-packet.py ./01-connect-disconnect-v5.py ./01-connect-duplicate-v5.py ./01-connect-duplicate.py ./01-connect-invalid-id-0-311.py ./01-connect-invalid-id-0.py ./01-connect-invalid-id-missing.py ./01-connect-invalid-id-utf8.py ./01-connect-invalid-protonum.py ./01-connect-invalid-reserved.py ./01-connect-success-v5.py ./01-connect-success.py ./01-connect-uname-invalid-utf8.py ./01-connect-uname-no-flag.py ./01-connect-uname-no-password-denied.py ./01-connect-uname-password-denied-no-will.py ./01-connect-uname-password-denied.py ./01-connect-uname-pwd-no-flag.py ifeq ($(WITH_TLS),yes) ./01-connect-uname-password-success.py else ./01-connect-uname-password-success-no-tls.py endif ./01-connect-zero-length-id.py 02 : ./02-shared-qos0-v5.py ./02-subhier-crash.py ./02-subpub-qos0-long-topic.py ./02-subpub-qos0-retain-as-publish.py ./02-subpub-qos0-send-retain.py ./02-subpub-qos0-subscription-id.py ./02-subpub-qos0-topic-alias-unknown.py ./02-subpub-qos0-topic-alias.py ./02-subpub-qos0-v5.py ./02-subpub-qos0.py ./02-subpub-qos1-bad-pubcomp.py ./02-subpub-qos1-bad-pubrec.py ./02-subpub-qos1-message-expiry-retain.py ./02-subpub-qos1-message-expiry-will.py ./02-subpub-qos1-message-expiry.py ./02-subpub-qos1-nolocal.py ./02-subpub-qos1-v5.py ./02-subpub-qos1.py ./02-subpub-qos2-1322.py ./02-subpub-qos2-bad-puback-1.py ./02-subpub-qos2-bad-puback-2.py ./02-subpub-qos2-bad-pubcomp.py ./02-subpub-qos2-pubrec-error.py ./02-subpub-qos2-receive-maximum-1.py ./02-subpub-qos2-receive-maximum-2.py ./02-subpub-qos2-v5.py ./02-subpub-qos2.py ./02-subscribe-dollar-v5.py ./02-subscribe-invalid-utf8.py ./02-subscribe-long-topic.py ./02-subscribe-persistence-flipflop.py ./02-subscribe-qos0.py ./02-subscribe-qos1.py ./02-subscribe-qos2.py ./02-unsubscribe-invalid-no-topic.py ./02-unsubscribe-qos0.py ./02-unsubscribe-qos1.py ./02-unsubscribe-qos2-multiple-v5.py ./02-unsubscribe-qos2-multiple.py ./02-unsubscribe-qos2-v5.py ./02-unsubscribe-qos2.py 03 : #./03-publish-qos1-queued-bytes.py ./03-pattern-matching.py ./03-publish-b2c-disconnect-qos1.py ./03-publish-b2c-disconnect-qos2.py ./03-publish-b2c-qos1-len.py ./03-publish-b2c-qos2-len.py ./03-publish-c2b-disconnect-qos2.py ./03-publish-c2b-qos2-len.py ./03-publish-dollar-v5.py ./03-publish-dollar.py ./03-publish-invalid-utf8.py ./03-publish-long-topic.py ./03-publish-qos1-no-subscribers-v5.py ./03-publish-qos1-retain-disabled.py ./03-publish-qos1.py ./03-publish-qos2-max-inflight.py ./03-publish-qos2.py 04 : ./04-retain-check-source-persist-diff-port.py ./04-retain-check-source-persist.py ./04-retain-check-source.py ./04-retain-qos0-clear.py ./04-retain-qos0-fresh.py ./04-retain-qos0-repeated.py ./04-retain-qos0.py ./04-retain-qos1-qos0.py ./04-retain-upgrade-outgoing-qos.py 05 : ./05-clean-session-qos1.py ./05-session-expiry-v5.py 06 : ./06-bridge-b2br-disconnect-qos1.py ./06-bridge-b2br-disconnect-qos2.py ./06-bridge-b2br-late-connection-retain.py ./06-bridge-b2br-late-connection.py ./06-bridge-b2br-remapping.py ./06-bridge-br2b-disconnect-qos1.py ./06-bridge-br2b-disconnect-qos2.py ./06-bridge-br2b-remapping.py ./06-bridge-fail-persist-resend-qos1.py ./06-bridge-fail-persist-resend-qos2.py ./06-bridge-no-local.py ./06-bridge-per-listener-settings.py ./06-bridge-reconnect-local-out.py 07 : ./07-will-delay-reconnect.py ./07-will-delay-recover.py ./07-will-delay-session-expiry.py ./07-will-delay-session-expiry2.py ./07-will-delay.py ./07-will-disconnect-with-will.py ./07-will-invalid-utf8.py ./07-will-no-flag.py ./07-will-null-topic.py ./07-will-null.py ./07-will-properties.py ./07-will-qos0.py ./07-will-reconnect-1273.py 08 : ifeq ($(WITH_TLS),yes) ./08-ssl-bridge.py ./08-ssl-connect-cert-auth-crl.py ./08-ssl-connect-cert-auth-expired.py ./08-ssl-connect-cert-auth-revoked.py ./08-ssl-connect-cert-auth-without.py ./08-ssl-connect-cert-auth.py ./08-ssl-connect-identity.py ./08-ssl-connect-no-auth-wrong-ca.py ./08-ssl-connect-no-auth.py ./08-ssl-connect-no-identity.py ./08-ssl-hup-disconnect.py ifeq ($(WITH_TLS_PSK),yes) ./08-tls-psk-pub.py ./08-tls-psk-bridge.py endif endif 09 : ./09-acl-access-variants.py ./09-acl-change.py ./09-acl-empty-file.py ./09-auth-bad-method.py ./09-extended-auth-change-username.py ./09-extended-auth-multistep-reauth.py ./09-extended-auth-multistep.py ./09-extended-auth-single.py ./09-extended-auth-unsupported.py ./09-plugin-auth-acl-pub.py ./09-plugin-auth-acl-sub-denied.py ./09-plugin-auth-acl-sub.py ./09-plugin-auth-context-params.py ./09-plugin-auth-defer-unpwd-fail.py ./09-plugin-auth-defer-unpwd-success.py ./09-plugin-auth-msg-params.py ./09-plugin-auth-unpwd-fail.py ./09-plugin-auth-unpwd-success.py ./09-plugin-auth-v2-unpwd-fail.py ./09-plugin-auth-v2-unpwd-success.py ./09-pwfile-parse-invalid.py 10 : ./10-listener-mount-point.py 11 : ./11-message-expiry.py ./11-persistent-subscription.py ./11-persistent-subscription-v5.py ./11-persistent-subscription-no-local.py ./11-pub-props.py ./11-subscription-id.py 12 : ./12-prop-assigned-client-identifier.py ./12-prop-maximum-packet-size-broker.py ./12-prop-maximum-packet-size-connect.py ./12-prop-maximum-packet-size-publish-qos1.py ./12-prop-maximum-packet-size-publish-qos2.py ./12-prop-maximum-packet-size-publish.py ./12-prop-response-topic-correlation-data.py ./12-prop-response-topic.py ./12-prop-server-keepalive.py ./12-prop-session-expiry-invalid.py ./12-prop-subpub-content-type.py ./12-prop-subpub-payload-format.py ./12-prop-topic-alias-invalid.py mosquitto-1.6.9/test/broker/08-ssl-connect-no-auth-wrong-ca.py0000775000175000017500000000262113626052637023207 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet using an SSL connection. from mosq_test_helper import * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write("cafile ../ssl/all-ca.crt\n") f.write("certfile ../ssl/server.crt\n") f.write("keyfile ../ssl/server.key\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock = ssl.wrap_socket(sock, ca_certs="../ssl/test-alt-ca.crt", cert_reqs=ssl.CERT_REQUIRED) ssock.settimeout(20) try: ssock.connect(("localhost", port1)) except ssl.SSLError as err: if err.errno == 1: rc = 0 finally: os.remove(conf_file) ssock.close() time.sleep(0.5) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/04-retain-qos0.py0000775000175000017500000000205413626052637020031 0ustar rogerroger#!/usr/bin/env python3 # Test whether a retained PUBLISH to a topic with QoS 0 is actually retained. from mosq_test_helper import * rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 0) suback_packet = mosq_test.gen_suback(mid, 0) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.send(publish_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/07-will-qos0.py0000775000175000017500000000360313626052637017522 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client will is transmitted correctly. from mosq_test_helper import * def do_test(proto_ver, clean_session): rc = 1 mid = 53 keepalive = 60 connect1_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) if proto_ver == 5: props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 100) else: props = None connect2_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive, will_topic="will/qos0/test", will_payload=b"will-message", clean_session=clean_session, proto_ver=proto_ver, properties=props) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "will/qos0/test", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("will/qos0/test", qos=0, payload="will-message", proto_ver=proto_ver) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, port=port, timeout=5) sock2.close() if mosq_test.expect_packet(sock, "publish", publish_packet): rc = 0 sock.close() except Exception as e: print(e) finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4, True) do_test(4, False) do_test(5, True) do_test(5, False) exit(0) mosquitto-1.6.9/test/broker/03-publish-invalid-utf8.py0000775000175000017500000000177013626052637021650 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with an invalid UTF-8 topic fails from mosq_test_helper import * rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-invalid-utf8", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("invalid/utf8", 1, mid=mid) b = list(struct.unpack("B"*len(publish_packet), publish_packet)) b[11] = 0 # Topic should never have a 0x0000 publish_packet = struct.pack("B"*len(b), *b) puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: time.sleep(0.5) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, b"", "puback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/03-publish-b2c-timeout-qos1.py0000775000175000017500000000314013626052637022342 0ustar rogerroger#!/usr/bin/env python3 # Test whether a SUBSCRIBE to a topic with QoS 2 results in the correct SUBACK packet. from mosq_test_helper import * rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-timeout-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/timeout/test", 1) suback_packet = mosq_test.gen_suback(mid, 1) mid = 1 publish_packet = mosq_test.gen_publish("qos1/timeout/test", qos=1, mid=mid, payload="timeout-message") publish_dup_packet = mosq_test.gen_publish("qos1/timeout/test", qos=1, mid=mid, payload="timeout-message", dup=True) puback_packet = mosq_test.gen_puback(mid) broker = mosq_test.start_broker(filename=os.path.basename(__file__)) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") pub = subprocess.Popen(['./03-publish-b2c-timeout-qos1-helper.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)) pub.wait() (stdo, stde) = pub.communicate() # Should have now received a publish command if mosq_test.expect_packet(sock, "publish", publish_packet): # Wait for longer than 5 seconds to get republish with dup set # This is covered by the 8 second timeout if mosq_test.expect_packet(sock, "dup publish", publish_dup_packet): sock.send(puback_packet) rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/12-prop-maximum-packet-size-connect.py0000775000175000017500000000141113626052637024161 0ustar rogerroger#!/usr/bin/env python3 # Test whether setting maximum packet size to smaller than a CONNACK packet # results in the CONNECT being rejected. # MQTTv5 from mosq_test_helper import * rc = 1 keepalive = 10 props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MAXIMUM_PACKET_SIZE, 2) connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive, properties=props) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, b"", port=port) # Exception occurs if connack packet returned rc = 0 finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/01-connect-uname-password-success.pwfile0000664000175000017500000000016213626052637024557 0ustar rogerrogeruser:$6$LIg/OiUz2yPftClP$dQu0vVNqRHOcMOzDLuqv4e+5rTFW83DFm3s+C8fy9F7Ip73cdIGUlsNGBs4MtKWNjtMl8LnT+pIQZ7ic1ZttyQ== mosquitto-1.6.9/test/broker/06-bridge-b2br-disconnect-qos2.py0000775000175000017500000000740213626052637022765 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge resend a QoS=1 message correctly after a disconnect? from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# both 2\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2) suback_packet = mosq_test.gen_suback(mid, 2) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2) suback2_packet = mosq_test.gen_suback(mid, 2) mid = 3 subscribe3_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2) suback3_packet = mosq_test.gen_suback(mid, 2) mid = 5 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message") publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(40) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): bridge.send(suback_packet) bridge.send(publish_packet) bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet): bridge.send(suback2_packet) bridge.send(publish_dup_packet) if mosq_test.expect_packet(bridge, "pubrec", pubrec_packet): bridge.send(pubrel_packet) bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "3rd subscribe", subscribe3_packet): bridge.send(suback3_packet) bridge.send(publish_dup_packet) if mosq_test.expect_packet(bridge, "2nd pubrec", pubrec_packet): bridge.send(pubrel_packet) if mosq_test.expect_packet(bridge, "pubcomp", pubcomp_packet): rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/broker/03-publish-qos1.py0000775000175000017500000000156113626052637020217 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 1 results in the correct PUBACK packet. from mosq_test_helper import * rc = 1 mid = 19 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message") puback_packet = mosq_test.gen_puback(mid) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") rc = 0 sock.close() finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-1.6.9/test/broker/06-bridge-b2br-late-connection-retain.py0000775000175000017500000000617613626052637024323 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge queue up retained messages correctly if the remote broker starts up late? from mosq_test_helper import * def write_config1(filename, persistence_file, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("persistence true\n") f.write("persistence_file %s\n" % (persistence_file)) def write_config2(filename, persistence_file, port1, port2): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("topic bridge/# out 1\n") f.write("notifications false\n") f.write("bridge_attempt_unsubscribe false\n") f.write("persistence true\n") f.write("persistence_file %s\n" % (persistence_file)) (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') persistence_file = os.path.basename(__file__).replace('.py', '.db') rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) c_connect_packet = mosq_test.gen_connect("client", keepalive=keepalive) c_connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("bridge/test", qos=1, mid=mid, payload="message", retain=True) puback_packet = mosq_test.gen_puback(mid) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(40) ssock.bind(('', port1)) ssock.listen(5) write_config1(conf_file, persistence_file, port1, port2) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) try: client = mosq_test.do_client_connect(c_connect_packet, c_connack_packet, timeout=20, port=port2) mosq_test.do_send_receive(client, publish_packet, puback_packet, "puback") client.close() broker.terminate() broker.wait() # Restart, with retained message in place write_config2(conf_file, persistence_file, port1, port2) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) (bridge, address) = ssock.accept() bridge.settimeout(20) if mosq_test.expect_packet(bridge, "connect", connect_packet): bridge.send(connack_packet) if mosq_test.expect_packet(bridge, "publish", publish_packet): bridge.send(puback_packet) # Guard against multiple retained messages of the same type by # sending a pingreq to give us something to expect back. If we get # a publish, it's a fail. mosq_test.do_ping(bridge) rc = 0 bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() os.remove(persistence_file) if rc: print(stde.decode('utf-8')) ssock.close() exit(rc) mosquitto-1.6.9/test/mqtt5_props.py0000664000175000017500000000370413626052637016457 0ustar rogerrogerimport struct PROP_PAYLOAD_FORMAT_INDICATOR = 1 PROP_MESSAGE_EXPIRY_INTERVAL = 2 PROP_CONTENT_TYPE = 3 PROP_RESPONSE_TOPIC = 8 PROP_CORRELATION_DATA = 9 PROP_SUBSCRIPTION_IDENTIFIER = 11 PROP_SESSION_EXPIRY_INTERVAL = 17 PROP_ASSIGNED_CLIENT_IDENTIFIER = 18 PROP_SERVER_KEEP_ALIVE = 19 PROP_AUTHENTICATION_METHOD = 21 PROP_AUTHENTICATION_DATA = 22 PROP_REQUEST_PROBLEM_INFO = 23 PROP_WILL_DELAY_INTERVAL = 24 PROP_REQUEST_RESPONSE_INFO = 25 PROP_RESPONSE_INFO = 26 PROP_SERVER_REFERENCE = 28 PROP_REASON_STRING = 31 PROP_RECEIVE_MAXIMUM = 33 PROP_TOPIC_ALIAS_MAXIMUM = 34 PROP_TOPIC_ALIAS = 35 PROP_MAXIMUM_QOS = 36 PROP_RETAIN_AVAILABLE = 37 PROP_USER_PROPERTY = 38 PROP_MAXIMUM_PACKET_SIZE = 39 PROP_WILDCARD_SUB_AVAILABLE = 40 PROP_SUBSCRIPTION_ID_AVAILABLE = 41 PROP_SHARED_SUB_AVAILABLE = 42 def gen_byte_prop(identifier, byte): prop = struct.pack('BB', identifier, byte) return prop def gen_uint16_prop(identifier, word): prop = struct.pack('!BH', identifier, word) return prop def gen_uint32_prop(identifier, word): prop = struct.pack('!BI', identifier, word) return prop def gen_string_prop(identifier, s): s = s.encode("utf-8") prop = struct.pack('!BH%ds'%(len(s)), identifier, len(s), s) return prop def gen_string_pair_prop(identifier, s1, s2): s1 = s1.encode("utf-8") s2 = s2.encode("utf-8") prop = struct.pack('!BH%dsH%ds'%(len(s1), len(s2)), identifier, len(s1), s1, len(s2), s2) return prop def gen_varint_prop(identifier, val): v = pack_varint(val) return struct.pack("!B"+str(len(v))+"s", identifier, v) def pack_varint(varint): s = b"" while True: byte = varint % 128 varint = varint // 128 # If there are more digits to encode, set the top bit of this digit if varint > 0: byte = byte | 0x80 s = s + struct.pack("!B", byte) if varint == 0: return s def prop_finalise(props): return pack_varint(len(props)) + props mosquitto-1.6.9/test/Makefile0000664000175000017500000000051213626052637015242 0ustar rogerrogerinclude ../config.mk .PHONY: all check test ptest clean all : check : test test : utest $(MAKE) -C broker test $(MAKE) -C lib test ptest : utest $(MAKE) -C broker ptest $(MAKE) -C lib ptest utest : $(MAKE) -C unit test reallyclean : clean clean : $(MAKE) -C lib clean $(MAKE) -C broker clean $(MAKE) -C unit clean mosquitto-1.6.9/test/unit/0000775000175000017500000000000013626052637014563 5ustar rogerrogermosquitto-1.6.9/test/unit/persist_write_stubs.c0000664000175000017500000000305613626052637021056 0ustar rogerroger#include #define WITH_BROKER #include #include #include #include #include #include extern uint64_t last_retained; extern char *last_sub; extern int last_qos; struct mosquitto *context__init(struct mosquitto_db *db, mosq_sock_t sock) { return mosquitto__calloc(1, sizeof(struct mosquitto)); } int log__printf(struct mosquitto *mosq, int priority, const char *fmt, ...) { return 0; } time_t mosquitto_time(void) { return 123; } int net__socket_close(struct mosquitto_db *db, struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int mosquitto_acl_check(struct mosquitto_db *db, struct mosquitto *context, const char *topic, long payloadlen, void* payload, int qos, bool retain, int access) { return MOSQ_ERR_SUCCESS; } int acl__find_acls(struct mosquitto_db *db, struct mosquitto *context) { return MOSQ_ERR_SUCCESS; } int send__publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { return MOSQ_ERR_SUCCESS; } int send__pubcomp(struct mosquitto *mosq, uint16_t mid) { return MOSQ_ERR_SUCCESS; } int send__pubrec(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code) { return MOSQ_ERR_SUCCESS; } int send__pubrel(struct mosquitto *mosq, uint16_t mid) { return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/test/unit/utf8.c0000664000175000017500000004556713626052637015636 0ustar rogerroger#include #include #include "mosquitto.h" /* Test data taken from * http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt but modified for * updated standard (no 5, 6 byte lengths) */ static void utf8_helper_len(const char *text, int len, int expected) { int result; result = mosquitto_validate_utf8(text, len); CU_ASSERT_EQUAL(result, expected); } static void utf8_helper(const char *text, int expected) { utf8_helper_len(text, strlen(text), expected); } static void TEST_utf8_empty(void) { utf8_helper_len(NULL, 0, MOSQ_ERR_INVAL); } static void TEST_utf8_valid(void) { /* 1 Some correct UTF-8 text */ utf8_helper("", MOSQ_ERR_SUCCESS); utf8_helper("You should see the Greek word 'kosme': \"κόσμε\"", MOSQ_ERR_SUCCESS); } static void TEST_utf8_truncated(void) { char buf[4]; /* As per boundary condition tests, but less one character */ buf[0] = 0xC2; buf[1] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); buf[0] = 0xE0; buf[1] = 0xA0; buf[2] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); buf[0] = 0xF0; buf[1] = 0x90; buf[2] = 0x80; buf[3] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } static void TEST_utf8_boundary_conditions(void) { /* 2 Boundary condition test cases */ /* 2.1 First possible sequence of a certain length */ utf8_helper_len("2.1.1 1 byte (U-00000000): \"\0\"", 39, MOSQ_ERR_MALFORMED_UTF8); utf8_helper("2.1.2 2 bytes (U-00000080): \"€\"", MOSQ_ERR_MALFORMED_UTF8); /* control char */ utf8_helper("2.1.3 3 bytes (U-00000800): \"ࠀ\"", MOSQ_ERR_SUCCESS); utf8_helper("2.1.4 4 bytes (U-00010000): \"𐀀\"", MOSQ_ERR_SUCCESS); /* 2.2 Last possible sequence of a certain length */ utf8_helper("2.2.1 1 byte (U-0000007F): \"\"", MOSQ_ERR_MALFORMED_UTF8); /* control char */ utf8_helper("2.2.2 2 bytes (U-000007FF): \"߿\"", MOSQ_ERR_SUCCESS); /* Non character */ utf8_helper("2.2.3 3 bytes (U-0000FFFF): \"￿\"", MOSQ_ERR_MALFORMED_UTF8); /* Non character */ utf8_helper("2.2.4 4 bytes (U-0010FFFF): \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 2.3 Other boundary conditions */ utf8_helper("2.3.1 U-0000D7FF = ed 9f bf = \"퟿\"", MOSQ_ERR_SUCCESS); utf8_helper("2.3.2 U-0000E000 = ee 80 80 = \"\"", MOSQ_ERR_SUCCESS); utf8_helper("2.3.3 U-0000FFFD = ef bf bd = \"�\"", MOSQ_ERR_SUCCESS); /* Non character */ utf8_helper("2.3.4 U-0010FFFF = f4 8f bf bf = \"􏿿\"", MOSQ_ERR_MALFORMED_UTF8); /* This used to be valid in pre-2003 utf-8 */ utf8_helper("2.3.5 U-00110000 = f4 90 80 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); } static void TEST_utf8_malformed_sequences(void) { char buf[100]; int i; /* 3 Malformed sequences */ /* 3.1 Unexpected continuation bytes */ utf8_helper("3.1.1 First continuation byte 0x80: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.2 Last continuation byte 0xbf: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.3 2 continuation bytes: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.4 3 continuation bytes: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.5 4 continuation bytes: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.6 5 continuation bytes: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.7 6 continuation bytes: \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.8 7 continuation bytes: \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 3.1.9 Sequence of all 64 possible continuation bytes (0x80-0xbf): */ memset(buf, 0, sizeof(buf)); for(i=0x80; i<0x90; i++){ buf[i-0x80] = i; } utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); memset(buf, 0, sizeof(buf)); for(i=0x90; i<0xa0; i++){ buf[i-0x90] = i; } utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); for(i=0x80; i<0xA0; i++){ buf[0] = i; buf[1] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } for(i=0xA0; i<0xC0; i++){ buf[0] = i; buf[1] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* 3.2 Lonely start characters */ /* 3.2.1 All 32 first bytes of 2-byte sequences (0xc0-0xdf), each followed by a space character: */ utf8_helper(" ", MOSQ_ERR_MALFORMED_UTF8); for(i=0xC0; i<0xE0; i++){ buf[0] = i; buf[1] = ' '; buf[2] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* 3.2.2 All 16 first bytes of 3-byte sequences (0xe0-0xef), each followed by a space character: */ utf8_helper("\" \"", MOSQ_ERR_MALFORMED_UTF8); for(i=0xe0; i<0xf0; i++){ buf[0] = i; buf[1] = ' '; buf[2] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* 3.2.3 All 8 first bytes of 4-byte sequences (0xf0-0xf7), each followed by a space character: */ utf8_helper("\" \"", MOSQ_ERR_MALFORMED_UTF8); for(i=0xF0; i<0xF8; i++){ buf[0] = i; buf[1] = ' '; buf[2] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* 3.2.4 All 4 first bytes of 5-byte sequences (0xf8-0xfb), each followed by a space character: */ utf8_helper("\" \"", MOSQ_ERR_MALFORMED_UTF8); for(i=0xF8; i<0xFC; i++){ buf[0] = i; buf[1] = ' '; buf[2] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* 3.2.5 All 2 first bytes of 6-byte sequences (0xfc-0xfd), each followed by a space character: */ utf8_helper("\" \"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper(" ", MOSQ_ERR_MALFORMED_UTF8); utf8_helper(" ", MOSQ_ERR_MALFORMED_UTF8); for(i=0xFC; i<0xFE; i++){ buf[0] = i; buf[1] = ' '; buf[2] = 0; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* 3.3 Sequences with last continuation byte missing All bytes of an incomplete sequence should be signalled as a single malformed sequence, i.e., you should see only a single replacement character in each of the next 10 tests. (Characters as in section 2) */ utf8_helper("3.3.1 2-byte sequence with last byte missing (U+0000): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.2 3-byte sequence with last byte missing (U+0000): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.3 4-byte sequence with last byte missing (U+0000): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.4 5-byte sequence with last byte missing (U+0000): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.5 6-byte sequence with last byte missing (U+0000): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.6 2-byte sequence with last byte missing (U-000007FF): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.7 3-byte sequence with last byte missing (U-0000FFFF): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.8 4-byte sequence with last byte missing (U-001FFFFF): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.9 5-byte sequence with last byte missing (U-03FFFFFF): \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.10 6-byte sequence with last byte missing (U-7FFFFFFF): \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 3.4 Concatenation of incomplete sequences All the 10 sequences of 3.3 concatenated, you should see 10 malformed sequences being signalled:*/ utf8_helper("\"\"", MOSQ_ERR_MALFORMED_UTF8); /* 3.5 Impossible bytes The following two bytes cannot appear in a correct UTF-8 string */ utf8_helper("3.5.1 fe = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.5.2 ff = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.5.3 fe fe ff ff = \"\"", MOSQ_ERR_MALFORMED_UTF8); } static void TEST_utf8_overlong_encoding(void) { /* 4 Overlong sequences The following sequences are not malformed according to the letter of the Unicode 2.0 standard. However, they are longer then necessary and a correct UTF-8 encoder is not allowed to produce them. A "safe UTF-8 decoder" should reject them just like malformed sequences for two reasons: (1) It helps to debug applications if overlong sequences are not treated as valid representations of characters, because this helps to spot problems more quickly. (2) Overlong sequences provide alternative representations of characters, that could maliciously be used to bypass filters that check only for ASCII characters. For instance, a 2-byte encoded line feed (LF) would not be caught by a line counter that counts only 0x0a bytes, but it would still be processed as a line feed by an unsafe UTF-8 decoder later in the pipeline. From a security point of view, ASCII compatibility of UTF-8 sequences means also, that ASCII characters are *only* allowed to be represented by ASCII bytes in the range 0x00-0x7f. To ensure this aspect of ASCII compatibility, use only "safe UTF-8 decoders" that reject overlong UTF-8 sequences for which a shorter encoding exists. */ /* 4.1 Examples of an overlong ASCII character With a safe UTF-8 decoder, all of the following five overlong representations of the ASCII character slash ("/") should be rejected like a malformed UTF-8 sequence, for instance by substituting it with a replacement character. If you see a slash below, you do not have a safe UTF-8 decoder! */ utf8_helper("4.1.1 U+002F = c0 af = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.2 U+002F = e0 80 af = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.3 U+002F = f0 80 80 af = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.4 U+002F = f8 80 80 80 af = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.5 U+002F = fc 80 80 80 80 af = \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 4.2 Maximum overlong sequences Below you see the highest Unicode value that is still resulting in an overlong sequence if represented with the given number of bytes. This is a boundary test for safe UTF-8 decoders. All five characters should be rejected like malformed UTF-8 sequences. */ utf8_helper("4.2.1 U-0000007F = c1 bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.2 U-000007FF = e0 9f bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.3 U-0000FFFF = f0 8f bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.4 U-001FFFFF = f8 87 bf bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.5 U-03FFFFFF = fc 83 bf bf bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 4.3 Overlong representation of the NUL character The following five sequences should also be rejected like malformed UTF-8 sequences and should not be treated like the ASCII NUL character. */ utf8_helper("4.3.1 U+0000 = c0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.2 U+0000 = e0 80 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.3 U+0000 = f0 80 80 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.4 U+0000 = f8 80 80 80 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.5 U+0000 = fc 80 80 80 80 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); } static void TEST_utf8_illegal_code_positions(void) { /* 5 Illegal code positions The following UTF-8 sequences should be rejected like malformed sequences, because they never represent valid ISO 10646 characters and a UTF-8 decoder that accepts them might introduce security problems comparable to overlong UTF-8 sequences. */ /* 5.1 Single UTF-16 surrogates */ utf8_helper("5.1.1 U+D800 = ed a0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.2 U+DB7F = ed ad bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.3 U+DB80 = ed ae 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.4 U+DBFF = ed af bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.5 U+DC00 = ed b0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.6 U+DF80 = ed be 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.7 U+DFFF = ed bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 5.2 Paired UTF-16 surrogates */ utf8_helper("5.2.1 U+D800 U+DC00 = ed a0 80 ed b0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.2 U+D800 U+DFFF = ed a0 80 ed bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.3 U+DB7F U+DC00 = ed ad bf ed b0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.4 U+DB7F U+DFFF = ed ad bf ed bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.5 U+DB80 U+DC00 = ed ae 80 ed b0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.6 U+DB80 U+DFFF = ed ae 80 ed bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.7 U+DBFF U+DC00 = ed af bf ed b0 80 = \"\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.8 U+DBFF U+DFFF = ed af bf ed bf bf = \"\"", MOSQ_ERR_MALFORMED_UTF8); /* 5.3 Noncharacter code positions The following "noncharacters" are "reserved for internal use" by applications, and according to older versions of the Unicode Standard "should never be interchanged". Unicode Corrigendum #9 dropped the latter restriction. Nevertheless, their presence in incoming UTF-8 data can remain a potential security risk, depending on what use is made of these codes subsequently. Examples of such internal use: - Some file APIs with 16-bit characters may use the integer value -1 = U+FFFF to signal an end-of-file (EOF) or error condition. - In some UTF-16 receivers, code point U+FFFE might trigger a byte-swap operation (to convert between UTF-16LE and UTF-16BE). With such internal use of noncharacters, it may be desirable and safer to block those code points in UTF-8 decoders, as they should never occur legitimately in incoming UTF-8 data, and could trigger unsafe behaviour in subsequent processing. Particularly problematic noncharacters in 16-bit applications: */ utf8_helper("5.3.1 U+FFFE = ef bf be = \"￾\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.3.2 U+FFFF = ef bf bf = \"￿\"", MOSQ_ERR_MALFORMED_UTF8); /* Other noncharacters: */ /* FIXME - these need splitting up into separate tests. */ utf8_helper("5.3.3 U+FDD0 .. U+FDEF = \"﷐﷑﷒﷓﷔﷕﷖﷗﷘﷙﷚﷛﷜﷝﷞﷟﷠﷡﷢﷣﷤﷥﷦﷧﷨﷩﷪﷫﷬﷭﷮﷯\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷐", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷑", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷒", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷓", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷔", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷕", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷖", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷗", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷘", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷙", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷚", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷛", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷜", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷝", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷞", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷟", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷠", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷡", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷢", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷣", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷤", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷥", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷦", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷧", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷨", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷩", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷪", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷫", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷬", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷭", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷮", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("﷯", MOSQ_ERR_MALFORMED_UTF8); /* 5.3.4 U+nFFFE U+nFFFF (for n = 1..10) */ utf8_helper("🿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("🿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("𯿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("𯿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("𿿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("𿿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񏿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񏿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񟿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񟿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񯿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񯿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񿿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("񿿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򏿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򏿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򟿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򟿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򯿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򯿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򿿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("򿿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󏿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󏿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󟿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󟿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󯿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󯿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󿿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("󿿿", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("􏿾", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("􏿿", MOSQ_ERR_MALFORMED_UTF8); } void TEST_utf8_control_characters(void) { char buf[10]; int i; /* U+0001 to U+001F are single byte control characters */ for(i=0x01; i<0x20; i++){ buf[0] = i; buf[1] = '\0'; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } /* U+007F is a single byte control character */ buf[0] = 0x7F; buf[1] = '\0'; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); /* U+007F to U+009F are two byte control characters */ for(i=0x80; i<0xA0; i++){ buf[0] = 0xC2; buf[1] = i-0x80; buf[2] = '\0'; utf8_helper(buf, MOSQ_ERR_MALFORMED_UTF8); } } void TEST_utf8_mqtt_1_5_4_2(void) { char buf[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', '\0'}; utf8_helper_len(buf, 9, MOSQ_ERR_SUCCESS); buf[3] = '\0'; utf8_helper_len(buf, 9, MOSQ_ERR_MALFORMED_UTF8); } void TEST_utf8_mqtt_1_5_4_3(void) { char buf[10] = {'a', 'b', 0xEF, 0xBB, 0xBF, 'f', 'g', 'h', 'i', '\0'}; utf8_helper_len(buf, 9, MOSQ_ERR_SUCCESS); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_utf8_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("UTF-8", NULL, NULL); if(!test_suite){ printf("Error adding CUnit test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "UTF-8 empty", TEST_utf8_empty) || !CU_add_test(test_suite, "UTF-8 valid", TEST_utf8_valid) || !CU_add_test(test_suite, "UTF-8 truncated", TEST_utf8_truncated) || !CU_add_test(test_suite, "UTF-8 boundary conditions", TEST_utf8_boundary_conditions) || !CU_add_test(test_suite, "UTF-8 malformed sequences", TEST_utf8_malformed_sequences) || !CU_add_test(test_suite, "UTF-8 overlong encoding", TEST_utf8_overlong_encoding) || !CU_add_test(test_suite, "UTF-8 illegal code positions", TEST_utf8_illegal_code_positions) || !CU_add_test(test_suite, "UTF-8 control characters", TEST_utf8_control_characters) || !CU_add_test(test_suite, "UTF-8 MQTT-1.5.4-2", TEST_utf8_mqtt_1_5_4_2) || !CU_add_test(test_suite, "UTF-8 MQTT-1.5.4-3", TEST_utf8_mqtt_1_5_4_3) ){ printf("Error adding UTF-8 CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/property_add.c0000664000175000017500000005552313626052637017435 0ustar rogerroger#include #include #include "mqtt_protocol.h" #include "property_mosq.h" #include "packet_mosq.h" /* ======================================================================== * BAD IDENTIFIER * ======================================================================== */ static void bad_add_byte_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_byte(&proplist, identifier, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void bad_add_int16_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_int16(&proplist, identifier, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void bad_add_int32_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_int32(&proplist, identifier, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void bad_add_varint_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_varint(&proplist, identifier, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void bad_add_binary_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_binary(&proplist, identifier, "test", 4); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void bad_add_string_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_string(&proplist, identifier, "test"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void bad_add_string_pair_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_string_pair(&proplist, identifier, "key", "value"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_PTR_NULL(proplist); } static void TEST_add_bad_byte(void) { bad_add_byte_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); bad_add_byte_helper(MQTT_PROP_CONTENT_TYPE); bad_add_byte_helper(MQTT_PROP_RESPONSE_TOPIC); bad_add_byte_helper(MQTT_PROP_CORRELATION_DATA); bad_add_byte_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); bad_add_byte_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); bad_add_byte_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); bad_add_byte_helper(MQTT_PROP_SERVER_KEEP_ALIVE); bad_add_byte_helper(MQTT_PROP_AUTHENTICATION_METHOD); bad_add_byte_helper(MQTT_PROP_AUTHENTICATION_DATA); bad_add_byte_helper(MQTT_PROP_WILL_DELAY_INTERVAL); bad_add_byte_helper(MQTT_PROP_RESPONSE_INFORMATION); bad_add_byte_helper(MQTT_PROP_SERVER_REFERENCE); bad_add_byte_helper(MQTT_PROP_REASON_STRING); bad_add_byte_helper(MQTT_PROP_RECEIVE_MAXIMUM); bad_add_byte_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); bad_add_byte_helper(MQTT_PROP_TOPIC_ALIAS); bad_add_byte_helper(MQTT_PROP_USER_PROPERTY); bad_add_byte_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); } static void TEST_add_bad_int16(void) { bad_add_int16_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); bad_add_int16_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); bad_add_int16_helper(MQTT_PROP_CONTENT_TYPE); bad_add_int16_helper(MQTT_PROP_RESPONSE_TOPIC); bad_add_int16_helper(MQTT_PROP_CORRELATION_DATA); bad_add_int16_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); bad_add_int16_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); bad_add_int16_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); bad_add_int16_helper(MQTT_PROP_AUTHENTICATION_METHOD); bad_add_int16_helper(MQTT_PROP_AUTHENTICATION_DATA); bad_add_int16_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); bad_add_int16_helper(MQTT_PROP_WILL_DELAY_INTERVAL); bad_add_int16_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); bad_add_int16_helper(MQTT_PROP_RESPONSE_INFORMATION); bad_add_int16_helper(MQTT_PROP_SERVER_REFERENCE); bad_add_int16_helper(MQTT_PROP_REASON_STRING); bad_add_int16_helper(MQTT_PROP_MAXIMUM_QOS); bad_add_int16_helper(MQTT_PROP_RETAIN_AVAILABLE); bad_add_int16_helper(MQTT_PROP_USER_PROPERTY); bad_add_int16_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); bad_add_int16_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); bad_add_int16_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); bad_add_int16_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_add_bad_int32(void) { bad_add_int32_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); bad_add_int32_helper(MQTT_PROP_CONTENT_TYPE); bad_add_int32_helper(MQTT_PROP_RESPONSE_TOPIC); bad_add_int32_helper(MQTT_PROP_CORRELATION_DATA); bad_add_int32_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); bad_add_int32_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); bad_add_int32_helper(MQTT_PROP_SERVER_KEEP_ALIVE); bad_add_int32_helper(MQTT_PROP_AUTHENTICATION_METHOD); bad_add_int32_helper(MQTT_PROP_AUTHENTICATION_DATA); bad_add_int32_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); bad_add_int32_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); bad_add_int32_helper(MQTT_PROP_RESPONSE_INFORMATION); bad_add_int32_helper(MQTT_PROP_SERVER_REFERENCE); bad_add_int32_helper(MQTT_PROP_REASON_STRING); bad_add_int32_helper(MQTT_PROP_RECEIVE_MAXIMUM); bad_add_int32_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); bad_add_int32_helper(MQTT_PROP_TOPIC_ALIAS); bad_add_int32_helper(MQTT_PROP_MAXIMUM_QOS); bad_add_int32_helper(MQTT_PROP_RETAIN_AVAILABLE); bad_add_int32_helper(MQTT_PROP_USER_PROPERTY); bad_add_int32_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); bad_add_int32_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); bad_add_int32_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_add_bad_varint(void) { bad_add_varint_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); bad_add_varint_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); bad_add_varint_helper(MQTT_PROP_CONTENT_TYPE); bad_add_varint_helper(MQTT_PROP_RESPONSE_TOPIC); bad_add_varint_helper(MQTT_PROP_CORRELATION_DATA); bad_add_varint_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); bad_add_varint_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); bad_add_varint_helper(MQTT_PROP_SERVER_KEEP_ALIVE); bad_add_varint_helper(MQTT_PROP_AUTHENTICATION_METHOD); bad_add_varint_helper(MQTT_PROP_AUTHENTICATION_DATA); bad_add_varint_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); bad_add_varint_helper(MQTT_PROP_WILL_DELAY_INTERVAL); bad_add_varint_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); bad_add_varint_helper(MQTT_PROP_RESPONSE_INFORMATION); bad_add_varint_helper(MQTT_PROP_SERVER_REFERENCE); bad_add_varint_helper(MQTT_PROP_REASON_STRING); bad_add_varint_helper(MQTT_PROP_RECEIVE_MAXIMUM); bad_add_varint_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); bad_add_varint_helper(MQTT_PROP_TOPIC_ALIAS); bad_add_varint_helper(MQTT_PROP_MAXIMUM_QOS); bad_add_varint_helper(MQTT_PROP_RETAIN_AVAILABLE); bad_add_varint_helper(MQTT_PROP_USER_PROPERTY); bad_add_varint_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); bad_add_varint_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); bad_add_varint_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); bad_add_varint_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_add_bad_binary(void) { bad_add_binary_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); bad_add_binary_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); bad_add_binary_helper(MQTT_PROP_CONTENT_TYPE); bad_add_binary_helper(MQTT_PROP_RESPONSE_TOPIC); bad_add_binary_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); bad_add_binary_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); bad_add_binary_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); bad_add_binary_helper(MQTT_PROP_SERVER_KEEP_ALIVE); bad_add_binary_helper(MQTT_PROP_AUTHENTICATION_METHOD); bad_add_binary_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); bad_add_binary_helper(MQTT_PROP_WILL_DELAY_INTERVAL); bad_add_binary_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); bad_add_binary_helper(MQTT_PROP_RESPONSE_INFORMATION); bad_add_binary_helper(MQTT_PROP_SERVER_REFERENCE); bad_add_binary_helper(MQTT_PROP_REASON_STRING); bad_add_binary_helper(MQTT_PROP_RECEIVE_MAXIMUM); bad_add_binary_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); bad_add_binary_helper(MQTT_PROP_TOPIC_ALIAS); bad_add_binary_helper(MQTT_PROP_MAXIMUM_QOS); bad_add_binary_helper(MQTT_PROP_RETAIN_AVAILABLE); bad_add_binary_helper(MQTT_PROP_USER_PROPERTY); bad_add_binary_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); bad_add_binary_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); bad_add_binary_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); bad_add_binary_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_add_bad_string(void) { bad_add_string_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); bad_add_string_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); bad_add_string_helper(MQTT_PROP_CORRELATION_DATA); bad_add_string_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); bad_add_string_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); bad_add_string_helper(MQTT_PROP_SERVER_KEEP_ALIVE); bad_add_string_helper(MQTT_PROP_AUTHENTICATION_DATA); bad_add_string_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); bad_add_string_helper(MQTT_PROP_WILL_DELAY_INTERVAL); bad_add_string_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); bad_add_string_helper(MQTT_PROP_RECEIVE_MAXIMUM); bad_add_string_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); bad_add_string_helper(MQTT_PROP_TOPIC_ALIAS); bad_add_string_helper(MQTT_PROP_MAXIMUM_QOS); bad_add_string_helper(MQTT_PROP_RETAIN_AVAILABLE); bad_add_string_helper(MQTT_PROP_USER_PROPERTY); bad_add_string_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); bad_add_string_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); bad_add_string_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); bad_add_string_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_add_bad_string_pair(void) { bad_add_string_pair_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); bad_add_string_pair_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); bad_add_string_pair_helper(MQTT_PROP_CONTENT_TYPE); bad_add_string_pair_helper(MQTT_PROP_RESPONSE_TOPIC); bad_add_string_pair_helper(MQTT_PROP_CORRELATION_DATA); bad_add_string_pair_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); bad_add_string_pair_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); bad_add_string_pair_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); bad_add_string_pair_helper(MQTT_PROP_SERVER_KEEP_ALIVE); bad_add_string_pair_helper(MQTT_PROP_AUTHENTICATION_METHOD); bad_add_string_pair_helper(MQTT_PROP_AUTHENTICATION_DATA); bad_add_string_pair_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); bad_add_string_pair_helper(MQTT_PROP_WILL_DELAY_INTERVAL); bad_add_string_pair_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); bad_add_string_pair_helper(MQTT_PROP_RESPONSE_INFORMATION); bad_add_string_pair_helper(MQTT_PROP_SERVER_REFERENCE); bad_add_string_pair_helper(MQTT_PROP_REASON_STRING); bad_add_string_pair_helper(MQTT_PROP_RECEIVE_MAXIMUM); bad_add_string_pair_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); bad_add_string_pair_helper(MQTT_PROP_TOPIC_ALIAS); bad_add_string_pair_helper(MQTT_PROP_MAXIMUM_QOS); bad_add_string_pair_helper(MQTT_PROP_RETAIN_AVAILABLE); bad_add_string_pair_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); bad_add_string_pair_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); bad_add_string_pair_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); bad_add_string_pair_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } /* ======================================================================== * SINGLE ADD * ======================================================================== */ static void single_add_byte_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_byte(&proplist, identifier, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_EQUAL(proplist->value.i8, 1); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void single_add_int16_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_int16(&proplist, identifier, 11234); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_EQUAL(proplist->value.i16, 11234); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void single_add_int32_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_int32(&proplist, identifier, 765432); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_EQUAL(proplist->value.i32, 765432); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void single_add_varint_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_varint(&proplist, identifier, 139123999); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_EQUAL(proplist->value.varint, 139123999); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void single_add_binary_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_binary(&proplist, identifier, "test", 4); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_EQUAL(proplist->value.bin.len, 4); CU_ASSERT_NSTRING_EQUAL(proplist->value.bin.v, "test", 4); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void single_add_string_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_string(&proplist, identifier, "string"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_STRING_EQUAL(proplist->value.s.v, "string"); CU_ASSERT_EQUAL(proplist->value.s.len, strlen("string")); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void single_add_string_pair_helper(int identifier) { mosquitto_property *proplist = NULL; int rc; rc = mosquitto_property_add_string_pair(&proplist, identifier, "key", "value"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); if(proplist){ CU_ASSERT_EQUAL(proplist->identifier, identifier); CU_ASSERT_STRING_EQUAL(proplist->name.v, "key"); CU_ASSERT_EQUAL(proplist->name.len, strlen("key")); CU_ASSERT_STRING_EQUAL(proplist->value.s.v, "value"); CU_ASSERT_EQUAL(proplist->value.s.len, strlen("value")); CU_ASSERT_PTR_NULL(proplist->next); mosquitto_property_free_all(&proplist); } } static void TEST_add_single_byte(void) { single_add_byte_helper(MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); single_add_byte_helper(MQTT_PROP_REQUEST_PROBLEM_INFORMATION); single_add_byte_helper(MQTT_PROP_REQUEST_RESPONSE_INFORMATION); single_add_byte_helper(MQTT_PROP_MAXIMUM_QOS); single_add_byte_helper(MQTT_PROP_RETAIN_AVAILABLE); single_add_byte_helper(MQTT_PROP_WILDCARD_SUB_AVAILABLE); single_add_byte_helper(MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); single_add_byte_helper(MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_add_single_int16(void) { single_add_int16_helper(MQTT_PROP_SERVER_KEEP_ALIVE); single_add_int16_helper(MQTT_PROP_RECEIVE_MAXIMUM); single_add_int16_helper(MQTT_PROP_TOPIC_ALIAS_MAXIMUM); single_add_int16_helper(MQTT_PROP_TOPIC_ALIAS); } static void TEST_add_single_int32(void) { single_add_int32_helper(MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); single_add_int32_helper(MQTT_PROP_SESSION_EXPIRY_INTERVAL); single_add_int32_helper(MQTT_PROP_WILL_DELAY_INTERVAL); single_add_int32_helper(MQTT_PROP_MAXIMUM_PACKET_SIZE); } static void TEST_add_single_varint(void) { single_add_varint_helper(MQTT_PROP_SUBSCRIPTION_IDENTIFIER); } static void TEST_add_single_binary(void) { single_add_binary_helper(MQTT_PROP_CORRELATION_DATA); single_add_binary_helper(MQTT_PROP_AUTHENTICATION_DATA); } static void TEST_add_single_string(void) { single_add_string_helper(MQTT_PROP_CONTENT_TYPE); single_add_string_helper(MQTT_PROP_RESPONSE_TOPIC); single_add_string_helper(MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); single_add_string_helper(MQTT_PROP_AUTHENTICATION_METHOD); single_add_string_helper(MQTT_PROP_RESPONSE_INFORMATION); single_add_string_helper(MQTT_PROP_SERVER_REFERENCE); single_add_string_helper(MQTT_PROP_REASON_STRING); } static void TEST_add_single_string_pair(void) { single_add_string_pair_helper(MQTT_PROP_USER_PROPERTY); } /* ======================================================================== * ADD ALL PROPERTIES FOR A COMMAND * ======================================================================== */ static void TEST_add_all_connect(void) { mosquitto_property *proplist = NULL; mosquitto_property *p; int count; int rc; rc = mosquitto_property_add_int32(&proplist, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 86400); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string(&proplist, MQTT_PROP_AUTHENTICATION_METHOD, "basic"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_binary(&proplist, MQTT_PROP_AUTHENTICATION_DATA, "password", strlen("password")); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int16(&proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1024); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int16(&proplist, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 64); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "user-agent", "mosquitto/test"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int32(&proplist, MQTT_PROP_MAXIMUM_PACKET_SIZE, 200000000); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); p = proplist; count = 0; while(p){ count++; p = p->next; } CU_ASSERT_EQUAL(count, 9); mosquitto_property_free_all(&proplist); } static void TEST_add_all_connack(void) { mosquitto_property *proplist = NULL; mosquitto_property *p; int count; int rc; rc = mosquitto_property_add_int32(&proplist, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 86400); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string(&proplist, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "clientid"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int16(&proplist, MQTT_PROP_SERVER_KEEP_ALIVE, 900); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string(&proplist, MQTT_PROP_AUTHENTICATION_METHOD, "basic"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_binary(&proplist, MQTT_PROP_AUTHENTICATION_DATA, "password", strlen("password")); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string(&proplist, MQTT_PROP_RESPONSE_INFORMATION, "response"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string(&proplist, MQTT_PROP_SERVER_REFERENCE, "localhost"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string(&proplist, MQTT_PROP_REASON_STRING, "reason"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int16(&proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1024); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int16(&proplist, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 64); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_MAXIMUM_QOS, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_RETAIN_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "user-agent", "mosquitto/test"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_int32(&proplist, MQTT_PROP_MAXIMUM_PACKET_SIZE, 200000000); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_SHARED_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist); p = proplist; count = 0; while(p){ count++; p = p->next; } CU_ASSERT_EQUAL(count, 17); mosquitto_property_free_all(&proplist); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_property_add_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Property add", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Property add test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Add bad byte", TEST_add_bad_byte) || !CU_add_test(test_suite, "Add bad int16", TEST_add_bad_int16) || !CU_add_test(test_suite, "Add bad int32", TEST_add_bad_int32) || !CU_add_test(test_suite, "Add bad varint", TEST_add_bad_varint) || !CU_add_test(test_suite, "Add bad binary", TEST_add_bad_binary) || !CU_add_test(test_suite, "Add bad string", TEST_add_bad_string) || !CU_add_test(test_suite, "Add bad string pair", TEST_add_bad_string_pair) || !CU_add_test(test_suite, "Add single byte", TEST_add_single_byte) || !CU_add_test(test_suite, "Add single int16", TEST_add_single_int16) || !CU_add_test(test_suite, "Add single int32", TEST_add_single_int32) || !CU_add_test(test_suite, "Add single varint", TEST_add_single_varint) || !CU_add_test(test_suite, "Add single binary", TEST_add_single_binary) || !CU_add_test(test_suite, "Add single string", TEST_add_single_string) || !CU_add_test(test_suite, "Add single string pair", TEST_add_single_string_pair) || !CU_add_test(test_suite, "Add all CONNECT", TEST_add_all_connect) || !CU_add_test(test_suite, "Add all CONNACK", TEST_add_all_connack) ){ printf("Error adding Property Add CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/misc_trim_test.c0000664000175000017500000001012513626052637017753 0ustar rogerroger#include #include #include static void rtrim_helper(const char *expected, char *buf) { char *res; res = misc__trimblanks(buf); CU_ASSERT_PTR_NOT_NULL(res); if(res){ CU_ASSERT_EQUAL(strlen(buf), strlen(res)); CU_ASSERT_STRING_EQUAL(res, expected); CU_ASSERT_PTR_EQUAL(res, buf); } } static void ltrim_helper(const char *expected, char *buf) { char *res; res = misc__trimblanks(buf); CU_ASSERT_PTR_NOT_NULL(res); if(res){ CU_ASSERT_EQUAL(strlen(expected), strlen(res)); CU_ASSERT_STRING_EQUAL(res, expected); } } static void TEST_null_input(void) { char *res; res = misc__trimblanks(NULL); CU_ASSERT_PTR_NULL(res); } static void TEST_empty_input(void) { char buf[10]; char *res; memset(buf, 0, sizeof(buf)); res = misc__trimblanks(buf); CU_ASSERT_PTR_NOT_NULL(res); if(res){ CU_ASSERT_STRING_EQUAL(res, ""); } } static void TEST_no_blanks(void) { char buf[10] = "noblanks"; rtrim_helper("noblanks", buf); } static void TEST_rtrim(void) { char buf1[20] = "spaces "; char buf2[20] = "spaces "; char buf3[20] = "spaces "; char buf4[20] = "spaces "; char buf5[20] = "tabs\t"; char buf6[20] = "tabs\t\t"; char buf7[20] = "tabs\t\t\t"; char buf8[20] = "tabs\t\t\t\t"; char buf9[20] = "mixed \t"; char buf10[20] = "mixed\t "; char buf11[20] = "mixed\t\t "; char buf12[20] = "mixed \t \t "; rtrim_helper("spaces", buf1); rtrim_helper("spaces", buf2); rtrim_helper("spaces", buf3); rtrim_helper("spaces", buf4); rtrim_helper("tabs", buf5); rtrim_helper("tabs", buf6); rtrim_helper("tabs", buf7); rtrim_helper("tabs", buf8); rtrim_helper("mixed", buf9); rtrim_helper("mixed", buf10); rtrim_helper("mixed", buf11); rtrim_helper("mixed", buf12); } static void TEST_ltrim(void) { char buf1[20] = " spaces"; char buf2[20] = " spaces"; char buf3[20] = " spaces"; char buf4[20] = " spaces"; char buf5[20] = "\ttabs"; char buf6[20] = "\t\ttabs"; char buf7[20] = "\t\t\ttabs"; char buf8[20] = "\t\t\t\ttabs"; char buf9[20] = "\t mixed"; char buf10[20] = " \tmixed"; char buf11[20] = " \t\tmixed"; char buf12[20] = "\t \t mixed"; ltrim_helper("spaces", buf1); ltrim_helper("spaces", buf2); ltrim_helper("spaces", buf3); ltrim_helper("spaces", buf4); ltrim_helper("tabs", buf5); ltrim_helper("tabs", buf6); ltrim_helper("tabs", buf7); ltrim_helper("tabs", buf8); ltrim_helper("mixed", buf9); ltrim_helper("mixed", buf10); ltrim_helper("mixed", buf11); ltrim_helper("mixed", buf12); } static void TEST_btrim(void) { char buf1[20] = " spaces "; char buf2[20] = " spaces "; char buf3[20] = " spaces "; char buf4[20] = " spaces "; char buf5[20] = "\ttabs\t"; char buf6[20] = "\t\ttabs\t\t"; char buf7[20] = "\t\t\ttabs\t\t\t"; char buf8[20] = "\t\t\t\ttabs\t\t\t\t"; char buf9[20] = "\t mixed \t"; char buf10[20] = " \tmixed\t "; char buf11[20] = " \t\tmixed\t\t "; char buf12[20] = "\t \t mixed \t \t "; ltrim_helper("spaces", buf1); ltrim_helper("spaces", buf2); ltrim_helper("spaces", buf3); ltrim_helper("spaces", buf4); ltrim_helper("tabs", buf5); ltrim_helper("tabs", buf6); ltrim_helper("tabs", buf7); ltrim_helper("tabs", buf8); ltrim_helper("mixed", buf9); ltrim_helper("mixed", buf10); ltrim_helper("mixed", buf11); ltrim_helper("mixed", buf12); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_misc_trim_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Misc string trim", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Misc string trim test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Null input", TEST_null_input) || !CU_add_test(test_suite, "Empty input", TEST_empty_input) || !CU_add_test(test_suite, "No blanks", TEST_no_blanks) || !CU_add_test(test_suite, "Right trim", TEST_rtrim) || !CU_add_test(test_suite, "Left trim", TEST_ltrim) || !CU_add_test(test_suite, "Both trim", TEST_btrim) ){ printf("Error adding Misc topic CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/stubs.c0000664000175000017500000000060013626052637016063 0ustar rogerroger#include #include struct mosquitto_db{ }; int log__printf(struct mosquitto *mosq, int priority, const char *fmt, ...) { return 0; } time_t mosquitto_time(void) { return 123; } int net__socket_close(struct mosquitto_db *db, struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } mosquitto-1.6.9/test/unit/util_topic_test.c0000664000175000017500000002335613626052637020152 0ustar rogerroger#include #include #include static void match_helper(const char *sub, const char *topic) { int rc; bool match; rc = mosquitto_topic_matches_sub(sub, topic, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); } static void no_match_helper(int rc_expected, const char *sub, const char *topic) { int rc; bool match; rc = mosquitto_topic_matches_sub(sub, topic, &match); CU_ASSERT_EQUAL(rc, rc_expected); if(rc != rc_expected){ printf("%d:%d %s:%s\n", rc, rc_expected, sub, topic); } CU_ASSERT_EQUAL(match, false); } /* ======================================================================== * EMPTY INPUT * ======================================================================== */ static void TEST_empty_input(void) { int rc; bool match; rc = mosquitto_topic_matches_sub("sub", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub(NULL, "topic", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub(NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub("sub", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub("", "topic", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub("", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub2("sub", 3, NULL, 0, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub2(NULL, 0, "topic", 5, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub2(NULL, 0, NULL, 0, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub2("sub", 3, "", 0, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub2("", 0, "topic", 5, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub2("", 0, "", 0, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); } /* ======================================================================== * VALID MATCHING AND NON-MATCHING * ======================================================================== */ static void TEST_valid_matching(void) { match_helper("foo/#", "foo/"); match_helper("foo/#", "foo"); match_helper("foo//bar", "foo//bar"); match_helper("foo//+", "foo//bar"); match_helper("foo/+/+/baz", "foo///baz"); match_helper("foo/bar/+", "foo/bar/"); match_helper("foo/bar", "foo/bar"); match_helper("foo/+", "foo/bar"); match_helper("foo/+/baz", "foo/bar/baz"); match_helper("A/B/+/#", "A/B/B/C"); match_helper("foo/+/#", "foo/bar/baz"); match_helper("foo/+/#", "foo/bar"); match_helper("#", "foo/bar/baz"); match_helper("#", "foo/bar/baz"); match_helper("#", "/foo/bar"); match_helper("/#", "/foo/bar"); } static void TEST_invalid_but_matching(void) { /* Matching here is "naive treatment of the wildcards would produce a * match". They shouldn't really match, they should fail. */ no_match_helper(MOSQ_ERR_INVAL, "+foo", "+foo"); no_match_helper(MOSQ_ERR_INVAL, "fo+o", "fo+o"); no_match_helper(MOSQ_ERR_INVAL, "foo+", "foo+"); no_match_helper(MOSQ_ERR_INVAL, "+foo/bar", "+foo/bar"); no_match_helper(MOSQ_ERR_INVAL, "foo+/bar", "foo+/bar"); no_match_helper(MOSQ_ERR_INVAL, "foo/+bar", "foo/+bar"); no_match_helper(MOSQ_ERR_INVAL, "foo/bar+", "foo/bar+"); no_match_helper(MOSQ_ERR_INVAL, "+foo", "afoo"); no_match_helper(MOSQ_ERR_INVAL, "fo+o", "foao"); no_match_helper(MOSQ_ERR_INVAL, "foo+", "fooa"); no_match_helper(MOSQ_ERR_INVAL, "+foo/bar", "afoo/bar"); no_match_helper(MOSQ_ERR_INVAL, "foo+/bar", "fooa/bar"); no_match_helper(MOSQ_ERR_INVAL, "foo/+bar", "foo/abar"); no_match_helper(MOSQ_ERR_INVAL, "foo/bar+", "foo/bara"); no_match_helper(MOSQ_ERR_INVAL, "#foo", "#foo"); no_match_helper(MOSQ_ERR_INVAL, "fo#o", "fo#o"); no_match_helper(MOSQ_ERR_INVAL, "foo#", "foo#"); no_match_helper(MOSQ_ERR_INVAL, "#foo/bar", "#foo/bar"); no_match_helper(MOSQ_ERR_INVAL, "foo#/bar", "foo#/bar"); no_match_helper(MOSQ_ERR_INVAL, "foo/#bar", "foo/#bar"); no_match_helper(MOSQ_ERR_INVAL, "foo/bar#", "foo/bar#"); no_match_helper(MOSQ_ERR_INVAL, "foo+", "fooa"); no_match_helper(MOSQ_ERR_INVAL, "foo/+", "foo/+"); no_match_helper(MOSQ_ERR_INVAL, "foo/#", "foo/+"); no_match_helper(MOSQ_ERR_INVAL, "foo/+", "foo/bar/+"); no_match_helper(MOSQ_ERR_INVAL, "foo/#", "foo/bar/+"); no_match_helper(MOSQ_ERR_INVAL, "foo/+", "foo/#"); no_match_helper(MOSQ_ERR_INVAL, "foo/#", "foo/#"); no_match_helper(MOSQ_ERR_INVAL, "foo/+", "foo/bar/#"); no_match_helper(MOSQ_ERR_INVAL, "foo/#", "foo/bar/#"); } static void TEST_valid_no_matching(void) { no_match_helper(MOSQ_ERR_SUCCESS, "test/6/#", "test/3"); no_match_helper(MOSQ_ERR_SUCCESS, "foo/bar", "foo"); no_match_helper(MOSQ_ERR_SUCCESS, "foo/+", "foo/bar/baz"); no_match_helper(MOSQ_ERR_SUCCESS, "foo/+/baz", "foo/bar/bar"); no_match_helper(MOSQ_ERR_SUCCESS, "foo/+/#", "fo2/bar/baz"); no_match_helper(MOSQ_ERR_SUCCESS, "/#", "foo/bar"); no_match_helper(MOSQ_ERR_SUCCESS, "#", "$SYS/bar"); no_match_helper(MOSQ_ERR_SUCCESS, "$BOB/bar", "$SYS/bar"); } static void TEST_invalid(void) { no_match_helper(MOSQ_ERR_INVAL, "foo#", "foo"); no_match_helper(MOSQ_ERR_INVAL, "fo#o/", "foo"); no_match_helper(MOSQ_ERR_INVAL, "foo#", "fooa"); no_match_helper(MOSQ_ERR_INVAL, "foo+", "foo"); no_match_helper(MOSQ_ERR_INVAL, "foo/#a", "foo"); no_match_helper(MOSQ_ERR_INVAL, "#a", "foo"); no_match_helper(MOSQ_ERR_INVAL, "foo/#abc", "foo"); no_match_helper(MOSQ_ERR_INVAL, "#abc", "foo"); no_match_helper(MOSQ_ERR_INVAL, "/#a", "foo/bar"); } /* ======================================================================== * PUB TOPIC CHECK * ======================================================================== */ static void pub_topic_helper(const char *topic, int rc_expected) { int rc; rc = mosquitto_pub_topic_check(topic); CU_ASSERT_EQUAL(rc, rc_expected); rc = mosquitto_pub_topic_check2(topic, strlen(topic)); CU_ASSERT_EQUAL(rc, rc_expected); } static void TEST_pub_topic_valid(void) { pub_topic_helper("pub/topic", MOSQ_ERR_SUCCESS); pub_topic_helper("pub//topic", MOSQ_ERR_SUCCESS); pub_topic_helper("pub/ /topic", MOSQ_ERR_SUCCESS); } static void TEST_pub_topic_invalid(void) { pub_topic_helper("+pub/topic", MOSQ_ERR_INVAL); pub_topic_helper("pub+/topic", MOSQ_ERR_INVAL); pub_topic_helper("pub/+topic", MOSQ_ERR_INVAL); pub_topic_helper("pub/topic+", MOSQ_ERR_INVAL); pub_topic_helper("pub/topic/+", MOSQ_ERR_INVAL); pub_topic_helper("#pub/topic", MOSQ_ERR_INVAL); pub_topic_helper("pub#/topic", MOSQ_ERR_INVAL); pub_topic_helper("pub/#topic", MOSQ_ERR_INVAL); pub_topic_helper("pub/topic#", MOSQ_ERR_INVAL); pub_topic_helper("pub/topic/#", MOSQ_ERR_INVAL); pub_topic_helper("+/pub/topic", MOSQ_ERR_INVAL); } /* ======================================================================== * SUB TOPIC CHECK * ======================================================================== */ static void sub_topic_helper(const char *topic, int rc_expected) { int rc; rc = mosquitto_sub_topic_check(topic); CU_ASSERT_EQUAL(rc, rc_expected); rc = mosquitto_sub_topic_check2(topic, strlen(topic)); CU_ASSERT_EQUAL(rc, rc_expected); } static void TEST_sub_topic_valid(void) { sub_topic_helper("sub/topic", MOSQ_ERR_SUCCESS); sub_topic_helper("sub//topic", MOSQ_ERR_SUCCESS); sub_topic_helper("sub/ /topic", MOSQ_ERR_SUCCESS); sub_topic_helper("sub/+/topic", MOSQ_ERR_SUCCESS); sub_topic_helper("+/+/+", MOSQ_ERR_SUCCESS); sub_topic_helper("+", MOSQ_ERR_SUCCESS); sub_topic_helper("sub/topic/#", MOSQ_ERR_SUCCESS); sub_topic_helper("sub//topic/#", MOSQ_ERR_SUCCESS); sub_topic_helper("sub/ /topic/#", MOSQ_ERR_SUCCESS); sub_topic_helper("sub/+/topic/#", MOSQ_ERR_SUCCESS); sub_topic_helper("+/+/+/#", MOSQ_ERR_SUCCESS); sub_topic_helper("#", MOSQ_ERR_SUCCESS); } static void TEST_sub_topic_invalid(void) { sub_topic_helper("+sub/topic", MOSQ_ERR_INVAL); sub_topic_helper("sub+/topic", MOSQ_ERR_INVAL); sub_topic_helper("sub/+topic", MOSQ_ERR_INVAL); sub_topic_helper("sub/topic+", MOSQ_ERR_INVAL); sub_topic_helper("#sub/topic", MOSQ_ERR_INVAL); sub_topic_helper("sub#/topic", MOSQ_ERR_INVAL); sub_topic_helper("sub/#topic", MOSQ_ERR_INVAL); sub_topic_helper("sub/topic#", MOSQ_ERR_INVAL); sub_topic_helper("#/sub/topic", MOSQ_ERR_INVAL); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_util_topic_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Util topic", NULL, NULL); if(!test_suite){ printf("Error adding CUnit util topic test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Matching: Empty input", TEST_empty_input) || !CU_add_test(test_suite, "Matching: Valid matching", TEST_valid_matching) || !CU_add_test(test_suite, "Matching: Valid no matching", TEST_valid_no_matching) || !CU_add_test(test_suite, "Matching: Invalid but matching", TEST_invalid_but_matching) || !CU_add_test(test_suite, "Matching: Invalid", TEST_invalid) || !CU_add_test(test_suite, "Pub topic: Valid", TEST_pub_topic_valid) || !CU_add_test(test_suite, "Pub topic: Invalid", TEST_pub_topic_invalid) || !CU_add_test(test_suite, "Sub topic: Valid", TEST_sub_topic_valid) || !CU_add_test(test_suite, "Sub topic: Invalid", TEST_sub_topic_invalid) ){ printf("Error adding util topic CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/files/0000775000175000017500000000000013626052637015665 5ustar rogerrogermosquitto-1.6.9/test/unit/files/persist_read/0000775000175000017500000000000013626052637020351 5ustar rogerrogermosquitto-1.6.9/test/unit/files/persist_read/unsupported-version.test-db0000664000175000017500000000002713626052637025707 0ustar rogerrogermosquitto dbmosquitto-1.6.9/test/unit/files/persist_read/v3-client-message.test-db0000664000175000017500000000022313626052637025060 0ustar rogerrogermosquitto db 4VxT source_idtopicpayload client-idR# client-idTsmosquitto-1.6.9/test/unit/files/persist_read/v5-client-message-props.test-db0000664000175000017500000000027113626052637026226 0ustar rogerrogermosquitto db4Vx=T [source_idusernametopicpayload#R client-idTs client-idmosquitto-1.6.9/test/unit/files/persist_read/v3-cfg.test-db0000664000175000017500000000004713626052637022723 0ustar rogerrogermosquitto db 4Vxmosquitto-1.6.9/test/unit/files/persist_read/v5-cfg-truncated.test-db0000664000175000017500000000005613626052637024714 0ustar rogerrogermosquitto db4Vxmosquitto-1.6.9/test/unit/files/persist_read/v4-cfg.test-db0000664000175000017500000000004713626052637022724 0ustar rogerrogermosquitto db 4Vxmosquitto-1.6.9/test/unit/files/persist_read/v3-cfg-truncated.test-db0000664000175000017500000000004613626052637024711 0ustar rogerrogermosquitto db mosquitto-1.6.9/test/unit/files/persist_read/v3-retain.test-db0000664000175000017500000000014613626052637023446 0ustar rogerrogermosquitto db 4VxT source_idtopicpayloadTmosquitto-1.6.9/test/unit/files/persist_read/v5-cfg.test-db0000664000175000017500000000005713626052637022726 0ustar rogerrogermosquitto db4Vxmosquitto-1.6.9/test/unit/files/persist_read/v3-message-store.test-db0000664000175000017500000000013013626052637024733 0ustar rogerrogermosquitto db 4Vx source_idtopicpayloadmosquitto-1.6.9/test/unit/files/persist_read/v5-client-message.test-db0000664000175000017500000000026613626052637025071 0ustar rogerrogermosquitto db4Vx=T [source_idusernametopicpayload#R client-idTs client-idmosquitto-1.6.9/test/unit/files/persist_read/v3-bad-chunk.test-db0000664000175000017500000000006413626052637024017 0ustar rogerrogermosquitto dbnochunk mosquitto-1.6.9/test/unit/files/persist_read/v5-message-store-props.test-db0000664000175000017500000000027113626052637026104 0ustar rogerrogermosquitto db4Vx@ [source_idusernametopicpayload#R client-ids client-idmosquitto-1.6.9/test/unit/files/persist_read/v4-message-store.test-db0000664000175000017500000000014413626052637024741 0ustar rogerrogermosquitto db 4Vx2Tv source_idusername[topicpayloadmosquitto-1.6.9/test/unit/files/persist_read/empty.test-db0000664000175000017500000000000013626052637022761 0ustar rogerrogermosquitto-1.6.9/test/unit/files/persist_read/corrupt-header-short.test-db0000664000175000017500000000001013626052637025705 0ustar rogerrogercorrupt mosquitto-1.6.9/test/unit/files/persist_read/v5-client.test-db0000664000175000017500000000012013626052637023434 0ustar rogerrogermosquitto db4Vx#R client-idmosquitto-1.6.9/test/unit/files/persist_read/v3-client.test-db0000664000175000017500000000010213626052637023432 0ustar rogerrogermosquitto db 4Vx client-idR#mosquitto-1.6.9/test/unit/files/persist_read/v5-bad-chunk.test-db0000664000175000017500000000010113626052637024011 0ustar rogerrogermosquitto db abcdefghijmosquitto-1.6.9/test/unit/files/persist_read/v5-sub.test-db0000664000175000017500000000017113626052637022755 0ustar rogerrogermosquitto db4Vx#R client-id!v#  client-idsubscriptionmosquitto-1.6.9/test/unit/files/persist_read/v5-message-store.test-db0000664000175000017500000000016413626052637024744 0ustar rogerrogermosquitto db4Vx= [source_idusernametopicpayloadmosquitto-1.6.9/test/unit/files/persist_read/v3-sub.test-db0000664000175000017500000000014213626052637022751 0ustar rogerrogermosquitto db 5Vx client-idR# client-id subscriptionmosquitto-1.6.9/test/unit/files/persist_read/v3-cfg-bad-dbid.test-db0000664000175000017500000000004713626052637024347 0ustar rogerrogermosquitto db  mosquitto-1.6.9/test/unit/files/persist_read/v5-retain.test-db0000664000175000017500000000020413626052637023443 0ustar rogerrogermosquitto db4Vx=T [source_idusernametopicpayloadTmosquitto-1.6.9/test/unit/files/persist_read/corrupt-header-long.test-db0000664000175000017500000000005313626052637025514 0ustar rogerrogercorruptcorruptcorruptcorruptcorruptcorrupt mosquitto-1.6.9/test/unit/files/persist_write/0000775000175000017500000000000013626052637020570 5ustar rogerrogermosquitto-1.6.9/test/unit/files/persist_write/v4-full.test-db0000664000175000017500000000071213626052637023345 0ustar rogerrogermosquitto db Amosqpub|0000-dev[queued/messagesmessage1Amosqpub|0000-dev[queued/messagesmessage2F?mosqpub|0000-dev[retained/message/testmessagedurable1}\durable2\durable2 durable2 ?!durable1sub/qos0/no-messagesdurable2queued/messagesmosquitto-1.6.9/test/unit/files/persist_write/v5-message-store-no-ref.test-db0000664000175000017500000000005713626052637026350 0ustar rogerrogermosquitto db4Vxmosquitto-1.6.9/test/unit/files/persist_write/empty.test-db0000664000175000017500000000005713626052637023214 0ustar rogerrogermosquitto dbmosquitto-1.6.9/test/unit/test.c0000664000175000017500000000212713626052637015710 0ustar rogerroger#include "config.h" #include #include #include int init_datatype_read_tests(void); int init_datatype_write_tests(void); int init_property_add_tests(void); int init_property_read_tests(void); int init_property_user_read_tests(void); int init_property_write_tests(void); int init_utf8_tests(void); int init_util_topic_tests(void); int init_misc_trim_tests(void); int main(int argc, char *argv[]) { unsigned int fails; if(CU_initialize_registry() != CUE_SUCCESS){ printf("Error initializing CUnit registry.\n"); return 1; } if(0 || init_utf8_tests() || init_datatype_read_tests() || init_datatype_write_tests() || init_property_add_tests() || init_property_read_tests() || init_property_user_read_tests() || init_property_write_tests() || init_util_topic_tests() || init_misc_trim_tests() ){ CU_cleanup_registry(); return 1; } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); fails = CU_get_number_of_failures(); CU_cleanup_registry(); return (int)fails; } mosquitto-1.6.9/test/unit/persist_write_test.c0000664000175000017500000002356213626052637020701 0ustar rogerroger/* Tests for persistence. * * FIXME - these need to be aggressive about finding failures, at the moment * they are just confirming that good behaviour works. */ #include #include #define WITH_BROKER #define WITH_PERSISTENCE #include "mosquitto_broker_internal.h" #include "persist.h" uint64_t last_retained; char *last_sub = NULL; int last_qos; /* read entire file into memory */ static int file_read(const char *filename, uint8_t **data, size_t *len) { FILE *fptr; size_t rc; fptr = fopen(filename, "rb"); if(!fptr) return 1; fseek(fptr, 0, SEEK_END); *len = ftell(fptr); *data = malloc(*len); if(!(*data)){ fclose(fptr); return 1; } fseek(fptr, 0, SEEK_SET); rc = fread(*data, 1, *len, fptr); fclose(fptr); if(rc == *len){ return 0; }else{ *len = 0; free(*data); return 1; } } /* Crude file diff, only for small files */ static int file_diff(const char *one, const char *two) { size_t len1, len2; uint8_t *data1 = NULL, *data2 = NULL; int rc = 1; if(file_read(one, &data1, &len1)){ return 1; } if(file_read(two, &data2, &len2)){ free(data1); return 1; } if(len1 == len2){ rc = memcmp(data1, data2, len1); } free(data1); free(data2); return rc; } static void TEST_persistence_disabled(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; rc = persist__backup(&db, false); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); config.persistence_filepath = "disabled.db"; rc = persist__backup(&db, false); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void TEST_empty_file(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "empty.db"; rc = persist__backup(&db, false); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_write/empty.test-db", "empty.db")); unlink("empty.db"); } static void TEST_v5_config_ok(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-cfg.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-cfg.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v5-cfg.test-db", "v5-cfg.db")); unlink("v5-cfg.db"); } static void TEST_v5_message_store_no_ref(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-message-store.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-message-store-no-ref.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_write/v5-message-store-no-ref.test-db", "v5-message-store-no-ref.db")); unlink("v5-message-store-no-ref.db"); } static void TEST_v5_message_store_props(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto__listener listener; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); memset(&listener, 0, sizeof(struct mosquitto__listener)); db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-message-store-props.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-message-store-props.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v5-message-store-props.test-db", "v5-message-store-props.db")); unlink("v5-message-store-props.db"); } static void TEST_v5_client(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-client.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-client.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v5-client.test-db", "v5-client.db")); unlink("v5-client.db"); } static void TEST_v5_client_message(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto__listener listener; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); memset(&listener, 0, sizeof(struct mosquitto__listener)); db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-client-message.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-client-message.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v5-client-message.test-db", "v5-client-message.db")); unlink("v5-client-message.db"); } static void TEST_v5_client_message_props(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto__listener listener; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); memset(&listener, 0, sizeof(struct mosquitto__listener)); db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-client-message-props.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_PTR_NOT_NULL(db.msg_store->source_listener); if(db.msg_store->source_listener){ CU_ASSERT_EQUAL(db.msg_store->source_listener->port, 1883); } } config.persistence_filepath = "v5-client-message-props.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v5-client-message-props.test-db", "v5-client-message-props.db")); unlink("v5-client-message-props.db"); } static void TEST_v5_sub(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto__listener listener; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); memset(&listener, 0, sizeof(struct mosquitto__listener)); db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; db__open(&config, &db); config.persistence = true; config.persistence_filepath = "files/persist_read/v5-sub.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-sub.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v5-sub.test-db", "v5-sub.db")); unlink("v5-sub.db"); } #if 0 NOT WORKING static void TEST_v5_full(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; db__open(&config, &db); config.persistence = true; config.persistence_filepath = "files/persist_write/v5-full.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-full.db"; rc = persist__backup(&db, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_write/v5-full.test-db", "v5-full.db")); unlink("v5-full.db"); } #endif /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int main(int argc, char *argv[]) { CU_pSuite test_suite = NULL; unsigned int fails; if(CU_initialize_registry() != CUE_SUCCESS){ printf("Error initializing CUnit registry.\n"); return 1; } test_suite = CU_add_suite("Persist write", NULL, NULL); if(!test_suite){ printf("Error adding CUnit persist write test suite.\n"); CU_cleanup_registry(); return 1; } if(0 || !CU_add_test(test_suite, "Persistence disabled", TEST_persistence_disabled) || !CU_add_test(test_suite, "Empty file", TEST_empty_file) || !CU_add_test(test_suite, "v5 config ok", TEST_v5_config_ok) || !CU_add_test(test_suite, "v5 message store (message has no refs)", TEST_v5_message_store_no_ref) || !CU_add_test(test_suite, "v5 message store + props", TEST_v5_message_store_props) || !CU_add_test(test_suite, "v5 client", TEST_v5_client) || !CU_add_test(test_suite, "v5 client message", TEST_v5_client_message) || !CU_add_test(test_suite, "v5 client message+props", TEST_v5_client_message_props) || !CU_add_test(test_suite, "v5 sub", TEST_v5_sub) //|| !CU_add_test(test_suite, "v5 full", TEST_v5_full) ){ printf("Error adding persist CUnit tests.\n"); CU_cleanup_registry(); return 1; } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); fails = CU_get_number_of_failures(); CU_cleanup_registry(); return (int)fails; } mosquitto-1.6.9/test/unit/property_read.c0000664000175000017500000016362713626052637017625 0ustar rogerroger#include #include #include "mqtt_protocol.h" #include "property_mosq.h" #include "packet_mosq.h" static void byte_prop_read_helper( int command, uint8_t *payload, int remaining_length, int rc_expected, int identifier, uint8_t value_expected) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.i8, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 2); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); } static void duplicate_byte_helper(int command, int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 4; /* Proplen = (Identifier + byte)*2 */ payload[1] = identifier; payload[2] = 1; payload[3] = identifier; payload[4] = 0; byte_prop_read_helper(command, payload, 5, MOSQ_ERR_DUPLICATE_PROPERTY, identifier, 1); } static void bad_byte_helper(int command, int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = identifier; payload[2] = 2; /* 0, 1 are only valid values */ byte_prop_read_helper(command, payload, 3, MOSQ_ERR_PROTOCOL, identifier, 0); } static void int32_prop_read_helper( int command, uint8_t *payload, int remaining_length, int rc_expected, int identifier, uint32_t value_expected) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.i32, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 5); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); } static void duplicate_int32_helper(int command, int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 10; /* Proplen = (Identifier + int32)*2 */ payload[1] = identifier; payload[2] = 1; payload[3] = 1; payload[4] = 1; payload[5] = 1; payload[6] = identifier; payload[7] = 0; payload[8] = 0; payload[9] = 0; payload[10] = 0; int32_prop_read_helper(command, payload, 11, MOSQ_ERR_DUPLICATE_PROPERTY, identifier, 1); } static void int16_prop_read_helper( int command, uint8_t *payload, int remaining_length, int rc_expected, int identifier, uint16_t value_expected) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.i16, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 3); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); } static void duplicate_int16_helper(int command, int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 6; /* Proplen = (Identifier + int16)*2 */ payload[1] = identifier; payload[2] = 1; payload[3] = 1; payload[4] = identifier; payload[5] = 0; payload[6] = 0; int16_prop_read_helper(command, payload, 7, MOSQ_ERR_DUPLICATE_PROPERTY, identifier, 1); } static void string_prop_read_helper( int command, uint8_t *payload, int remaining_length, int rc_expected, int identifier, const char *value_expected) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.s.len, strlen(value_expected)); CU_ASSERT_STRING_EQUAL(properties->value.s.v, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 1+2+strlen(value_expected)); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); } static void duplicate_string_helper(int command, int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = identifier; payload[2] = 0; payload[3] = 1; /* 1 length string */ payload[4] = 'h'; payload[5] = identifier; payload[6] = 0; payload[7] = 1; payload[8] = 'h'; string_prop_read_helper(command, payload, 9, MOSQ_ERR_DUPLICATE_PROPERTY, identifier, ""); } static void bad_string_helper(int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 6; payload[1] = identifier; payload[2] = 0; payload[3] = 3; /* 1 length string */ payload[4] = 'h'; payload[5] = 0; /* 0 in string not allowed */ payload[6] = 'h'; string_prop_read_helper(CMD_PUBLISH, payload, 7, MOSQ_ERR_MALFORMED_UTF8, identifier, ""); } static void binary_prop_read_helper( int command, uint8_t *payload, int remaining_length, int rc_expected, int identifier, const uint8_t *value_expected, int len_expected) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.bin.len, len_expected); CU_ASSERT_EQUAL(memcmp(properties->value.bin.v, value_expected, len_expected), 0); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 1+2+len_expected); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); } static void duplicate_binary_helper(int command, int identifier) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = identifier; payload[2] = 0; payload[3] = 1; /* 2 length binary */ payload[4] = 'h'; payload[5] = identifier; payload[6] = 0; payload[7] = 1; payload[8] = 'h'; string_prop_read_helper(command, payload, 9, MOSQ_ERR_DUPLICATE_PROPERTY, identifier, ""); } static void string_pair_prop_read_helper( uint8_t *payload, int remaining_length, int rc_expected, int identifier, const char *name_expected, const char *value_expected, bool expect_multiple) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->name.len, strlen(name_expected)); CU_ASSERT_EQUAL(properties->value.s.len, strlen(value_expected)); CU_ASSERT_STRING_EQUAL(properties->name.v, name_expected); CU_ASSERT_STRING_EQUAL(properties->value.s.v, value_expected); if(expect_multiple){ CU_ASSERT_PTR_NOT_NULL(properties->next); }else{ CU_ASSERT_PTR_NULL(properties->next); CU_ASSERT_EQUAL(property__get_length_all(properties), 1+2+strlen(name_expected)+2+strlen(value_expected)); } mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_NULL(properties); } static void varint_prop_read_helper( uint8_t *payload, int remaining_length, int rc_expected, int identifier, uint32_t value_expected) { struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(CMD_PUBLISH, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.varint, value_expected); CU_ASSERT_PTR_NULL(properties->next); CU_ASSERT_EQUAL(property__get_length_all(properties), packet__varint_bytes(value_expected)+1); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_NULL(properties); } static void packet_helper_reason_string_user_property(int command) { uint8_t payload[24] = {23, MQTT_PROP_REASON_STRING, 0, 6, 'r', 'e', 'a', 's', 'o', 'n', MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e'}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(properties); if(properties){ CU_ASSERT_PTR_NOT_NULL(properties->next); p = properties; CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_REASON_STRING); CU_ASSERT_STRING_EQUAL(p->value.s.v, "reason"); CU_ASSERT_EQUAL(p->value.s.len, strlen("reason")); p = p->next; if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); } mosquitto_property_free_all(&properties); } } /* ======================================================================== * NO PROPERTIES * ======================================================================== */ static void TEST_no_properties(void) { struct mosquitto__packet packet; mosquitto_property *properties = NULL; uint8_t payload[5]; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); packet.payload = payload; packet.remaining_length = 1; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 1); } static void TEST_truncated(void) { struct mosquitto__packet packet; mosquitto_property *properties = NULL; uint8_t payload[5]; int rc; /* Zero length packet */ memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); packet.payload = payload; packet.remaining_length = 0; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_PROTOCOL); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 0); /* Proplen > 0 but not enough data */ memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); payload[0] = 2; packet.payload = payload; packet.remaining_length = 1; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_PROTOCOL); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 1); /* Proplen > 0 but not enough data */ memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); payload[0] = 4; payload[1] = MQTT_PROP_PAYLOAD_FORMAT_INDICATOR; packet.payload = payload; packet.remaining_length = 2; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_PROTOCOL); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 2); } /* ======================================================================== * INVALID PROPERTY ID * ======================================================================== */ static void TEST_invalid_property_id(void) { struct mosquitto__packet packet; mosquitto_property *properties = NULL; uint8_t payload[5]; int rc; /* ID = 0 */ memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); payload[0] = 4; packet.payload = payload; packet.remaining_length = 2; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_MALFORMED_PACKET); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 2); /* ID = 4 */ memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); payload[0] = 4; payload[1] = 4; packet.payload = payload; packet.remaining_length = 2; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_MALFORMED_PACKET); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 2); } /* ======================================================================== * SINGLE PROPERTIES * ======================================================================== */ static void TEST_single_payload_format_indicator(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_PAYLOAD_FORMAT_INDICATOR; payload[2] = 1; byte_prop_read_helper(CMD_PUBLISH, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); } static void TEST_single_request_problem_information(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_REQUEST_PROBLEM_INFORMATION; payload[2] = 1; byte_prop_read_helper(CMD_CONNECT, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); } static void TEST_single_request_response_information(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_REQUEST_RESPONSE_INFORMATION; payload[2] = 1; byte_prop_read_helper(CMD_CONNECT, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); } static void TEST_single_maximum_qos(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_MAXIMUM_QOS; payload[2] = 1; byte_prop_read_helper(CMD_CONNACK, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_MAXIMUM_QOS, 1); } static void TEST_single_retain_available(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_RETAIN_AVAILABLE; payload[2] = 1; byte_prop_read_helper(CMD_CONNACK, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_RETAIN_AVAILABLE, 1); } static void TEST_single_wildcard_subscription_available(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_WILDCARD_SUB_AVAILABLE; payload[2] = 0; byte_prop_read_helper(CMD_CONNACK, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); } static void TEST_single_subscription_identifier_available(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE; payload[2] = 0; byte_prop_read_helper(CMD_CONNACK, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); } static void TEST_single_shared_subscription_available(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 2; /* Proplen = Identifier + byte */ payload[1] = MQTT_PROP_SHARED_SUB_AVAILABLE; payload[2] = 1; byte_prop_read_helper(CMD_CONNACK, payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_SHARED_SUB_AVAILABLE, 1); } static void TEST_single_message_expiry_interval(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 5; /* Proplen = Identifier + int32 */ payload[1] = MQTT_PROP_MESSAGE_EXPIRY_INTERVAL; payload[2] = 0x12; payload[3] = 0x23; payload[4] = 0x34; payload[5] = 0x45; int32_prop_read_helper(CMD_WILL, payload, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 0x12233445); } static void TEST_single_session_expiry_interval(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 5; /* Proplen = Identifier + int32 */ payload[1] = MQTT_PROP_SESSION_EXPIRY_INTERVAL; payload[2] = 0x45; payload[3] = 0x34; payload[4] = 0x23; payload[5] = 0x12; int32_prop_read_helper(CMD_CONNACK, payload, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 0x45342312); } static void TEST_single_will_delay_interval(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 5; /* Proplen = Identifier + int32 */ payload[1] = MQTT_PROP_WILL_DELAY_INTERVAL; payload[2] = 0x45; payload[3] = 0x34; payload[4] = 0x23; payload[5] = 0x12; int32_prop_read_helper(CMD_WILL, payload, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_WILL_DELAY_INTERVAL, 0x45342312); } static void TEST_single_maximum_packet_size(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 5; /* Proplen = Identifier + int32 */ payload[1] = MQTT_PROP_MAXIMUM_PACKET_SIZE; payload[2] = 0x45; payload[3] = 0x34; payload[4] = 0x23; payload[5] = 0x12; int32_prop_read_helper(CMD_CONNECT, payload, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_MAXIMUM_PACKET_SIZE, 0x45342312); } static void TEST_single_server_keep_alive(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 3; /* Proplen = Identifier + int16 */ payload[1] = MQTT_PROP_SERVER_KEEP_ALIVE; payload[2] = 0x45; payload[3] = 0x34; int16_prop_read_helper(CMD_CONNACK, payload, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_SERVER_KEEP_ALIVE, 0x4534); } static void TEST_single_receive_maximum(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 3; /* Proplen = Identifier + int16 */ payload[1] = MQTT_PROP_RECEIVE_MAXIMUM; payload[2] = 0x68; payload[3] = 0x42; int16_prop_read_helper(CMD_CONNACK, payload, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_RECEIVE_MAXIMUM, 0x6842); } static void TEST_single_topic_alias_maximum(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 3; /* Proplen = Identifier + int16 */ payload[1] = MQTT_PROP_TOPIC_ALIAS_MAXIMUM; payload[2] = 0x68; payload[3] = 0x42; int16_prop_read_helper(CMD_CONNECT, payload, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 0x6842); } static void TEST_single_topic_alias(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 3; /* Proplen = Identifier + int16 */ payload[1] = MQTT_PROP_TOPIC_ALIAS; payload[2] = 0x68; payload[3] = 0x42; int16_prop_read_helper(CMD_PUBLISH, payload, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_TOPIC_ALIAS, 0x6842); } static void TEST_single_content_type(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_CONTENT_TYPE; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_PUBLISH, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_CONTENT_TYPE, "hello"); } static void TEST_single_response_topic(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_RESPONSE_TOPIC; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_WILL, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_RESPONSE_TOPIC, "hello"); } static void TEST_single_assigned_client_identifier(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_CONNACK, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "hello"); } static void TEST_single_authentication_method(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_AUTHENTICATION_METHOD; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_AUTH, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_AUTHENTICATION_METHOD, "hello"); } static void TEST_single_response_information(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_RESPONSE_INFORMATION; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_CONNACK, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_RESPONSE_INFORMATION, "hello"); } static void TEST_single_server_reference(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_SERVER_REFERENCE; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_CONNACK, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_SERVER_REFERENCE, "hello"); } static void TEST_single_reason_string(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_REASON_STRING; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 'h'; payload[5] = 'e'; payload[6] = 'l'; payload[7] = 'l'; payload[8] = 'o'; string_prop_read_helper(CMD_PUBCOMP, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_REASON_STRING, "hello"); } static void TEST_single_correlation_data(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_CORRELATION_DATA; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 1; payload[5] = 'e'; payload[6] = 0; payload[7] = 'l'; payload[8] = 9; binary_prop_read_helper(CMD_PUBLISH, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_CORRELATION_DATA, &payload[4], 5); } static void TEST_single_authentication_data(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 8; payload[1] = MQTT_PROP_AUTHENTICATION_DATA; payload[2] = 0x00; payload[3] = 0x05; payload[4] = 1; payload[5] = 'e'; payload[6] = 0; payload[7] = 'l'; payload[8] = 9; binary_prop_read_helper(CMD_CONNECT, payload, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_AUTHENTICATION_DATA, &payload[4], 5); } static void TEST_single_user_property(void) { uint8_t payload[20]; payload[0] = 9; payload[1] = MQTT_PROP_USER_PROPERTY; payload[2] = 0; payload[3] = 2; payload[4] = 'z'; payload[5] = 'a'; payload[6] = 0; payload[7] = 2; payload[8] = 'b'; payload[9] = 'c'; string_pair_prop_read_helper(payload, 10, MOSQ_ERR_SUCCESS, MQTT_PROP_USER_PROPERTY, "za", "bc", false); } static void TEST_single_subscription_identifier(void) { uint8_t payload[20]; payload[0] = 2; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0; varint_prop_read_helper(payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 0); payload[0] = 2; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0x7F; varint_prop_read_helper(payload, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 127); payload[0] = 3; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0x80; payload[3] = 0x01; varint_prop_read_helper(payload, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 128); payload[0] = 3; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0xFF; payload[3] = 0x7F; varint_prop_read_helper(payload, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 16383); payload[0] = 4; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0x80; payload[3] = 0x80; payload[4] = 0x01; varint_prop_read_helper(payload, 5, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 16384); payload[0] = 4; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0xFF; payload[3] = 0xFF; payload[4] = 0x7F; varint_prop_read_helper(payload, 5, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 2097151); payload[0] = 5; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0x80; payload[3] = 0x80; payload[4] = 0x80; payload[5] = 0x01; varint_prop_read_helper(payload, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 2097152); payload[0] = 5; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0xFF; payload[3] = 0xFF; payload[4] = 0xFF; payload[5] = 0x7F; varint_prop_read_helper(payload, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 268435455); } /* ======================================================================== * DUPLICATE PROPERTIES * ======================================================================== */ static void TEST_duplicate_payload_format_indicator(void) { duplicate_byte_helper(CMD_PUBLISH, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); } static void TEST_duplicate_request_problem_information(void) { duplicate_byte_helper(CMD_CONNECT, MQTT_PROP_REQUEST_PROBLEM_INFORMATION); } static void TEST_duplicate_request_response_information(void) { duplicate_byte_helper(CMD_CONNECT, MQTT_PROP_REQUEST_RESPONSE_INFORMATION); } static void TEST_duplicate_maximum_qos(void) { duplicate_byte_helper(CMD_CONNACK, MQTT_PROP_MAXIMUM_QOS); } static void TEST_duplicate_retain_available(void) { duplicate_byte_helper(CMD_CONNACK, MQTT_PROP_RETAIN_AVAILABLE); } static void TEST_duplicate_wildcard_subscription_available(void) { duplicate_byte_helper(CMD_CONNACK, MQTT_PROP_WILDCARD_SUB_AVAILABLE); } static void TEST_duplicate_subscription_identifier_available(void) { duplicate_byte_helper(CMD_CONNACK, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); } static void TEST_duplicate_shared_subscription_available(void) { duplicate_byte_helper(CMD_CONNACK, MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_duplicate_message_expiry_interval(void) { duplicate_int32_helper(CMD_PUBLISH, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); } static void TEST_duplicate_session_expiry_interval(void) { duplicate_int32_helper(CMD_DISCONNECT, MQTT_PROP_SESSION_EXPIRY_INTERVAL); } static void TEST_duplicate_will_delay_interval(void) { duplicate_int32_helper(CMD_WILL, MQTT_PROP_WILL_DELAY_INTERVAL); } static void TEST_duplicate_maximum_packet_size(void) { duplicate_int32_helper(CMD_CONNECT, MQTT_PROP_MAXIMUM_PACKET_SIZE); } static void TEST_duplicate_server_keep_alive(void) { duplicate_int16_helper(CMD_CONNACK, MQTT_PROP_SERVER_KEEP_ALIVE); } static void TEST_duplicate_receive_maximum(void) { duplicate_int16_helper(CMD_CONNACK, MQTT_PROP_RECEIVE_MAXIMUM); } static void TEST_duplicate_topic_alias_maximum(void) { duplicate_int16_helper(CMD_CONNECT, MQTT_PROP_TOPIC_ALIAS_MAXIMUM); } static void TEST_duplicate_topic_alias(void) { duplicate_int16_helper(CMD_PUBLISH, MQTT_PROP_TOPIC_ALIAS); } static void TEST_duplicate_content_type(void) { duplicate_string_helper(CMD_PUBLISH, MQTT_PROP_CONTENT_TYPE); } static void TEST_duplicate_response_topic(void) { duplicate_string_helper(CMD_PUBLISH, MQTT_PROP_RESPONSE_TOPIC); } static void TEST_duplicate_assigned_client_identifier(void) { duplicate_string_helper(CMD_CONNACK, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); } static void TEST_duplicate_authentication_method(void) { duplicate_string_helper(CMD_AUTH, MQTT_PROP_AUTHENTICATION_METHOD); } static void TEST_duplicate_response_information(void) { duplicate_string_helper(CMD_CONNACK, MQTT_PROP_RESPONSE_INFORMATION); } static void TEST_duplicate_server_reference(void) { duplicate_string_helper(CMD_CONNACK, MQTT_PROP_SERVER_REFERENCE); } static void TEST_duplicate_reason_string(void) { duplicate_string_helper(CMD_PUBACK, MQTT_PROP_REASON_STRING); } static void TEST_duplicate_correlation_data(void) { duplicate_binary_helper(CMD_PUBLISH, MQTT_PROP_CORRELATION_DATA); } static void TEST_duplicate_authentication_data(void) { duplicate_binary_helper(CMD_CONNACK, MQTT_PROP_AUTHENTICATION_DATA); } static void TEST_duplicate_user_property(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 18; /* Proplen = (Identifier + byte)*2 */ payload[1] = MQTT_PROP_USER_PROPERTY; payload[2] = 0; payload[3] = 2; payload[4] = 'a'; payload[5] = 'b'; payload[6] = 0; payload[7] = 2; payload[8] = 'g'; payload[9] = 'h'; payload[10] = MQTT_PROP_USER_PROPERTY; payload[11] = 0; payload[12] = 2; payload[13] = 'c'; payload[14] = 'd'; payload[15] = 0; payload[16] = 2; payload[17] = 'e'; payload[18] = 'f'; string_pair_prop_read_helper(payload, 19, MOSQ_ERR_SUCCESS, MQTT_PROP_USER_PROPERTY, "ab", "gh", true); } static void TEST_duplicate_subscription_identifier(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 4; /* Proplen = (Identifier + byte)*2 */ payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0x80; payload[3] = 0x02; payload[4] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[5] = 0x04; varint_prop_read_helper(payload, 5, MOSQ_ERR_PROTOCOL, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 0); } /* ======================================================================== * BAD PROPERTY VALUES * ======================================================================== */ static void TEST_bad_request_problem_information(void) { bad_byte_helper(CMD_CONNECT, MQTT_PROP_REQUEST_PROBLEM_INFORMATION); } static void TEST_bad_request_response_information(void) { bad_byte_helper(CMD_CONNECT, MQTT_PROP_REQUEST_RESPONSE_INFORMATION); } static void TEST_bad_maximum_qos(void) { bad_byte_helper(CMD_CONNACK, MQTT_PROP_MAXIMUM_QOS); } static void TEST_bad_retain_available(void) { bad_byte_helper(CMD_CONNACK, MQTT_PROP_RETAIN_AVAILABLE); } static void TEST_bad_wildcard_sub_available(void) { bad_byte_helper(CMD_CONNACK, MQTT_PROP_WILDCARD_SUB_AVAILABLE); } static void TEST_bad_subscription_id_available(void) { bad_byte_helper(CMD_CONNACK, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); } static void TEST_bad_shared_sub_available(void) { bad_byte_helper(CMD_CONNACK, MQTT_PROP_SHARED_SUB_AVAILABLE); } static void TEST_bad_maximum_packet_size(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 5; /* Proplen = Identifier + int32 */ payload[1] = MQTT_PROP_MAXIMUM_PACKET_SIZE; payload[2] = 0; payload[3] = 0; payload[4] = 0; payload[5] = 0; /* 0 is invalid */ int32_prop_read_helper(CMD_CONNACK, payload, 6, MOSQ_ERR_PROTOCOL, MQTT_PROP_MAXIMUM_PACKET_SIZE, 0); } static void TEST_bad_receive_maximum(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 3; /* Proplen = Identifier + int16 */ payload[1] = MQTT_PROP_RECEIVE_MAXIMUM; payload[2] = 0; payload[3] = 0; /* 0 is invalid */ int32_prop_read_helper(CMD_CONNECT, payload, 4, MOSQ_ERR_PROTOCOL, MQTT_PROP_RECEIVE_MAXIMUM, 0); } static void TEST_bad_topic_alias(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 3; /* Proplen = Identifier + int16 */ payload[1] = MQTT_PROP_TOPIC_ALIAS; payload[2] = 0; payload[3] = 0; /* 0 is invalid */ int32_prop_read_helper(CMD_PUBLISH, payload, 4, MOSQ_ERR_PROTOCOL, MQTT_PROP_TOPIC_ALIAS, 0); } static void TEST_bad_content_type(void) { bad_string_helper(MQTT_PROP_CONTENT_TYPE); } static void TEST_bad_subscription_identifier(void) { uint8_t payload[20]; memset(&payload, 0, sizeof(payload)); payload[0] = 6; payload[1] = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; payload[2] = 0xFF; payload[3] = 0xFF; payload[4] = 0xFF; payload[5] = 0xFF; payload[6] = 0x01; varint_prop_read_helper(payload, 7, MOSQ_ERR_PROTOCOL, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 0); } /* ======================================================================== * CONTROL PACKET TESTS * ======================================================================== */ static void TEST_packet_connect(void) { uint8_t payload[] = {0, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 0x12, 0x45, 0x00, 0x00, MQTT_PROP_RECEIVE_MAXIMUM, 0x00, 0x05, MQTT_PROP_MAXIMUM_PACKET_SIZE, 0x12, 0x45, 0x00, 0x00, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 0x00, 0x02, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1, MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e', MQTT_PROP_AUTHENTICATION_METHOD, 0x00, 0x04, 'n', 'o', 'n', 'e', MQTT_PROP_AUTHENTICATION_DATA, 0x00, 0x02, 1, 2}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); p = properties; CU_ASSERT_PTR_NOT_NULL(properties); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SESSION_EXPIRY_INTERVAL); CU_ASSERT_EQUAL(p->value.i32, 0x12450000); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_RECEIVE_MAXIMUM); CU_ASSERT_EQUAL(p->value.i16, 0x0005); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_MAXIMUM_PACKET_SIZE); CU_ASSERT_EQUAL(p->value.i32, 0x12450000); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_TOPIC_ALIAS_MAXIMUM); CU_ASSERT_EQUAL(p->value.i16, 0x0002); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_REQUEST_PROBLEM_INFORMATION); CU_ASSERT_EQUAL(p->value.i8, 1); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_REQUEST_RESPONSE_INFORMATION); CU_ASSERT_EQUAL(p->value.i8, 1); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_AUTHENTICATION_METHOD); CU_ASSERT_STRING_EQUAL(p->value.s.v, "none"); CU_ASSERT_EQUAL(p->value.s.len, strlen("none")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_AUTHENTICATION_DATA); CU_ASSERT_EQUAL(p->value.bin.v[0], 1); CU_ASSERT_EQUAL(p->value.bin.v[1], 2); CU_ASSERT_EQUAL(p->value.s.len, 2); } } } } } } } } } mosquitto_property_free_all(&properties); } static void TEST_packet_connack(void) { uint8_t payload[] = {0, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 0x12, 0x45, 0x00, 0x00, MQTT_PROP_RECEIVE_MAXIMUM, 0x00, 0x05, MQTT_PROP_MAXIMUM_QOS, 1, MQTT_PROP_RETAIN_AVAILABLE, 0, MQTT_PROP_MAXIMUM_PACKET_SIZE, 0x12, 0x45, 0x00, 0x00, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, 0x00, 0x02, 'a', 'b', MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 0x00, 0x02, MQTT_PROP_REASON_STRING, 0, 6, 'r', 'e', 'a', 's', 'o', 'n', MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e', MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0, MQTT_PROP_SHARED_SUB_AVAILABLE, 0, MQTT_PROP_SERVER_KEEP_ALIVE, 0x00, 0xFF, MQTT_PROP_RESPONSE_INFORMATION, 0x00, 0x03, 'r', 's', 'p', MQTT_PROP_SERVER_REFERENCE, 0x00, 0x04, 's', 'e', 'r', 'v', MQTT_PROP_AUTHENTICATION_METHOD, 0x00, 0x04, 'n', 'o', 'n', 'e', MQTT_PROP_AUTHENTICATION_DATA, 0x00, 0x02, 1, 2}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_CONNACK, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(properties); p = properties; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SESSION_EXPIRY_INTERVAL); CU_ASSERT_EQUAL(p->value.i32, 0x12450000); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_RECEIVE_MAXIMUM); CU_ASSERT_EQUAL(p->value.i16, 0x0005); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_MAXIMUM_QOS); CU_ASSERT_EQUAL(p->value.i8, 1); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_RETAIN_AVAILABLE); CU_ASSERT_EQUAL(p->value.i8, 0); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_MAXIMUM_PACKET_SIZE); CU_ASSERT_EQUAL(p->value.i32, 0x12450000); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER); CU_ASSERT_STRING_EQUAL(p->value.s.v, "ab"); CU_ASSERT_EQUAL(p->value.s.len, strlen("ab")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_TOPIC_ALIAS_MAXIMUM); CU_ASSERT_EQUAL(p->value.i16, 0x0002); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_REASON_STRING); CU_ASSERT_STRING_EQUAL(p->value.s.v, "reason"); CU_ASSERT_EQUAL(p->value.s.len, strlen("reason")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_WILDCARD_SUB_AVAILABLE); CU_ASSERT_EQUAL(p->value.i8, 0); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE); CU_ASSERT_EQUAL(p->value.i8, 0); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SHARED_SUB_AVAILABLE); CU_ASSERT_EQUAL(p->value.i8, 0); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SERVER_KEEP_ALIVE); CU_ASSERT_EQUAL(p->value.i16, 0x00FF); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_RESPONSE_INFORMATION); CU_ASSERT_STRING_EQUAL(p->value.s.v, "rsp"); CU_ASSERT_EQUAL(p->value.s.len, strlen("rsp")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SERVER_REFERENCE); CU_ASSERT_STRING_EQUAL(p->value.s.v, "serv"); CU_ASSERT_EQUAL(p->value.s.len, strlen("serv")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_AUTHENTICATION_METHOD); CU_ASSERT_STRING_EQUAL(p->value.s.v, "none"); CU_ASSERT_EQUAL(p->value.s.len, strlen("none")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_AUTHENTICATION_DATA); CU_ASSERT_EQUAL(p->value.bin.v[0], 1); CU_ASSERT_EQUAL(p->value.bin.v[1], 2); CU_ASSERT_EQUAL(p->value.s.len, 2); } } } } } } } } } } } } } } } } } mosquitto_property_free_all(&properties); } static void TEST_packet_publish(void) { uint8_t payload[] = {0, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 0x12, 0x45, 0x00, 0x00, MQTT_PROP_TOPIC_ALIAS, 0x00, 0x02, MQTT_PROP_RESPONSE_TOPIC, 0, 6, 'r', 'e', 's', 'p', 'o', 'n', MQTT_PROP_CORRELATION_DATA, 0x00, 0x02, 1, 2, MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e', MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 0x04, MQTT_PROP_CONTENT_TYPE, 0, 5, 'e', 'm', 'p', 't', 'y'}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_PUBLISH, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); p = properties; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR); CU_ASSERT_EQUAL(p->value.i8, 1); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL); CU_ASSERT_EQUAL(p->value.i32, 0x12450000); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_TOPIC_ALIAS); CU_ASSERT_EQUAL(p->value.i16, 0x0002); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_RESPONSE_TOPIC); CU_ASSERT_STRING_EQUAL(p->value.s.v, "respon"); CU_ASSERT_EQUAL(p->value.s.len, strlen("respon")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_CORRELATION_DATA); CU_ASSERT_EQUAL(p->value.bin.v[0], 1); CU_ASSERT_EQUAL(p->value.bin.v[1], 2); CU_ASSERT_EQUAL(p->value.bin.len, 2); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SUBSCRIPTION_IDENTIFIER); CU_ASSERT_EQUAL(p->value.varint, 0x00000004); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_CONTENT_TYPE); CU_ASSERT_STRING_EQUAL(p->value.s.v, "empty"); CU_ASSERT_EQUAL(p->value.s.len, strlen("empty")); } } } } } } } } mosquitto_property_free_all(&properties); } static void TEST_packet_puback(void) { packet_helper_reason_string_user_property(CMD_PUBACK); } static void TEST_packet_pubrec(void) { packet_helper_reason_string_user_property(CMD_PUBREC); } static void TEST_packet_pubrel(void) { packet_helper_reason_string_user_property(CMD_PUBREL); } static void TEST_packet_pubcomp(void) { packet_helper_reason_string_user_property(CMD_PUBCOMP); } static void TEST_packet_subscribe(void) { uint8_t payload[] = {0, MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e', MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 0x04}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_SUBSCRIBE, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); p = properties; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SUBSCRIPTION_IDENTIFIER); CU_ASSERT_EQUAL(p->value.varint, 0x00000004); } } mosquitto_property_free_all(&properties); } static void TEST_packet_suback(void) { packet_helper_reason_string_user_property(CMD_SUBACK); } static void TEST_packet_unsubscribe(void) { uint8_t payload[] = {0, MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e'}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_UNSUBSCRIBE, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); p = properties; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); } mosquitto_property_free_all(&properties); } static void TEST_packet_unsuback(void) { packet_helper_reason_string_user_property(CMD_UNSUBACK); } static void TEST_packet_disconnect(void) { uint8_t payload[] = {0, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 0x12, 0x45, 0x00, 0x00, MQTT_PROP_REASON_STRING, 0, 6, 'r', 'e', 'a', 's', 'o', 'n', MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e'}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_DISCONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); p = properties; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_SESSION_EXPIRY_INTERVAL); CU_ASSERT_EQUAL(p->value.i32, 0x12450000); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_REASON_STRING); CU_ASSERT_STRING_EQUAL(p->value.s.v, "reason"); CU_ASSERT_EQUAL(p->value.s.len, strlen("reason")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); } } } mosquitto_property_free_all(&properties); } static void TEST_packet_auth(void) { uint8_t payload[] = {0, MQTT_PROP_AUTHENTICATION_METHOD, 0x00, 0x04, 'n', 'o', 'n', 'e', MQTT_PROP_AUTHENTICATION_DATA, 0x00, 0x02, 1, 2, MQTT_PROP_REASON_STRING, 0, 6, 'r', 'e', 'a', 's', 'o', 'n', MQTT_PROP_USER_PROPERTY, 0, 4, 'n', 'a', 'm', 'e', 0, 5, 'v', 'a', 'l', 'u', 'e'}; struct mosquitto__packet packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = sizeof(payload);; rc = property__read_all(CMD_AUTH, &packet, &properties); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); p = properties; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_AUTHENTICATION_METHOD); CU_ASSERT_STRING_EQUAL(p->value.s.v, "none"); CU_ASSERT_EQUAL(p->value.s.len, strlen("none")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_AUTHENTICATION_DATA); CU_ASSERT_EQUAL(p->value.bin.v[0], 1); CU_ASSERT_EQUAL(p->value.bin.v[1], 2); CU_ASSERT_EQUAL(p->value.s.len, 2); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NOT_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_REASON_STRING); CU_ASSERT_STRING_EQUAL(p->value.s.v, "reason"); CU_ASSERT_EQUAL(p->value.s.len, strlen("reason")); p = p->next; CU_ASSERT_PTR_NOT_NULL(p); if(p){ CU_ASSERT_PTR_NULL(p->next); CU_ASSERT_EQUAL(p->identifier, MQTT_PROP_USER_PROPERTY); CU_ASSERT_STRING_EQUAL(p->value.s.v, "value"); CU_ASSERT_EQUAL(p->value.s.len, strlen("value")); CU_ASSERT_STRING_EQUAL(p->name.v, "name"); CU_ASSERT_EQUAL(p->name.len, strlen("name")); } } } } mosquitto_property_free_all(&properties); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_property_read_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Property read", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Property read test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Truncated packet", TEST_truncated) || !CU_add_test(test_suite, "Invalid property ID", TEST_invalid_property_id) || !CU_add_test(test_suite, "No properties", TEST_no_properties) || !CU_add_test(test_suite, "Single Payload Format Indicator", TEST_single_payload_format_indicator) || !CU_add_test(test_suite, "Single Request Problem Information", TEST_single_request_problem_information) || !CU_add_test(test_suite, "Single Request Response Information", TEST_single_request_response_information) || !CU_add_test(test_suite, "Single Maximum QoS", TEST_single_maximum_qos) || !CU_add_test(test_suite, "Single Retain Available", TEST_single_retain_available) || !CU_add_test(test_suite, "Single Wildcard Subscription Available", TEST_single_wildcard_subscription_available) || !CU_add_test(test_suite, "Single Subscription Identifier Available", TEST_single_subscription_identifier_available) || !CU_add_test(test_suite, "Single Shared Subscription Available", TEST_single_shared_subscription_available) || !CU_add_test(test_suite, "Single Message Expiry Interval", TEST_single_message_expiry_interval) || !CU_add_test(test_suite, "Single Session Expiry Interval", TEST_single_session_expiry_interval) || !CU_add_test(test_suite, "Single Will Delay Interval", TEST_single_will_delay_interval) || !CU_add_test(test_suite, "Single Maximum Packet Size", TEST_single_maximum_packet_size) || !CU_add_test(test_suite, "Single Server Keep Alive", TEST_single_server_keep_alive) || !CU_add_test(test_suite, "Single Receive Maximum", TEST_single_receive_maximum) || !CU_add_test(test_suite, "Single Topic Alias Maximum", TEST_single_topic_alias_maximum) || !CU_add_test(test_suite, "Single Topic Alias", TEST_single_topic_alias) || !CU_add_test(test_suite, "Single Content Type", TEST_single_content_type) || !CU_add_test(test_suite, "Single Response Topic", TEST_single_response_topic) || !CU_add_test(test_suite, "Single Assigned Client Identifier", TEST_single_assigned_client_identifier) || !CU_add_test(test_suite, "Single Authentication Method", TEST_single_authentication_method) || !CU_add_test(test_suite, "Single Response Information", TEST_single_response_information) || !CU_add_test(test_suite, "Single Server Reference", TEST_single_server_reference) || !CU_add_test(test_suite, "Single Reason String", TEST_single_reason_string) || !CU_add_test(test_suite, "Single Correlation Data", TEST_single_correlation_data) || !CU_add_test(test_suite, "Single Authentication Data", TEST_single_authentication_data) || !CU_add_test(test_suite, "Single User Property", TEST_single_user_property) || !CU_add_test(test_suite, "Single Subscription Identifier", TEST_single_subscription_identifier) || !CU_add_test(test_suite, "Duplicate Payload Format Indicator", TEST_duplicate_payload_format_indicator) || !CU_add_test(test_suite, "Duplicate Request Problem Information", TEST_duplicate_request_problem_information) || !CU_add_test(test_suite, "Duplicate Request Response Information", TEST_duplicate_request_response_information) || !CU_add_test(test_suite, "Duplicate Maximum QoS", TEST_duplicate_maximum_qos) || !CU_add_test(test_suite, "Duplicate Retain Available", TEST_duplicate_retain_available) || !CU_add_test(test_suite, "Duplicate Wildcard Subscription Available", TEST_duplicate_wildcard_subscription_available) || !CU_add_test(test_suite, "Duplicate Subscription Identifier Available", TEST_duplicate_subscription_identifier_available) || !CU_add_test(test_suite, "Duplicate Shared Subscription Available", TEST_duplicate_shared_subscription_available) || !CU_add_test(test_suite, "Duplicate Message Expiry Interval", TEST_duplicate_message_expiry_interval) || !CU_add_test(test_suite, "Duplicate Session Expiry Interval", TEST_duplicate_session_expiry_interval) || !CU_add_test(test_suite, "Duplicate Will Delay Interval", TEST_duplicate_will_delay_interval) || !CU_add_test(test_suite, "Duplicate Maximum Packet Size", TEST_duplicate_maximum_packet_size) || !CU_add_test(test_suite, "Duplicate Server Keep Alive", TEST_duplicate_server_keep_alive) || !CU_add_test(test_suite, "Duplicate Receive Maximum", TEST_duplicate_receive_maximum) || !CU_add_test(test_suite, "Duplicate Topic Alias Maximum", TEST_duplicate_topic_alias_maximum) || !CU_add_test(test_suite, "Duplicate Topic Alias", TEST_duplicate_topic_alias) || !CU_add_test(test_suite, "Duplicate Content Type", TEST_duplicate_content_type) || !CU_add_test(test_suite, "Duplicate Response Topic", TEST_duplicate_response_topic) || !CU_add_test(test_suite, "Duplicate Assigned Client ID", TEST_duplicate_assigned_client_identifier) || !CU_add_test(test_suite, "Duplicate Authentication Method", TEST_duplicate_authentication_method) || !CU_add_test(test_suite, "Duplicate Response Information", TEST_duplicate_response_information) || !CU_add_test(test_suite, "Duplicate Server Reference", TEST_duplicate_server_reference) || !CU_add_test(test_suite, "Duplicate Reason String", TEST_duplicate_reason_string) || !CU_add_test(test_suite, "Duplicate Correlation Data", TEST_duplicate_correlation_data) || !CU_add_test(test_suite, "Duplicate Authentication Data", TEST_duplicate_authentication_data) || !CU_add_test(test_suite, "Duplicate User Property", TEST_duplicate_user_property) || !CU_add_test(test_suite, "Duplicate Subscription Identifier", TEST_duplicate_subscription_identifier) || !CU_add_test(test_suite, "Bad Request Problem Information", TEST_bad_request_problem_information) || !CU_add_test(test_suite, "Bad Request Response Information", TEST_bad_request_response_information) || !CU_add_test(test_suite, "Bad Maximum QoS", TEST_bad_maximum_qos) || !CU_add_test(test_suite, "Bad Retain Available", TEST_bad_retain_available) || !CU_add_test(test_suite, "Bad Wildcard Subscription Available", TEST_bad_wildcard_sub_available) || !CU_add_test(test_suite, "Bad Subscription Identifier Available", TEST_bad_subscription_id_available) || !CU_add_test(test_suite, "Bad Shared Subscription Available", TEST_bad_shared_sub_available) || !CU_add_test(test_suite, "Bad Maximum Packet Size", TEST_bad_maximum_packet_size) || !CU_add_test(test_suite, "Bad Receive Maximum", TEST_bad_receive_maximum) || !CU_add_test(test_suite, "Bad Topic Alias", TEST_bad_topic_alias) || !CU_add_test(test_suite, "Bad Content Type", TEST_bad_content_type) || !CU_add_test(test_suite, "Bad Subscription Identifier", TEST_bad_subscription_identifier) || !CU_add_test(test_suite, "Packet CONNECT", TEST_packet_connect) || !CU_add_test(test_suite, "Packet CONNACK", TEST_packet_connack) || !CU_add_test(test_suite, "Packet PUBLISH", TEST_packet_publish) || !CU_add_test(test_suite, "Packet PUBACK", TEST_packet_puback) || !CU_add_test(test_suite, "Packet PUBREC", TEST_packet_pubrec) || !CU_add_test(test_suite, "Packet PUBREL", TEST_packet_pubrel) || !CU_add_test(test_suite, "Packet PUBCOMP", TEST_packet_pubcomp) || !CU_add_test(test_suite, "Packet SUBSCRIBE", TEST_packet_subscribe) || !CU_add_test(test_suite, "Packet SUBACK", TEST_packet_suback) || !CU_add_test(test_suite, "Packet UNSUBSCRIBE", TEST_packet_unsubscribe) || !CU_add_test(test_suite, "Packet UNSUBACK", TEST_packet_unsuback) || !CU_add_test(test_suite, "Packet DISCONNECT", TEST_packet_disconnect) || !CU_add_test(test_suite, "Packet AUTH", TEST_packet_auth) ){ printf("Error adding Property read CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/persist_read_test.c0000664000175000017500000006126513626052637020464 0ustar rogerroger/* Tests for persistence. * * FIXME - these need to be aggressive about finding failures, at the moment * they are just confirming that good behaviour works. */ #include #include #define WITH_BROKER #define WITH_PERSISTENCE #include "mosquitto_broker_internal.h" #include "persist.h" #include "property_mosq.h" uint64_t last_retained; char *last_sub = NULL; int last_qos; uint32_t last_identifier; static void TEST_persistence_disabled(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void TEST_empty_file(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/empty.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void TEST_corrupt_header(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/corrupt-header-short.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, 1); config.persistence_filepath = "files/persist_read/corrupt-header-long.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, 1); } static void TEST_unsupported_version(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/unsupported-version.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, 1); } static void TEST_v3_config_ok(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-cfg.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x7856341200000000); } static void TEST_v4_config_ok(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v4-cfg.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x7856341200000000); } static void TEST_v3_config_truncated(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-cfg-truncated.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, 1); CU_ASSERT_EQUAL(db.last_db_id, 0); } static void TEST_v3_config_bad_dbid(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-cfg-bad-dbid.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, 1); CU_ASSERT_EQUAL(db.last_db_id, 0); } static void TEST_v3_bad_chunk(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-bad-chunk.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x17); } static void TEST_v3_message_store(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-message-store.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.msg_store_count, 1); CU_ASSERT_EQUAL(db.msg_store_bytes, 7); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_EQUAL(db.msg_store->db_id, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->mid, 0); CU_ASSERT_EQUAL(db.msg_store->qos, 2); CU_ASSERT_EQUAL(db.msg_store->retain, 1); CU_ASSERT_PTR_NOT_NULL(db.msg_store->topic); if(db.msg_store->topic){ CU_ASSERT_STRING_EQUAL(db.msg_store->topic, "topic"); } CU_ASSERT_EQUAL(db.msg_store->payloadlen, 7); if(db.msg_store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(db.msg_store), "payload", 7); } } } static void TEST_v3_client(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-client.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NULL(context->msgs_in.inflight); CU_ASSERT_PTR_NULL(context->msgs_out.inflight); CU_ASSERT_EQUAL(context->last_mid, 0x5287); } } static void TEST_v3_client_message(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-client-message.test-db"; config.max_inflight_messages = 20; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight); if(context->msgs_out.inflight){ CU_ASSERT_PTR_NULL(context->msgs_out.inflight->next); CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight->store); if(context->msgs_out.inflight->store){ CU_ASSERT_EQUAL(context->msgs_out.inflight->store->ref_count, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->store->source_id, "source_id"); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->source_mid, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->mid, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->qos, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->retain, 1); CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight->store->topic); if(context->msgs_out.inflight->store->topic){ CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->store->topic, "topic"); } CU_ASSERT_EQUAL(context->msgs_out.inflight->store->payloadlen, 7); if(context->msgs_out.inflight->store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(context->msgs_out.inflight->store), "payload", 7); } } CU_ASSERT_EQUAL(context->msgs_out.inflight->mid, 0x73); CU_ASSERT_EQUAL(context->msgs_out.inflight->qos, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->retain, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->direction, mosq_md_out); CU_ASSERT_EQUAL(context->msgs_out.inflight->state, mosq_ms_wait_for_puback); CU_ASSERT_EQUAL(context->msgs_out.inflight->dup, 0); CU_ASSERT_PTR_NULL(context->msgs_out.inflight->properties); } } } static void TEST_v3_retain(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; last_retained = 0; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-retain.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.msg_store_count, 1); CU_ASSERT_EQUAL(db.msg_store_bytes, 7); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_EQUAL(db.msg_store->db_id, 0x54); CU_ASSERT_STRING_EQUAL(db.msg_store->source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->mid, 0); CU_ASSERT_EQUAL(db.msg_store->qos, 2); CU_ASSERT_EQUAL(db.msg_store->retain, 1); CU_ASSERT_PTR_NOT_NULL(db.msg_store->topic); if(db.msg_store->topic){ CU_ASSERT_STRING_EQUAL(db.msg_store->topic, "topic"); } CU_ASSERT_EQUAL(db.msg_store->payloadlen, 7); if(db.msg_store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(db.msg_store), "payload", 7); } } CU_ASSERT_EQUAL(last_retained, 0x54); } static void TEST_v3_sub(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; last_sub = NULL; last_qos = -1; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v3-sub.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NOT_NULL(last_sub); if(last_sub){ CU_ASSERT_STRING_EQUAL(last_sub, "subscription") free(last_sub); } CU_ASSERT_EQUAL(last_qos, 1); } } static void TEST_v4_message_store(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v4-message-store.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.msg_store_count, 1); CU_ASSERT_EQUAL(db.msg_store_bytes, 7); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_EQUAL(db.msg_store->db_id, 0xFEDCBA9876543210); CU_ASSERT_STRING_EQUAL(db.msg_store->source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->source_mid, 0x88); CU_ASSERT_EQUAL(db.msg_store->mid, 0); CU_ASSERT_EQUAL(db.msg_store->qos, 1); CU_ASSERT_EQUAL(db.msg_store->retain, 0); CU_ASSERT_PTR_NOT_NULL(db.msg_store->topic); if(db.msg_store->topic){ CU_ASSERT_STRING_EQUAL(db.msg_store->topic, "topic"); } CU_ASSERT_EQUAL(db.msg_store->payloadlen, 7); if(db.msg_store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(db.msg_store), "payload", 7); } } } static void TEST_v5_config_ok(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-cfg.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x7856341200000000); } static void TEST_v5_config_truncated(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-cfg-truncated.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, 1); CU_ASSERT_EQUAL(db.last_db_id, 0); } static void TEST_v5_bad_chunk(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-bad-chunk.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x17); } static void TEST_v5_message_store(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-message-store.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.msg_store_count, 1); CU_ASSERT_EQUAL(db.msg_store_bytes, 7); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_EQUAL(db.msg_store->db_id, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->mid, 0); CU_ASSERT_EQUAL(db.msg_store->qos, 2); CU_ASSERT_EQUAL(db.msg_store->retain, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->topic, "topic"); CU_ASSERT_EQUAL(db.msg_store->payloadlen, 7); if(db.msg_store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(db.msg_store), "payload", 7); } CU_ASSERT_PTR_NULL(db.msg_store->properties); } } static void TEST_v5_message_store_props(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto__listener listener; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); memset(&listener, 0, sizeof(struct mosquitto__listener)); db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-message-store-props.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.msg_store_count, 1); CU_ASSERT_EQUAL(db.msg_store_bytes, 7); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_EQUAL(db.msg_store->db_id, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->mid, 0); CU_ASSERT_EQUAL(db.msg_store->qos, 2); CU_ASSERT_EQUAL(db.msg_store->retain, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->topic, "topic"); CU_ASSERT_EQUAL(db.msg_store->payloadlen, 7); if(db.msg_store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(db.msg_store), "payload", 7); } CU_ASSERT_PTR_NOT_NULL(db.msg_store->properties); if(db.msg_store->properties){ CU_ASSERT_EQUAL(db.msg_store->properties->identifier, 1); CU_ASSERT_EQUAL(db.msg_store->properties->value.i8, 1); } CU_ASSERT_PTR_NOT_NULL(db.msg_store->source_listener); } } static void TEST_v5_client(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-client.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NULL(context->msgs_in.inflight); CU_ASSERT_PTR_NULL(context->msgs_out.inflight); CU_ASSERT_EQUAL(context->last_mid, 0x5287); } } static void TEST_v5_client_message(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-client-message.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight); if(context->msgs_out.inflight){ CU_ASSERT_PTR_NULL(context->msgs_out.inflight->next); CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight->store); if(context->msgs_out.inflight->store){ CU_ASSERT_EQUAL(context->msgs_out.inflight->store->ref_count, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->store->source_id, "source_id"); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->source_mid, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->mid, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->qos, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->retain, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->store->topic, "topic"); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->payloadlen, 7); if(context->msgs_out.inflight->store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(context->msgs_out.inflight->store), "payload", 7); } } CU_ASSERT_EQUAL(context->msgs_out.inflight->mid, 0x73); CU_ASSERT_EQUAL(context->msgs_out.inflight->qos, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->retain, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->direction, mosq_md_out); CU_ASSERT_EQUAL(context->msgs_out.inflight->state, mosq_ms_wait_for_puback); CU_ASSERT_EQUAL(context->msgs_out.inflight->dup, 0); CU_ASSERT_PTR_NULL(context->msgs_out.inflight->properties); } } } static void TEST_v5_client_message_props(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-client-message-props.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight); if(context->msgs_out.inflight){ CU_ASSERT_PTR_NULL(context->msgs_out.inflight->next); CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight->store); if(context->msgs_out.inflight->store){ CU_ASSERT_EQUAL(context->msgs_out.inflight->store->ref_count, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->store->source_id, "source_id"); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->source_mid, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->mid, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->qos, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->retain, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->store->topic, "topic"); CU_ASSERT_EQUAL(context->msgs_out.inflight->store->payloadlen, 7); if(context->msgs_out.inflight->store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(context->msgs_out.inflight->store), "payload", 7); } } CU_ASSERT_EQUAL(context->msgs_out.inflight->mid, 0x73); CU_ASSERT_EQUAL(context->msgs_out.inflight->qos, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->retain, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->direction, mosq_md_out); CU_ASSERT_EQUAL(context->msgs_out.inflight->state, mosq_ms_wait_for_puback); CU_ASSERT_EQUAL(context->msgs_out.inflight->dup, 0); CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight->properties); if(context->msgs_out.inflight->properties){ CU_ASSERT_EQUAL(context->msgs_out.inflight->properties->identifier, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->properties->value.i8, 1); } } } } static void TEST_v5_retain(void) { struct mosquitto_db db; struct mosquitto__config config; int rc; last_retained = 0; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-retain.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.msg_store_count, 1); CU_ASSERT_EQUAL(db.msg_store_bytes, 7); CU_ASSERT_PTR_NOT_NULL(db.msg_store); if(db.msg_store){ CU_ASSERT_EQUAL(db.msg_store->db_id, 0x54); CU_ASSERT_STRING_EQUAL(db.msg_store->source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->mid, 0); CU_ASSERT_EQUAL(db.msg_store->qos, 2); CU_ASSERT_EQUAL(db.msg_store->retain, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->topic, "topic"); CU_ASSERT_EQUAL(db.msg_store->payloadlen, 7); if(db.msg_store->payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(UHPA_ACCESS_PAYLOAD(db.msg_store), "payload", 7); } } CU_ASSERT_EQUAL(last_retained, 0x54); } static void TEST_v5_sub(void) { struct mosquitto_db db; struct mosquitto__config config; struct mosquitto *context; int rc; last_sub = NULL; last_qos = -1; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; config.persistence_filepath = "files/persist_read/v5-sub.test-db"; rc = persist__restore(&db); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.contexts_by_id); HASH_FIND(hh_id, db.contexts_by_id, "client-id", strlen("client-id"), context); CU_ASSERT_PTR_NOT_NULL(context); if(context){ CU_ASSERT_PTR_NOT_NULL(last_sub); if(last_sub){ CU_ASSERT_STRING_EQUAL(last_sub, "subscription") free(last_sub); } CU_ASSERT_EQUAL(last_qos, 1); CU_ASSERT_EQUAL(last_identifier, 0x7623); } } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_persist_read_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Persist read", NULL, NULL); if(!test_suite){ printf("Error adding CUnit persist read test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Persistence disabled", TEST_persistence_disabled) || !CU_add_test(test_suite, "Empty file", TEST_empty_file) || !CU_add_test(test_suite, "Corrupt header", TEST_corrupt_header) || !CU_add_test(test_suite, "Unsupported version", TEST_unsupported_version) || !CU_add_test(test_suite, "v3 config ok", TEST_v3_config_ok) || !CU_add_test(test_suite, "v3 config bad truncated", TEST_v3_config_truncated) || !CU_add_test(test_suite, "v3 config bad dbid", TEST_v3_config_bad_dbid) || !CU_add_test(test_suite, "v3 bad chunk", TEST_v3_bad_chunk) || !CU_add_test(test_suite, "v3 message store", TEST_v3_message_store) || !CU_add_test(test_suite, "v3 client", TEST_v3_client) || !CU_add_test(test_suite, "v3 client message", TEST_v3_client_message) || !CU_add_test(test_suite, "v3 retain", TEST_v3_retain) || !CU_add_test(test_suite, "v3 sub", TEST_v3_sub) || !CU_add_test(test_suite, "v4 config ok", TEST_v4_config_ok) || !CU_add_test(test_suite, "v4 message store", TEST_v4_message_store) || !CU_add_test(test_suite, "v5 config ok", TEST_v5_config_ok) || !CU_add_test(test_suite, "v5 config bad truncated", TEST_v5_config_truncated) || !CU_add_test(test_suite, "v5 bad chunk", TEST_v5_bad_chunk) || !CU_add_test(test_suite, "v5 message store", TEST_v5_message_store) || !CU_add_test(test_suite, "v5 message store+props", TEST_v5_message_store_props) || !CU_add_test(test_suite, "v5 client", TEST_v5_client) || !CU_add_test(test_suite, "v5 client message", TEST_v5_client_message) || !CU_add_test(test_suite, "v5 client message+props", TEST_v5_client_message_props) || !CU_add_test(test_suite, "v5 retain", TEST_v5_retain) || !CU_add_test(test_suite, "v5 sub", TEST_v5_sub) ){ printf("Error adding persist CUnit tests.\n"); return 1; } return 0; } int main(int argc, char *argv[]) { int fails; if(CU_initialize_registry() != CUE_SUCCESS){ printf("Error initializing CUnit registry.\n"); return 1; } if(0 || init_persist_read_tests() ){ CU_cleanup_registry(); return 1; } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); fails = CU_get_number_of_failures(); CU_cleanup_registry(); return (int)fails; } mosquitto-1.6.9/test/unit/publish_test.c0000664000175000017500000000167713626052637017447 0ustar rogerroger#include #include #include #include static void TEST_maximum_packet_size(void) { struct mosquitto mosq; int rc; memset(&mosq, 0, sizeof(struct mosquitto)); mosq.maximum_packet_size = 5; rc = mosquitto_publish(&mosq, NULL, "topic/oversize", strlen("payload"), "payload", 0, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_OVERSIZE_PACKET); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_publish_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Publish", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Publish test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "v5: Maximum packet size", TEST_maximum_packet_size) ){ printf("Error adding Publish CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/property_write.c0000664000175000017500000004545513626052637020042 0ustar rogerroger#include #include #include "mqtt_protocol.h" #include "property_mosq.h" #include "packet_mosq.h" static void byte_prop_write_helper( int command, int remaining_length, int rc_expected, int identifier, uint8_t value_expected) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.i8 = value_expected; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.i8, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 2); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(packet.payload); } static void int32_prop_write_helper( int command, int remaining_length, int rc_expected, int identifier, uint32_t value_expected) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.i32 = value_expected; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.i32, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 5); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(packet.payload); } static void int16_prop_write_helper( int command, int remaining_length, int rc_expected, int identifier, uint16_t value_expected) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.i16 = value_expected; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.i16, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 3); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(packet.payload); } static void string_prop_write_helper( int command, int remaining_length, int rc_expected, int identifier, const char *value_expected) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.s.v = strdup(value_expected); CU_ASSERT_PTR_NOT_NULL(property.value.s.v); if(!property.value.s.v) return; property.value.s.len = strlen(value_expected); memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.s.len, strlen(value_expected)); CU_ASSERT_STRING_EQUAL(properties->value.s.v, value_expected); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 1+2+strlen(value_expected)); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(property.value.s.v); free(packet.payload); } static void binary_prop_write_helper( int command, int remaining_length, int rc_expected, int identifier, const uint8_t *value_expected, int len_expected) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.bin.v = malloc(len_expected); CU_ASSERT_PTR_NOT_NULL(property.value.bin.v); if(!property.value.bin.v) return; memcpy(property.value.bin.v, value_expected, len_expected); property.value.bin.len = len_expected; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.bin.len, len_expected); CU_ASSERT_EQUAL(memcmp(properties->value.bin.v, value_expected, len_expected), 0); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_EQUAL(property__get_length_all(properties), 1+2+len_expected); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(property.value.bin.v); free(packet.payload); } static void string_pair_prop_write_helper( int remaining_length, int rc_expected, int identifier, const char *name_expected, const char *value_expected, bool expect_multiple) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.s.v = strdup(value_expected); CU_ASSERT_PTR_NOT_NULL(property.value.s.v); if(!property.value.s.v) return; property.value.s.len = strlen(value_expected); property.name.v = strdup(name_expected); CU_ASSERT_PTR_NOT_NULL(property.name.v); if(!property.name.v) return; property.name.len = strlen(name_expected); memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(CMD_CONNECT, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->name.len, strlen(name_expected)); CU_ASSERT_EQUAL(properties->value.s.len, strlen(value_expected)); CU_ASSERT_STRING_EQUAL(properties->name.v, name_expected); CU_ASSERT_STRING_EQUAL(properties->value.s.v, value_expected); if(expect_multiple){ CU_ASSERT_PTR_NOT_NULL(properties->next); }else{ CU_ASSERT_PTR_NULL(properties->next); CU_ASSERT_EQUAL(property__get_length_all(properties), 1+2+strlen(name_expected)+2+strlen(value_expected)); } mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_NULL(properties); free(property.value.s.v); free(property.name.v); free(packet.payload); } static void varint_prop_write_helper( int remaining_length, int rc_expected, int identifier, uint32_t value_expected) { mosquitto_property property; struct mosquitto__packet packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.varint = value_expected; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.remaining_length = property__get_length_all(&property)+1; packet.packet_length = packet.remaining_length+10; packet.payload = calloc(packet.remaining_length+10, 1); CU_ASSERT_PTR_NOT_NULL(packet.payload); if(!packet.payload) return; property__write_all(&packet, &property, true); packet.pos = 0; rc = property__read_all(CMD_PUBLISH, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(properties->value.varint, value_expected); CU_ASSERT_PTR_NULL(properties->next); if(value_expected < 128){ CU_ASSERT_EQUAL(property__get_length_all(properties), 2); }else if(value_expected < 16384){ CU_ASSERT_EQUAL(property__get_length_all(properties), 3); }else if(value_expected < 2097152){ CU_ASSERT_EQUAL(property__get_length_all(properties), 4); }else if(value_expected < 268435456){ CU_ASSERT_EQUAL(property__get_length_all(properties), 5); }else{ CU_FAIL("Incorrect varint value."); } mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_NULL(properties); free(packet.payload); } /* ======================================================================== * BAD IDENTIFIER * ======================================================================== */ static void TEST_bad_identifier(void) { mosquitto_property property; struct mosquitto__packet packet; uint8_t payload[10]; int rc; memset(&property, 0, sizeof(mosquitto_property)); memset(&packet, 0, sizeof(struct mosquitto__packet)); property.identifier = 0xFFFF; packet.packet_length = 10; packet.remaining_length = 8; packet.payload = payload; rc = property__write_all(&packet, &property, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); } /* ======================================================================== * SINGLE PROPERTIES * ======================================================================== */ static void TEST_single_payload_format_indicator(void) { byte_prop_write_helper(CMD_PUBLISH, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); } static void TEST_single_request_problem_information(void) { byte_prop_write_helper(CMD_CONNECT, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); } static void TEST_single_request_response_information(void) { byte_prop_write_helper(CMD_CONNECT, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); } static void TEST_single_maximum_qos(void) { byte_prop_write_helper(CMD_CONNACK, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_MAXIMUM_QOS, 1); } static void TEST_single_retain_available(void) { byte_prop_write_helper(CMD_CONNACK, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_RETAIN_AVAILABLE, 1); } static void TEST_single_wildcard_subscription_available(void) { byte_prop_write_helper(CMD_CONNACK, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); } static void TEST_single_subscription_identifier_available(void) { byte_prop_write_helper(CMD_CONNACK, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); } static void TEST_single_shared_subscription_available(void) { byte_prop_write_helper(CMD_CONNACK, 3, MOSQ_ERR_SUCCESS, MQTT_PROP_SHARED_SUB_AVAILABLE, 1); } static void TEST_single_message_expiry_interval(void) { int32_prop_write_helper(CMD_PUBLISH, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 0x12233445); } static void TEST_single_session_expiry_interval(void) { int32_prop_write_helper(CMD_CONNACK, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 0x45342312); } static void TEST_single_will_delay_interval(void) { int32_prop_write_helper(CMD_WILL, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_WILL_DELAY_INTERVAL, 0x45342312); } static void TEST_single_maximum_packet_size(void) { int32_prop_write_helper(CMD_CONNECT, 6, MOSQ_ERR_SUCCESS, MQTT_PROP_MAXIMUM_PACKET_SIZE, 0x45342312); } static void TEST_single_server_keep_alive(void) { int16_prop_write_helper(CMD_CONNACK, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_SERVER_KEEP_ALIVE, 0x4534); } static void TEST_single_receive_maximum(void) { int16_prop_write_helper(CMD_CONNACK, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_RECEIVE_MAXIMUM, 0x6842); } static void TEST_single_topic_alias_maximum(void) { int16_prop_write_helper(CMD_CONNECT, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 0x6842); } static void TEST_single_topic_alias(void) { int16_prop_write_helper(CMD_PUBLISH, 4, MOSQ_ERR_SUCCESS, MQTT_PROP_TOPIC_ALIAS, 0x6842); } static void TEST_single_content_type(void) { string_prop_write_helper(CMD_PUBLISH, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_CONTENT_TYPE, "hello"); } static void TEST_single_response_topic(void) { string_prop_write_helper(CMD_WILL, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_RESPONSE_TOPIC, "hello"); } static void TEST_single_assigned_client_identifier(void) { string_prop_write_helper(CMD_CONNACK, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "hello"); } static void TEST_single_authentication_method(void) { string_prop_write_helper(CMD_CONNECT, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_AUTHENTICATION_METHOD, "hello"); } static void TEST_single_response_information(void) { string_prop_write_helper(CMD_CONNACK, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_RESPONSE_INFORMATION, "hello"); } static void TEST_single_server_reference(void) { string_prop_write_helper(CMD_CONNACK, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_SERVER_REFERENCE, "hello"); } static void TEST_single_reason_string(void) { string_prop_write_helper(CMD_PUBREC, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_REASON_STRING, "hello"); } static void TEST_single_correlation_data(void) { uint8_t payload[5] = {1, 'e', 0, 'l', 9}; binary_prop_write_helper(CMD_PUBLISH, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_CORRELATION_DATA, payload, 5); } static void TEST_single_authentication_data(void) { uint8_t payload[5] = {1, 'e', 0, 'l', 9}; binary_prop_write_helper(CMD_CONNECT, 9, MOSQ_ERR_SUCCESS, MQTT_PROP_AUTHENTICATION_DATA, payload, 5); } static void TEST_single_user_property(void) { string_pair_prop_write_helper(10, MOSQ_ERR_SUCCESS, MQTT_PROP_USER_PROPERTY, "za", "bc", false); } static void TEST_single_subscription_identifier(void) { varint_prop_write_helper(3, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 0); varint_prop_write_helper(3, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 127); varint_prop_write_helper(4, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 128); varint_prop_write_helper(4, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 16383); varint_prop_write_helper(5, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 16384); varint_prop_write_helper(5, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 2097151); varint_prop_write_helper(6, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 2097152); varint_prop_write_helper(6, MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 268435455); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_property_write_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Property write", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Property write test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Bad identifier", TEST_bad_identifier) || !CU_add_test(test_suite, "Single Payload Format Indicator", TEST_single_payload_format_indicator) || !CU_add_test(test_suite, "Single Request Problem Information", TEST_single_request_problem_information) || !CU_add_test(test_suite, "Single Request Response Information", TEST_single_request_response_information) || !CU_add_test(test_suite, "Single Maximum QoS", TEST_single_maximum_qos) || !CU_add_test(test_suite, "Single Retain Available", TEST_single_retain_available) || !CU_add_test(test_suite, "Single Wildcard Subscription Available", TEST_single_wildcard_subscription_available) || !CU_add_test(test_suite, "Single Subscription Identifier Available", TEST_single_subscription_identifier_available) || !CU_add_test(test_suite, "Single Shared Subscription Available", TEST_single_shared_subscription_available) || !CU_add_test(test_suite, "Single Message Expiry Interval", TEST_single_message_expiry_interval) || !CU_add_test(test_suite, "Single Session Expiry Interval", TEST_single_session_expiry_interval) || !CU_add_test(test_suite, "Single Will Delay Interval", TEST_single_will_delay_interval) || !CU_add_test(test_suite, "Single Maximum Packet Size", TEST_single_maximum_packet_size) || !CU_add_test(test_suite, "Single Server Keep Alive", TEST_single_server_keep_alive) || !CU_add_test(test_suite, "Single Receive Maximum", TEST_single_receive_maximum) || !CU_add_test(test_suite, "Single Topic Alias Maximum", TEST_single_topic_alias_maximum) || !CU_add_test(test_suite, "Single Topic Alias", TEST_single_topic_alias) || !CU_add_test(test_suite, "Single Content Type", TEST_single_content_type) || !CU_add_test(test_suite, "Single Response Topic", TEST_single_response_topic) || !CU_add_test(test_suite, "Single Assigned Client Identifier", TEST_single_assigned_client_identifier) || !CU_add_test(test_suite, "Single Authentication Method", TEST_single_authentication_method) || !CU_add_test(test_suite, "Single Response Information", TEST_single_response_information) || !CU_add_test(test_suite, "Single Server Reference", TEST_single_server_reference) || !CU_add_test(test_suite, "Single Reason String", TEST_single_reason_string) || !CU_add_test(test_suite, "Single Correlation Data", TEST_single_correlation_data) || !CU_add_test(test_suite, "Single Authentication Data", TEST_single_authentication_data) || !CU_add_test(test_suite, "Single User Property", TEST_single_user_property) || !CU_add_test(test_suite, "Single Subscription Identifier", TEST_single_subscription_identifier) ){ printf("Error adding Property read CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/datatype_write.c0000664000175000017500000000763513626052637017767 0ustar rogerroger#include #include #include #include "packet_mosq.h" /* ======================================================================== * BYTE TESTS * ======================================================================== */ /* This tests writing a Byte to an incoming packet. */ static void TEST_byte_write(void) { uint8_t payload[260]; struct mosquitto__packet packet; int i; memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); packet.payload = payload; packet.packet_length = 256; for(i=0; i<256; i++){ packet__write_byte(&packet, 255-i); } CU_ASSERT_EQUAL(packet.pos, 256); for(i=0; i<256; i++){ CU_ASSERT_EQUAL(payload[i], 255-i); } } /* ======================================================================== * TWO BYTE INTEGER TESTS * ======================================================================== */ /* This tests writing a Two Byte Integer to an incoming packet. */ static void TEST_uint16_write(void) { uint8_t payload[650]; uint16_t *payload16; struct mosquitto__packet packet; int i; memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, sizeof(payload)); packet.payload = payload; packet.packet_length = 650; for(i=0; i<325; i++){ packet__write_uint16(&packet, 100*i); } CU_ASSERT_EQUAL(packet.pos, 650); payload16 = (uint16_t *)payload; for(i=0; i<325; i++){ CU_ASSERT_EQUAL(payload16[i], htons(100*i)); } } /* ======================================================================== * FOUR BYTE INTEGER TESTS * ======================================================================== */ /* This tests writing a Four Byte Integer to an incoming packet. */ static void TEST_uint32_write(void) { uint8_t *payload; uint32_t *payload32; struct mosquitto__packet packet; int i; payload = calloc(42000, sizeof(uint32_t)); if(!payload){ CU_FAIL_FATAL("Out of memory"); } memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.packet_length = 42000; for(i=0; i<10500; i++){ packet__write_uint32(&packet, 1000*i); } CU_ASSERT_EQUAL(packet.pos, 42000); payload32 = (uint32_t *)payload; for(i=0; i<10500; i++){ CU_ASSERT_EQUAL(payload32[i], htonl(1000*i)); } free(payload); } /* ======================================================================== * UTF-8 STRING TESTS * ======================================================================== */ /* This tests writing a UTF-8 String to an incoming packet. */ static void TEST_string_write(void) { uint8_t payload[100]; struct mosquitto__packet packet; memset(&packet, 0, sizeof(struct mosquitto__packet)); memset(payload, 0, 100); packet.payload = payload; packet.packet_length = 100; packet__write_string(&packet, "first test", strlen("first test")); packet__write_string(&packet, "second test", strlen("second test")); CU_ASSERT_EQUAL(packet.pos, 2+10+2+11); CU_ASSERT_EQUAL(payload[0], 0); CU_ASSERT_EQUAL(payload[1], 10); CU_ASSERT_NSTRING_EQUAL(payload+2, "first test", 10); CU_ASSERT_EQUAL(payload[2+10+0], 0); CU_ASSERT_EQUAL(payload[2+10+1], 11); CU_ASSERT_NSTRING_EQUAL(payload+2+10+2, "second test", 11); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_datatype_write_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Datatype write", NULL, NULL); if(!test_suite){ printf("Error adding CUnit test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Byte write", TEST_byte_write) || !CU_add_test(test_suite, "Two Byte Integer write", TEST_uint16_write) || !CU_add_test(test_suite, "Four Byte Integer write", TEST_uint32_write) || !CU_add_test(test_suite, "UTF-8 String write", TEST_string_write) ){ printf("Error adding Datatype write CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/persist_read_stubs.c0000664000175000017500000000715713626052637020645 0ustar rogerroger#include #define WITH_BROKER #include #include #include #include #include #include extern uint64_t last_retained; extern char *last_sub; extern int last_qos; extern uint32_t last_identifier; struct mosquitto *context__init(struct mosquitto_db *db, mosq_sock_t sock) { struct mosquitto *m; m = mosquitto__calloc(1, sizeof(struct mosquitto)); if(m){ m->msgs_in.inflight_maximum = 20; m->msgs_out.inflight_maximum = 20; m->msgs_in.inflight_quota = 20; m->msgs_out.inflight_quota = 20; } return m; } int db__message_store(struct mosquitto_db *db, const struct mosquitto *source, uint16_t source_mid, char *topic, int qos, uint32_t payloadlen, mosquitto__payload_uhpa *payload, int retain, struct mosquitto_msg_store **stored, uint32_t message_expiry_interval, mosquitto_property *properties, dbid_t store_id, enum mosquitto_msg_origin origin) { struct mosquitto_msg_store *temp = NULL; int rc = MOSQ_ERR_SUCCESS; temp = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(!temp){ rc = MOSQ_ERR_NOMEM; goto error; } if(source && source->id){ temp->source_id = mosquitto__strdup(source->id); }else{ temp->source_id = mosquitto__strdup(""); } if(!temp->source_id){ rc = MOSQ_ERR_NOMEM; goto error; } if(source && source->username){ temp->source_username = mosquitto__strdup(source->username); if(!temp->source_username){ rc = MOSQ_ERR_NOMEM; goto error; } } if(source){ temp->source_listener = source->listener; } temp->source_mid = source_mid; temp->mid = 0; temp->qos = qos; temp->retain = retain; temp->topic = topic; topic = NULL; temp->payloadlen = payloadlen; temp->properties = properties; if(payloadlen){ UHPA_MOVE(temp->payload, *payload, payloadlen); }else{ temp->payload.ptr = NULL; } if(message_expiry_interval > 0){ temp->message_expiry_time = time(NULL) + message_expiry_interval; }else{ temp->message_expiry_time = 0; } temp->dest_ids = NULL; temp->dest_id_count = 0; db->msg_store_count++; db->msg_store_bytes += payloadlen; (*stored) = temp; if(!store_id){ temp->db_id = ++db->last_db_id; }else{ temp->db_id = store_id; } db->msg_store = temp; return MOSQ_ERR_SUCCESS; error: mosquitto__free(topic); if(temp){ mosquitto__free(temp->source_id); mosquitto__free(temp->source_username); mosquitto__free(temp->topic); mosquitto__free(temp); } UHPA_FREE(*payload, payloadlen); return rc; } int log__printf(struct mosquitto *mosq, int priority, const char *fmt, ...) { return 0; } time_t mosquitto_time(void) { return 123; } int net__socket_close(struct mosquitto_db *db, struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int sub__add(struct mosquitto_db *db, struct mosquitto *context, const char *sub, int qos, uint32_t identifier, int options, struct mosquitto__subhier **root) { last_sub = strdup(sub); last_qos = qos; last_identifier = identifier; return MOSQ_ERR_SUCCESS; } int sub__messages_queue(struct mosquitto_db *db, const char *source_id, const char *topic, int qos, int retain, struct mosquitto_msg_store **stored) { if(retain){ last_retained = (*stored)->db_id; } return MOSQ_ERR_SUCCESS; } void db__msg_store_ref_inc(struct mosquitto_msg_store *store) { store->ref_count++; } mosquitto-1.6.9/test/unit/datatype_read.c0000664000175000017500000005237113626052637017545 0ustar rogerroger#include #include #include "packet_mosq.h" static void byte_read_helper( uint8_t *payload, int remaining_length, int rc_expected, uint8_t value_expected) { struct mosquitto__packet packet; uint8_t value = 0; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_byte(&packet, &value); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(value, value_expected); } static void uint16_read_helper( uint8_t *payload, int remaining_length, int rc_expected, uint16_t value_expected) { struct mosquitto__packet packet; uint16_t value = 0; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_uint16(&packet, &value); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(value, value_expected); } static void uint32_read_helper( uint8_t *payload, int remaining_length, int rc_expected, uint32_t value_expected) { struct mosquitto__packet packet; uint32_t value = 0; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_uint32(&packet, &value); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(value, value_expected); } static void varint_read_helper( uint8_t *payload, int remaining_length, int rc_expected, int32_t value_expected, int8_t bytes_expected) { struct mosquitto__packet packet; int32_t value = -1; int8_t bytes = -1; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_varint(&packet, &value, &bytes); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(value, value_expected); CU_ASSERT_EQUAL(bytes, bytes_expected); } static void binary_read_helper( uint8_t *payload, int remaining_length, int rc_expected, const uint8_t *value_expected, int length_expected) { struct mosquitto__packet packet; uint8_t *value = NULL; int length = -1; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_binary(&packet, (uint8_t **)&value, &length); CU_ASSERT_EQUAL(rc, rc_expected); if(value_expected){ /* FIXME - this should be a memcmp */ CU_ASSERT_NSTRING_EQUAL(value, value_expected, length_expected); }else{ CU_ASSERT_EQUAL(value, NULL); } CU_ASSERT_EQUAL(length, length_expected); free(value); } static void string_read_helper( uint8_t *payload, int remaining_length, int rc_expected, const uint8_t *value_expected, int length_expected) { struct mosquitto__packet packet; uint8_t *value = NULL; int length = -1; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_string(&packet, (char **)&value, &length); CU_ASSERT_EQUAL(rc, rc_expected); if(value_expected){ if(value){ CU_ASSERT_NSTRING_EQUAL(value, value_expected, length_expected); } }else{ CU_ASSERT_PTR_NULL(value); } CU_ASSERT_EQUAL(length, length_expected); free(value); } static void bytes_read_helper( uint8_t *payload, int remaining_length, int rc_expected, const uint8_t *value_expected, int count) { struct mosquitto__packet packet; uint8_t value[count]; int rc; int i; memset(&packet, 0, sizeof(struct mosquitto__packet)); packet.payload = payload; packet.remaining_length = remaining_length; rc = packet__read_bytes(&packet, value, count); CU_ASSERT_EQUAL(rc, rc_expected); if(rc == MOSQ_ERR_SUCCESS){ CU_ASSERT_EQUAL(packet.pos, count); } if(value_expected){ for(i=0; i #include #include "mqtt_protocol.h" #include "property_mosq.h" #include "packet_mosq.h" static void generate_full_proplist(mosquitto_property **proplist) { int rc; /* This isn't a valid proplist for sending, because it contains every * property. Very useful for testing though. */ rc = mosquitto_property_add_byte(proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int32(proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 3600); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_binary(proplist, MQTT_PROP_CORRELATION_DATA, "correlation-data", strlen("correlation-data")); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_varint(proplist, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 63); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int32(proplist, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 86400); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "mosquitto-test"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int16(proplist, MQTT_PROP_SERVER_KEEP_ALIVE, 180); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_AUTHENTICATION_METHOD, "basic"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_binary(proplist, MQTT_PROP_AUTHENTICATION_DATA, "password", strlen("password")); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int32(proplist, MQTT_PROP_WILL_DELAY_INTERVAL, 1800); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_RESPONSE_INFORMATION, "response"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_SERVER_REFERENCE, "localhost"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string(proplist, MQTT_PROP_REASON_STRING, "reason"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int16(proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1024); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int16(proplist, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 64); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int16(proplist, MQTT_PROP_TOPIC_ALIAS, 15); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_MAXIMUM_QOS, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_RETAIN_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_string_pair(proplist, MQTT_PROP_USER_PROPERTY, "user-agent", "mosquitto/test"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_int32(proplist, MQTT_PROP_MAXIMUM_PACKET_SIZE, 200000000); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS) return; rc = mosquitto_property_add_byte(proplist, MQTT_PROP_SHARED_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void generate_partial_proplist(mosquitto_property **proplist) { int rc; // BYTE MISSING: MQTT_PROP_PAYLOAD_FORMAT_INDICATOR rc = mosquitto_property_add_int32(proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 3600); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); // STRING MISSING: MQTT_PROP_CONTENT_TYPE rc = mosquitto_property_add_string(proplist, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); // BINARY MISSING: MQTT_PROP_CORRELATION_DATA // VARINT MISSING: MQTT_PROP_SUBSCRIPTION_IDENTIFIER // INT32 MISSING: MQTT_PROP_SESSION_EXPIRY_INTERVAL rc = mosquitto_property_add_string(proplist, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "mosquitto-test"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); // INT16 MISSING: MQTT_PROP_SERVER_KEEP_ALIVE rc = mosquitto_property_add_string(proplist, MQTT_PROP_AUTHENTICATION_METHOD, "basic"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_binary(proplist, MQTT_PROP_AUTHENTICATION_DATA, "password", strlen("password")); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_int32(proplist, MQTT_PROP_WILL_DELAY_INTERVAL, 1800); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_string(proplist, MQTT_PROP_RESPONSE_INFORMATION, "response"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_string(proplist, MQTT_PROP_SERVER_REFERENCE, "localhost"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_string(proplist, MQTT_PROP_REASON_STRING, "reason"); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_int16(proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1024); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_int16(proplist, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 64); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_int16(proplist, MQTT_PROP_TOPIC_ALIAS, 15); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_MAXIMUM_QOS, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_RETAIN_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); // STRING PAIR MISSING: MQTT_PROP_USER_PROPERTY rc = mosquitto_property_add_int32(proplist, MQTT_PROP_MAXIMUM_PACKET_SIZE, 200000000); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); rc = mosquitto_property_add_byte(proplist, MQTT_PROP_SHARED_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } /* ======================================================================== * SINGLE READ * ======================================================================== */ static void read_byte_helper(const mosquitto_property *proplist, int identifier, uint8_t expected_value) { const mosquitto_property *prop; uint8_t value; prop = mosquitto_property_read_byte(proplist, identifier, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(value, expected_value); } static void read_int16_helper(const mosquitto_property *proplist, int identifier, uint16_t expected_value) { const mosquitto_property *prop; uint16_t value; prop = mosquitto_property_read_int16(proplist, identifier, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(value, expected_value); } static void read_int32_helper(const mosquitto_property *proplist, int identifier, uint32_t expected_value) { const mosquitto_property *prop; uint32_t value; prop = mosquitto_property_read_int32(proplist, identifier, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(value, expected_value); } static void read_varint_helper(const mosquitto_property *proplist, int identifier, uint32_t expected_value) { const mosquitto_property *prop; uint32_t value; prop = mosquitto_property_read_varint(proplist, identifier, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(value, expected_value); } static void read_binary_helper(const mosquitto_property *proplist, int identifier, void *expected_value, int expected_length) { const mosquitto_property *prop; void *value = NULL; uint16_t length; prop = mosquitto_property_read_binary(proplist, identifier, &value, &length, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(length, expected_length); CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_NSTRING_EQUAL(value, expected_value, expected_length); } free(value); } static void read_string_helper(const mosquitto_property *proplist, int identifier, char *expected_value) { const mosquitto_property *prop; char *value = NULL; prop = mosquitto_property_read_string(proplist, identifier, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_STRING_EQUAL(value, expected_value); } free(value); } static void read_string_pair_helper(const mosquitto_property *proplist, int identifier, char *expected_key, char *expected_value) { const mosquitto_property *prop; char *key = NULL, *value = NULL; prop = mosquitto_property_read_string_pair(proplist, identifier, &key, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_PTR_NOT_NULL(key); if(key){ CU_ASSERT_STRING_EQUAL(key, expected_key); } CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_STRING_EQUAL(value, expected_value); } free(key); free(value); } static void TEST_read_single_byte(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_byte_helper(proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); read_byte_helper(proplist, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); read_byte_helper(proplist, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); read_byte_helper(proplist, MQTT_PROP_MAXIMUM_QOS, 0); read_byte_helper(proplist, MQTT_PROP_RETAIN_AVAILABLE, 0); read_byte_helper(proplist, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); read_byte_helper(proplist, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); read_byte_helper(proplist, MQTT_PROP_SHARED_SUB_AVAILABLE, 0); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_byte_helper(proplist_copy, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); read_byte_helper(proplist_copy, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, 1); read_byte_helper(proplist_copy, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, 1); read_byte_helper(proplist_copy, MQTT_PROP_MAXIMUM_QOS, 0); read_byte_helper(proplist_copy, MQTT_PROP_RETAIN_AVAILABLE, 0); read_byte_helper(proplist_copy, MQTT_PROP_WILDCARD_SUB_AVAILABLE, 0); read_byte_helper(proplist_copy, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, 0); read_byte_helper(proplist_copy, MQTT_PROP_SHARED_SUB_AVAILABLE, 0); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_single_int16(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_int16_helper(proplist, MQTT_PROP_SERVER_KEEP_ALIVE, 180); read_int16_helper(proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1024); read_int16_helper(proplist, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 64); read_int16_helper(proplist, MQTT_PROP_TOPIC_ALIAS, 15); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_int16_helper(proplist_copy, MQTT_PROP_SERVER_KEEP_ALIVE, 180); read_int16_helper(proplist_copy, MQTT_PROP_RECEIVE_MAXIMUM, 1024); read_int16_helper(proplist_copy, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, 64); read_int16_helper(proplist_copy, MQTT_PROP_TOPIC_ALIAS, 15); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_single_int32(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_int32_helper(proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 3600); read_int32_helper(proplist, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 86400); read_int32_helper(proplist, MQTT_PROP_WILL_DELAY_INTERVAL, 1800); read_int32_helper(proplist, MQTT_PROP_MAXIMUM_PACKET_SIZE, 200000000); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_int32_helper(proplist_copy, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 3600); read_int32_helper(proplist_copy, MQTT_PROP_SESSION_EXPIRY_INTERVAL, 86400); read_int32_helper(proplist_copy, MQTT_PROP_WILL_DELAY_INTERVAL, 1800); read_int32_helper(proplist_copy, MQTT_PROP_MAXIMUM_PACKET_SIZE, 200000000); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_single_varint(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_varint_helper(proplist, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 63); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_varint_helper(proplist_copy, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 63); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_single_binary(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_binary_helper(proplist, MQTT_PROP_CORRELATION_DATA, "correlation-data", strlen("correlation-data")); read_binary_helper(proplist, MQTT_PROP_AUTHENTICATION_DATA, "password", strlen("password")); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); if(proplist_copy){ read_binary_helper(proplist_copy, MQTT_PROP_CORRELATION_DATA, "correlation-data", strlen("correlation-data")); read_binary_helper(proplist_copy, MQTT_PROP_AUTHENTICATION_DATA, "password", strlen("password")); } mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_single_string(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_string_helper(proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); read_string_helper(proplist, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); read_string_helper(proplist, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "mosquitto-test"); read_string_helper(proplist, MQTT_PROP_AUTHENTICATION_METHOD, "basic"); read_string_helper(proplist, MQTT_PROP_RESPONSE_INFORMATION, "response"); read_string_helper(proplist, MQTT_PROP_SERVER_REFERENCE, "localhost"); read_string_helper(proplist, MQTT_PROP_REASON_STRING, "reason"); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); if(proplist_copy){ read_string_helper(proplist_copy, MQTT_PROP_CONTENT_TYPE, "application/json"); read_string_helper(proplist_copy, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); read_string_helper(proplist_copy, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, "mosquitto-test"); read_string_helper(proplist_copy, MQTT_PROP_AUTHENTICATION_METHOD, "basic"); read_string_helper(proplist_copy, MQTT_PROP_RESPONSE_INFORMATION, "response"); read_string_helper(proplist_copy, MQTT_PROP_SERVER_REFERENCE, "localhost"); read_string_helper(proplist_copy, MQTT_PROP_REASON_STRING, "reason"); } mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_single_string_pair(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; generate_full_proplist(&proplist); if(!proplist) return; read_string_pair_helper(proplist, MQTT_PROP_USER_PROPERTY, "user-agent", "mosquitto/test"); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); if(proplist_copy){ read_string_pair_helper(proplist_copy, MQTT_PROP_USER_PROPERTY, "user-agent", "mosquitto/test"); } mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } /* ======================================================================== * MISSING READ * ======================================================================== */ static void missing_read_helper(mosquitto_property *proplist) { const mosquitto_property *prop; uint8_t byte_value; uint16_t int16_value; uint32_t int32_value; char *key, *value; uint16_t length; /* MISSING */ prop = mosquitto_property_read_byte(proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, &byte_value, false); CU_ASSERT_PTR_NULL(prop); /* NOT MISSING */ prop = mosquitto_property_read_int32(proplist, MQTT_PROP_WILL_DELAY_INTERVAL, &int32_value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(int32_value, 1800); /* MISSING */ value = NULL; prop = mosquitto_property_read_string(proplist, MQTT_PROP_CONTENT_TYPE, &value, false); CU_ASSERT_PTR_NULL(prop); /* NOT MISSING */ value = NULL; prop = mosquitto_property_read_string(proplist, MQTT_PROP_RESPONSE_TOPIC, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_STRING_EQUAL(value, "response/topic"); free(value); } /* MISSING */ prop = mosquitto_property_read_binary(proplist, MQTT_PROP_CORRELATION_DATA, (void **)&value, &length, false); CU_ASSERT_PTR_NULL(prop); /* NOT MISSING */ prop = mosquitto_property_read_byte(proplist, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, &byte_value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(byte_value, 1); /* MISSING */ prop = mosquitto_property_read_varint(proplist, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, &int32_value, false); CU_ASSERT_PTR_NULL(prop); /* NOT MISSING */ value = NULL; prop = mosquitto_property_read_string(proplist, MQTT_PROP_SERVER_REFERENCE, &value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_STRING_EQUAL(value, "localhost"); free(value); } /* MISSING */ prop = mosquitto_property_read_int32(proplist, MQTT_PROP_SESSION_EXPIRY_INTERVAL, &int32_value, false); CU_ASSERT_PTR_NULL(prop); /* NOT MISSING */ value = NULL; prop = mosquitto_property_read_binary(proplist, MQTT_PROP_AUTHENTICATION_DATA, (void **)&value, &length, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_NSTRING_EQUAL(value, "password", strlen("password")); CU_ASSERT_EQUAL(length, strlen("password")); free(value); } /* MISSING */ prop = mosquitto_property_read_int16(proplist, MQTT_PROP_SERVER_KEEP_ALIVE, &int16_value, false); CU_ASSERT_PTR_NULL(prop); /* NOT MISSING */ prop = mosquitto_property_read_int16(proplist, MQTT_PROP_RECEIVE_MAXIMUM, &int16_value, false); CU_ASSERT_PTR_NOT_NULL(prop); CU_ASSERT_EQUAL(int16_value, 1024); /* MISSING */ prop = mosquitto_property_read_string_pair(proplist, MQTT_PROP_USER_PROPERTY, &key, &value, false); CU_ASSERT_PTR_NULL(prop); } static void TEST_read_missing(void) { mosquitto_property *proplist = NULL, *proplist_copy = NULL; int rc; generate_partial_proplist(&proplist); if(!proplist) return; missing_read_helper(proplist); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); if(proplist_copy){ missing_read_helper(proplist_copy); } mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } /* ======================================================================== * STRING TO PROPERTY INFO * ======================================================================== */ static void string_to_property_info_helper(const char *str, int rc_expected, int identifier_expected, int type_expected) { int rc; int identifier, type; rc = mosquitto_string_to_property_info(str, &identifier, &type); CU_ASSERT_EQUAL(rc, rc_expected); if(rc == MOSQ_ERR_SUCCESS){ CU_ASSERT_EQUAL(identifier, identifier_expected); CU_ASSERT_EQUAL(type, type_expected); } } static void TEST_string_to_property_info(void) { string_to_property_info_helper("payload-format-indicator", MOSQ_ERR_SUCCESS, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("message-expiry-interval", MOSQ_ERR_SUCCESS, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT32); string_to_property_info_helper("content-type", MOSQ_ERR_SUCCESS, MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("response-topic", MOSQ_ERR_SUCCESS, MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("correlation-data", MOSQ_ERR_SUCCESS, MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY); string_to_property_info_helper("subscription-identifier", MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARINT); string_to_property_info_helper("session-expiry-interval", MOSQ_ERR_SUCCESS, MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT32); string_to_property_info_helper("assigned-client-identifier", MOSQ_ERR_SUCCESS, MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("server-keep-alive", MOSQ_ERR_SUCCESS, MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_INT16); string_to_property_info_helper("authentication-method", MOSQ_ERR_SUCCESS, MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("authentication-data", MOSQ_ERR_SUCCESS, MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY); string_to_property_info_helper("request-problem-information", MOSQ_ERR_SUCCESS, MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("will-delay-interval", MOSQ_ERR_SUCCESS, MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT32); string_to_property_info_helper("request-response-information", MOSQ_ERR_SUCCESS, MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("response-information", MOSQ_ERR_SUCCESS, MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("server-reference", MOSQ_ERR_SUCCESS, MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("reason-string", MOSQ_ERR_SUCCESS, MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING); string_to_property_info_helper("receive-maximum", MOSQ_ERR_SUCCESS, MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_INT16); string_to_property_info_helper("topic-alias-maximum", MOSQ_ERR_SUCCESS, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_INT16); string_to_property_info_helper("topic-alias", MOSQ_ERR_SUCCESS, MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_INT16); string_to_property_info_helper("maximum-qos", MOSQ_ERR_SUCCESS, MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("retain-available", MOSQ_ERR_SUCCESS, MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("user-property", MOSQ_ERR_SUCCESS, MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR); string_to_property_info_helper("maximum-packet-size", MOSQ_ERR_SUCCESS, MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT32); string_to_property_info_helper("wildcard-subscription-available", MOSQ_ERR_SUCCESS, MQTT_PROP_WILDCARD_SUB_AVAILABLE, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("subscription-identifier-available", MOSQ_ERR_SUCCESS, MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("shared-subscription-available", MOSQ_ERR_SUCCESS, MQTT_PROP_SHARED_SUB_AVAILABLE, MQTT_PROP_TYPE_BYTE); string_to_property_info_helper("payload-format-indicator1", MOSQ_ERR_INVAL, 0, 0); string_to_property_info_helper("payload", MOSQ_ERR_INVAL, 0, 0); string_to_property_info_helper("", MOSQ_ERR_INVAL, 0, 0); string_to_property_info_helper(NULL, MOSQ_ERR_INVAL, 0, 0); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_property_user_read_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Property user read", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Property user read test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Read single byte", TEST_read_single_byte) || !CU_add_test(test_suite, "Read single int16", TEST_read_single_int16) || !CU_add_test(test_suite, "Read single int32", TEST_read_single_int32) || !CU_add_test(test_suite, "Read single varint", TEST_read_single_varint) || !CU_add_test(test_suite, "Read single binary", TEST_read_single_binary) || !CU_add_test(test_suite, "Read single string", TEST_read_single_string) || !CU_add_test(test_suite, "Read single string pair", TEST_read_single_string_pair) || !CU_add_test(test_suite, "Read missing", TEST_read_missing) || !CU_add_test(test_suite, "String to property info", TEST_string_to_property_info) ){ printf("Error adding Property Add CUnit tests.\n"); return 1; } return 0; } mosquitto-1.6.9/test/unit/Makefile0000664000175000017500000000713013626052637016224 0ustar rogerrogerinclude ../../config.mk .PHONY: all check test test-broker test-lib clean coverage CPPFLAGS:=$(CPPFLAGS) -I../.. -I../../lib -I../../src ifeq ($(WITH_BUNDLED_DEPS),yes) CPPFLAGS:=$(CPPFLAGS) -I../../src/deps endif CFLAGS:=$(CFLAGS) -coverage -Wall -ggdb LDFLAGS:=$(LDFLAGS) -coverage LDADD:=$(LDADD) -lcunit TEST_OBJS = test.o \ datatype_read.o \ datatype_write.o \ misc_trim_test.o \ property_add.o \ property_read.o \ property_user_read.o \ property_write.o \ stubs.o \ util_topic_test.o \ utf8.o LIB_OBJS = memory_mosq.o \ misc_mosq.o \ packet_datatypes.o \ property_mosq.o \ util_mosq.o \ util_topic.o \ utf8_mosq.o PERSIST_READ_TEST_OBJS = \ persist_read_test.o \ persist_read_stubs.o PERSIST_READ_OBJS = \ memory_mosq.o \ misc_mosq.o \ packet_datatypes.o \ persist_read.o \ persist_read_v234.o \ persist_read_v5.o \ property_mosq.o \ utf8_mosq.o \ util_mosq.o PERSIST_WRITE_TEST_OBJS = \ persist_write_test.o \ persist_write_stubs.o PERSIST_WRITE_OBJS = \ database.o \ memory_mosq.o \ misc_mosq.o \ packet_datatypes.o \ persist_read.o \ persist_read_v234.o \ persist_read_v5.o \ persist_write.o \ persist_write_v5.o \ property_mosq.o \ subs.o \ utf8_mosq.o \ util_mosq.o all : test check : test mosq_test : ${TEST_OBJS} ${LIB_OBJS} $(CROSS_COMPILE)$(CC) $(LDFLAGS) -o $@ $^ $(LDADD) persist_read_test : ${PERSIST_READ_TEST_OBJS} ${PERSIST_READ_OBJS} $(CROSS_COMPILE)$(CC) $(LDFLAGS) -o $@ $^ $(LDADD) persist_write_test : ${PERSIST_WRITE_TEST_OBJS} ${PERSIST_WRITE_OBJS} $(CROSS_COMPILE)$(CC) $(LDFLAGS) -o $@ $^ $(LDADD) database.o : ../../src/database.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ memory_mosq.o : ../../lib/memory_mosq.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ misc_mosq.o : ../../lib/misc_mosq.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ packet_datatypes.o : ../../lib/packet_datatypes.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ persist_read.o : ../../src/persist_read.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ persist_read_v234.o : ../../src/persist_read_v234.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ persist_read_v5.o : ../../src/persist_read_v5.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ persist_write.o : ../../src/persist_write.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ persist_write_v5.o : ../../src/persist_write_v5.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ property_mosq.o : ../../lib/property_mosq.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ subs.o : ../../src/subs.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ util_mosq.o : ../../lib/util_mosq.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ util_topic.o : ../../lib/util_topic.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ utf8_mosq.o : ../../lib/utf8_mosq.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ test-lib : mosq_test ./mosq_test test-broker : persist_read_test persist_write_test ./persist_read_test ./persist_write_test test : test-broker test-lib clean : -rm -rf mosq_test persist_read_test persist_write_test -rm -rf *.o *.gcda *.gcno coverage.info out/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out mosquitto-1.6.9/test/mqtt5_opts.py0000664000175000017500000000026613626052637016301 0ustar rogerrogerMQTT_SUB_OPT_NO_LOCAL = 0x04 MQTT_SUB_OPT_RETAIN_AS_PUBLISHED = 0x08 MQTT_SUB_OPT_SEND_RETAIN_ALWAYS = 0x00 MQTT_SUB_OPT_SEND_RETAIN_NEW = 0x10 MQTT_SUB_OPT_SEND_RETAIN_NEVER = 0x20 mosquitto-1.6.9/compiling.txt0000664000175000017500000000153613626052637015354 0ustar rogerrogerThe following packages can be used to add features to mosquitto. All of them are optional. * openssl * c-ares (for DNS-SRV support, disabled by default) * tcp-wrappers (optional, package name libwrap0-dev) * libwebsockets (optional, disabled by default, version 1.3 and above) * On Windows, a pthreads library is required if threading support is to be included. To compile, run "make", but also see the file config.mk for more details on the various options that can be compiled in. Where possible use the Makefiles to compile. This is particularly relevant for the client libraries as symbol information will be included. Use cmake to compile on Windows or Mac. If you have any questions, problems or suggestions (particularly related to installing on a more unusual device like a plug-computer) then please get in touch using the details in readme.txt. mosquitto-1.6.9/config.h0000664000175000017500000000324113626052637014243 0ustar rogerroger#ifndef CONFIG_H #define CONFIG_H /* ============================================================ * Platform options * ============================================================ */ #ifdef __APPLE__ # define __DARWIN_C_SOURCE #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__SYMBIAN32__) || defined(__QNX__) # define _XOPEN_SOURCE 700 # define __BSD_VISIBLE 1 # define HAVE_NETINET_IN_H #else # define _XOPEN_SOURCE 700 # define _DEFAULT_SOURCE 1 # define _POSIX_C_SOURCE 200809L #endif #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #define OPENSSL_LOAD_CONF /* ============================================================ * Compatibility defines * ============================================================ */ #if defined(_MSC_VER) && _MSC_VER < 1900 # define snprintf sprintf_s # define EPROTO ECONNABORTED #endif #ifdef WIN32 # ifndef strcasecmp # define strcasecmp strcmpi # endif # define strtok_r strtok_s # define strerror_r(e, b, l) strerror_s(b, l, e) #endif #define uthash_malloc(sz) mosquitto__malloc(sz) #define uthash_free(ptr,sz) mosquitto__free(ptr) #ifdef WITH_TLS # include # if defined(WITH_TLS_PSK) && !defined(OPENSSL_NO_PSK) # define FINAL_WITH_TLS_PSK # endif #endif #ifdef __COVERITY__ # include /* These are "wrong", but we don't use them so it doesn't matter */ # define _Float32 uint32_t # define _Float32x uint32_t # define _Float64 uint64_t # define _Float64x uint64_t # define _Float128 uint64_t #endif #define UNUSED(A) (void)(A) /* Android Bionic libpthread implementation doesn't have pthread_cancel */ #ifndef ANDROID # define HAVE_PTHREAD_CANCEL #endif #endif mosquitto-1.6.9/misc/0000775000175000017500000000000013626052637013560 5ustar rogerrogermosquitto-1.6.9/misc/currentcost/0000775000175000017500000000000013626052637016133 5ustar rogerrogermosquitto-1.6.9/misc/currentcost/cc128_read.pl0000775000175000017500000000071713626052637020313 0ustar rogerroger#!/usr/bin/perl -w # Reads data from a Current Cost device via serial port. # Spawns use strict; use Device::SerialPort qw( :PARAM :STAT 0.07 ); my $pubclient = "mosquitto_pub -t sensors/cc128/raw -q 1 -l"; my $PORT = "/dev/ttyUSB0"; local $| = 1; my $ob = Device::SerialPort->new($PORT); $ob->baudrate(57600); $ob->write_settings; open(SERIAL, "+<$PORT"); open(MQTT, "|$pubclient"); while (my $line = ) { print(MQTT "$line"); } close(MQTT); mosquitto-1.6.9/misc/currentcost/gnome-panel/0000775000175000017500000000000013626052637020335 5ustar rogerrogermosquitto-1.6.9/misc/currentcost/gnome-panel/CurrentCostMQTT.server0000664000175000017500000000217613626052637024554 0ustar rogerroger mosquitto-1.6.9/misc/currentcost/gnome-panel/CurrentCostMQTT.py0000775000175000017500000000421113626052637023671 0ustar rogerroger#!/usr/bin/env python import gnomeapplet import gtk import mosquitto import sys class CurrentCostMQTT(gnomeapplet.Applet): def on_message(self, mosq, obj, msg): # Message format is "power" self.label.set_text(msg.payload+"W") def set_label(self, val): self.label.set_text(val) def on_change_background(self, applet, type, color, pixmap): applet.set_style(None) applet.modify_style(gtk.RcStyle()) if type == gnomeapplet.COLOR_BACKGROUND: applet.modify_bg(gtk.STATE_NORMAL, color) elif type == gnomeapplet.PIXMAP_BACKGROUND: style = applet.get_style().copy() style.bg_pixmap[gtk.STATE_NORMAL] = pixmap applet.set_style(style) def show_menu(self, widget, event): print "menu" def __init__(self, applet, iid): self.applet = applet self.label = gtk.Label("0W") self.event_box = gtk.EventBox() self.event_box.add(self.label) self.event_box.set_events(gtk.gdk.BUTTON_PRESS_MASK) self.event_box.connect("button_press_event", self.show_menu) self.applet.add(self.event_box) self.applet.set_background_widget(applet) self.applet.show_all() self.mosq = mosquitto.Mosquitto() self.mosq.on_message = self.on_message self.mosq.connect("localhost") self.mosq.loop_start() self.mosq.subscribe("sensors/cc128/ch1", 0) self.applet.connect('change-background', self.on_change_background) def CurrentCostMQTT_factory(applet, iid): CurrentCostMQTT(applet, iid) return gtk.TRUE if len(sys.argv) == 2: if sys.argv[1] == "-d": #Debug mode main_window = gtk.Window(gtk.WINDOW_TOPLEVEL) main_window.set_title("Python Applet") main_window.connect("destroy", gtk.main_quit) app = gnomeapplet.Applet() CurrentCostMQTT_factory(app,None) app.reparent(main_window) main_window.show_all() gtk.main() sys.exit() if __name__ == '__main__': gnomeapplet.bonobo_factory("OAFIID:CurrentCostMQTT_Factory", gnomeapplet.Applet.__gtype__, "MQTT", "0", CurrentCostMQTT_factory) mosquitto-1.6.9/misc/currentcost/gnome-panel/currentcost.png0000664000175000017500000001230413626052637023416 0ustar rogerrogerPNG  IHDR00WsRGBbKGD pHYs ftIME m,tEXtCommentCreated with GIMPWIDAThޭk$uz{z;;"wK.IEG l  LcH,0A r DKb `ǰ2 7AEe>fv=ﮪ{ɇ]1< (TssFxiVNcrv-SՕA.z^ !<霻+@bEv(VFdDx^7Z^nF%֣kOMx̙v% B#,^'d2PAdxE hP1VRj^,};I?Y<ųÉYiT{:p:ܘLǽ_L&{8F# +J{g2`D *jQk?M;]t0F6ky0I^= j8ջPζAy$1F$!c+@%Mi[+nk:RVY/7G3wl`w?}t|\GQX9D֖<B@‰s,ϘfyNARUI8mnm_?o|<j=ywN'r]UQ3oux웍I*;OGƫbUCpbU1:1LVj8ZÓO>/:G'@INpZxڱUm}Ν;cm4&Iypzh93<<~؇+ޣjqLףsZM=GV*daLͿ\[VUED 'Da-[{.~h[RȳdV]Z͖ 'h6A 4=-T*"xʊ;9!6aooϤi\A"'o IRL8K)z7ݴF)FC`gy&+7]4$Ϧ"B`n*G3 aJ<N#L&M&VmUzeFb3'ZƙvTJِ2ɊReՔZu !3 !W(PUEAfIb8d6Som8<@=P3e`^t$">E^}j`ueRݏVU1 tc v(O&5.GGGNck5QܯE^V%ix<&21ưBZ)qxL1Ȼ93~(Q @ 6"ɳ\888޳n5$˦X1+&ςh4Tk ,XɊ`I!3^ $! Zk++gi[2qn5 ;T*)׮>ƕK1w ZƗ@imm8d!Ld;'J,^0޹c(p͓b… TR3M9>d: kkkji>t@Ze9VVɳ cM |ys~ܡޮc,]`6899;7R}cȋe($8d фh\r$jG* BP<ˉίR#\rJ\1rwNseϳzRyW\\B) ce3E#X 9.l[ۻg9KV8>:PUiƀDxXW9z?6έr~c7߾CT~1]k^bX_Y%#;s$Ke̼!:viѐmjCEt5@Ygփ#DZfcE:-ȲIN_{|Ρl3NԈ-z)ZP,G1Qs҅~dݭTVOOy.,gOdc1 ޳O\RZsrpp@$[_΍ڵLjr=X[.Pc 4x,(t>k$T]{Oei7h5f޾6A X1~~lc-8&ZʹՎ^v#1%xp}{}B1B~V;F,JjMⓓSvvwKb-W"OCvVhpZԳ`xL$8x{qw7x\(kA T\i(K(^TU1jİO|QD_wMg +p~V>rۈEޕVJ*q=a0`ELm0J|G<ua:ɸ,^Z"" xSGk DB]B\๛?="`<^"jA5Kj1N؅ x2xѯ3a8b#KN?G3D,'8+\)j.:>̫"e/\SO i0o>uO?''=ob z&fKhe;歧{[ Fc$lO*Ad.vPpyfW;ܳ^oR"B%1j`Z\⹕O{&Grm1zeZv)CDNx&b>,c7Ixң"5x2a%Ix,+m{߽OdeIVJ\^x+~Mݮ^p lVv\R# w^?V*xPΈHyQ@8Q~<rɳO?+/_訫X޽G̥֛_[bl_ zL&u2*\N%w3fJ-+r5& b} 1"jQ ̲}gϾܫ [^m}ORL\>v[}uwgr8bmm-lllH2 :f(5jZs4(zfŸ*˝֋|,lΓO=E=[җoX_wwÃse{f3<JY,T4#DQk ,ԫKϷj|Sq^zyp0O+?ճ޼K?9=]ZQIH̚2o8J} ERINKzsy.+wyxpt*:_7?:>?=̈ (zG,)d^QrIY_~鿊ޛo37{+z/u։Wf/*ս^ _WIgDg`9GvjO*ieV1Oo~wG}U[?xn*SOK:4/_/RowkvtyN^sO\/wg?Ddq}?Pb} }aQӾZhIENDB`mosquitto-1.6.9/misc/currentcost/cc128_log_mysql.pl0000775000175000017500000000266613626052637021413 0ustar rogerroger#!/usr/bin/perl # Log CurrentCost power meter data to a mysql database. # Assumes data is coming in on MQTT topic sensors/cc128 # and in format timestamp,temperature,ch1_data # e.g. 1276605752,12.7,86 # To create database, table and user: # # CREATE DATABASE powermeter; # USE 'powermeter'; # CREATE TABLE powermeter ( # `id` INT NOT NULL auto_increment, # `timestamp` INT NOT NULL, # `temperature` FLOAT NOT NULL DEFAULT 0.0, # `ch1` INT NOT NULL DEFAULT 0, # PRIMARY KEY (`id`), # UNIQUE KEY `timestamp` (`timestamp`) # ) ENGINE=InnoDB DEFAULT CHARSET=utf8; # # CREATE USER 'powermeter'@'localhost' IDENTIFIED BY ''; # GRANT ALL ON powermeter.* to 'powermeter'@'localhost'; use strict; use DBI(); use FileHandle; local $| = 1; my $dbname = "powermeter"; my $dbhost = "localhost"; my $dbusername = "powermeter"; my $dbpassword = ""; my $dbtable = "powermeter"; my $subclient = "mosquitto_sub -t sensors/cc128"; open(SUB, "$subclient|"); SUB->autoflush(1); my $dbh = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost", "$dbusername", "$dbpassword", {'RaiseError' => 1}); my $query = "INSERT INTO powermeter (timestamp, temperature, ch1) VALUES (?,?,?)"; my @vals; my ($timestamp, $temperature, $ch1); while (my $line = ) { @vals = split(/,/, $line); $timestamp = @vals[0]; $temperature = @vals[1]; $ch1 = @vals[2]; $dbh->do($query, undef, $timestamp, $temperature, $ch1); } $dbh->disconnect(); mosquitto-1.6.9/misc/currentcost/cc128_parse.pl0000775000175000017500000000244713626052637020514 0ustar rogerroger#!/usr/bin/perl -w # Read raw cc128 data and republish without xml. # Probably only works if you have a single channel. use strict; use HTTP::Date "str2time"; use FileHandle; local $| = 1; my $subclient = "mosquitto_sub -t sensors/cc128/raw -q 1"; my $pubclient = "mosquitto_pub -t sensors/cc128 -q 1 -l"; my $pubclient_ch1 = "mosquitto_pub -t sensors/cc128/ch1 -q 1 -l"; open(SUB, "$subclient|"); open(PUB, "|$pubclient"); open(PUB_CH1, "|$pubclient_ch1"); SUB->autoflush(1); PUB->autoflush(1); PUB_CH1->autoflush(1); while (my $line = ) { #CC128-v0.120000215.7003112100108 if ($line =~ m# *([\-\d.]+)0[0-9]*10*(\d+) $now){ $r_stamp -= 86400; } print PUB "$r_stamp,$temp,$watts\n"; print PUB_CH1 "$r_stamp $watts\n"; } } mosquitto-1.6.9/misc/currentcost/cc128_read.py0000775000175000017500000000060713626052637020326 0ustar rogerroger#!/usr/bin/python -u import mosquitto import serial usb = serial.Serial(port='/dev/ttyUSB0', baudrate=57600) mosq = mosquitto.Mosquitto() mosq.connect("localhost") mosq.loop_start() running = True try: while running: line = usb.readline() mosq.publish("sensors/cc128/raw", line) except usb.SerialException, e: running = False mosq.disconnect() mosq.loop_stop() mosquitto-1.6.9/readme.md0000664000175000017500000000655213626052637014414 0ustar rogerrogerEclipse Mosquitto ================= Mosquitto is an open source implementation of a server for version 5.0, 3.1.1, and 3.1 of the MQTT protocol. It also includes a C and C++ client library, and the `mosquitto_pub` and `mosquitto_sub` utilities for publishing and subscribing. ## Links See the following links for more information on MQTT: - Community page: - MQTT v3.1.1 standard: - MQTT v5.0 standard: Mosquitto project information is available at the following locations: - Main homepage: - Find existing bugs or submit a new bug: - Source code repository: There is also a public test server available at ## Installing See for details on installing binaries for various platforms. ## Quick start If you have installed a binary package the broker should have been started automatically. If not, it can be started with a basic configuration: mosquitto Then use `mosquitto_sub` to subscribe to a topic: mosquitto_sub -t 'test/topic' -v And to publish a message: mosquitto_pub -t 'test/topic' -m 'hello world' ## Documentation Documentation for the broker, clients and client library API can be found in the man pages, which are available online at . There are also pages with an introduction to the features of MQTT, the `mosquitto_passwd` utility for dealing with username/passwords, and a description of the configuration file options available for the broker. Detailed client library API documentation can be found at ## Building from source To build from source the recommended route for end users is to download the archive from . On Windows and Mac, use `cmake` to build. On other platforms, just run `make` to build. For Windows, see also `readme-windows.txt`. If you are building from the git repository then the documentation will not already be built. Use `make binary` to skip building the man pages, or install `docbook-xsl` on Debian/Ubuntu systems. ### Build Dependencies * c-ares (libc-ares-dev on Debian based systems) - only when compiled with `make WITH_SRV=yes` * libwebsockets (libwebsockets-dev) - enable with `make WITH_WEBSOCKETS=yes` * openssl (libssl-dev on Debian based systems) - disable with `make WITH_TLS=no` * xsltproc (xsltproc and docbook-xsl on Debian based systems) - only needed when building from git sources - disable with `make WITH_DOCS=no` * uthash / utlist - bundled versions of these headers are provided, disable their use with `make WITH_BUNDLED_DEPS=no` Equivalent options for enabling/disabling features are available when using the CMake build. ## Credits Mosquitto was written by Roger Light Master: [![Travis Build Status (master)](https://travis-ci.org/eclipse/mosquitto.svg?branch=master)](https://travis-ci.org/eclipse/mosquitto) Develop: [![Travis Build Status (develop)](https://travis-ci.org/eclipse/mosquitto.svg?branch=develop)](https://travis-ci.org/eclipse/mosquitto) Fixes: [![Travis Build Status (fixes)](https://travis-ci.org/eclipse/mosquitto.svg?branch=fixes)](https://travis-ci.org/eclipse/mosquitto) mosquitto-1.6.9/notice.html0000664000175000017500000002201613626052637014775 0ustar rogerroger Eclipse Foundation Software User Agreement

Eclipse Foundation Software User Agreement

February 1, 2011

Usage Of Content

THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.

Applicable Licenses

Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").

  • Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
  • Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
  • A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins and/or Fragments associated with that Feature.
  • Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.

The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module including, but not limited to the following locations:

  • The top-level (root) directory
  • Plug-in and Fragment directories
  • Inside Plug-ins and Fragments packaged as JARs
  • Sub-directories of the directory named "src" of certain Plug-ins
  • Feature directories

Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in that directory.

THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):

IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.

Use of Provisioning Technology

The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").

You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:

  1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based product.
  2. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be accessed and copied to the Target Machine.
  3. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.

Cryptography

Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.

Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.

mosquitto-1.6.9/epl-v100000664000175000017500000002665713626052637013754 0ustar rogerrogerEclipse Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. "Contributor" means any person or entity that distributes the Program. "Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 3. REQUIREMENTS A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: a) it complies with the terms and conditions of this Agreement; and b) its license agreement: i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. When the Program is made available in source code form: a) it must be made available under this Agreement; and b) a copy of this Agreement must be included with each copy of the Program. Contributors may not remove or alter any copyright notices contained within the Program. Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. mosquitto-1.6.9/libmosquittopp.pc.in0000664000175000017500000000037413626052637016655 0ustar rogerrogerprefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/lib Name: mosquittopp Description: mosquitto MQTT library (C++ bindings) Version: @VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lmosquittopp mosquitto-1.6.9/CONTRIBUTING.md0000664000175000017500000000751213626052637015063 0ustar rogerrogerContributing to Mosquitto ========================= Thank you for your interest in this project. Project description: -------------------- The Mosquitto project has been created to provide a light weight, open-source implementation, of an MQTT broker to allow new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). - - Source ------ The Mosquitto code is stored in a git repository. - https://github.com/eclipse/mosquitto You can contribute bugfixes and new features by sending pull requests through GitHub. ## Legal In order for your contribution to be accepted, it must comply with the Eclipse Foundation IP policy. Please read the [Eclipse Foundation policy on accepting contributions via Git](http://wiki.eclipse.org/Development_Resources/Contributing_via_Git). 1. Sign the [Eclipse ECA](http://www.eclipse.org/legal/ECA.php) 1. Register for an Eclipse Foundation User ID. You can register [here](https://accounts.eclipse.org/user/register). 2. Log into the [Accounts Portal](https://accounts.eclipse.org/), and click on the '[Eclipse Contributor Agreement](https://accounts.eclipse.org/user/eca)' link. 2. Go to your [account settings](https://accounts.eclipse.org/user/edit) and add your GitHub username to your account. 3. Make sure that you _sign-off_ your Git commits in the following format: ``` Signed-off-by: John Smith ``` This is usually at the bottom of the commit message. You can automate this by adding the '-s' flag when you make the commits. e.g. ```git commit -s -m "Adding a cool feature"``` 4. Ensure that the email address that you make your commits with is the same one you used to sign up to the Eclipse Foundation website with. ## Contributing a change 1. [Fork the repository on GitHub](https://github.com/eclipse/mosquitto/fork) 2. Clone the forked repository onto your computer: ``` git clone https://github.com//mosquitto.git ``` 3. If you are adding a new feature, then create a new branch from the latest ```develop``` branch with ```git checkout -b YOUR_BRANCH_NAME origin/develop``` 4. If you are fixing a bug, then create a new branch from the latest ```fixes``` branch with ```git checkout -b YOUR_BRANCH_NAME origin/fixes``` 5. Make your changes 6. Ensure that all new and existing tests pass. 7. Commit the changes into the branch: ``` git commit -s ``` Make sure that your commit message is meaningful and describes your changes correctly. 8. If you have a lot of commits for the change, squash them into a single / few commits. 9. Push the changes in your branch to your forked repository. 10. Finally, go to [https://github.com/eclipse/mosquitto](https://github.com/eclipse/mosquitto) and create a pull request from your "YOUR_BRANCH_NAME" branch to the ```develop``` or ```fixes``` branch as appropriate to request review and merge of the commits in your pushed branch. What happens next depends on the content of the patch. If it is 100% authored by the contributor and is less than 1000 lines (and meets the needs of the project), then it can be pulled into the main repository. If not, more steps are required. These are detailed in the [legal process poster](http://www.eclipse.org/legal/EclipseLegalProcessPoster.pdf). Contact: -------- Contact the project developers via the project's development [mailing list](https://dev.eclipse.org/mailman/listinfo/mosquitto-dev). Search for bugs: ---------------- This project uses [Github](https://github.com/eclipse/mosquitto/issues) to track ongoing development and issues. Create a new bug: ----------------- Be sure to search for existing bugs before you create another one. Remember that contributions are always welcome! - [Create new Mosquitto bug](https://github.com/eclipse/mosquitto/issues) mosquitto-1.6.9/pwfile.example0000664000175000017500000000054313626052637015472 0ustar rogerrogerroger:$6$clQ4Ocu312S0qWgl$Cv2wUxgEN73c6C6jlBkswqR4AkHsvDLWvtEXZZ8NpsBLgP1WAo/qA+WXcmEN/mjDNgdUwcxRAveqNMs2xUVQYA== sub_client:$6$U+qg0/32F0g2Fh+n$fBPSkq/rfNyEQ/TkEjRgwGTTVBpvNhKSyGShovH9KHewsvJ731tD5Zx26IHhR5RYCICt0L9qBW0/KK31UkCliw== pub_client:$6$vxQ89y+7WrsnL2yn$fSPMmEZn9TSrC8s/jaPmxJ9NijWpkP2e7bMJLz78JXR1vW2x8+T3FZ23byJA6xs5Mt+LeOybAHwcUv0OCl40rA== mosquitto-1.6.9/logo/0000775000175000017500000000000013626052637013565 5ustar rogerrogermosquitto-1.6.9/logo/mosquitto.ico0000664000175000017500000010341413626052637016330 0ustar rogerroger hV   F00 % vBD(  $$wwwwR<R<R<R<ww w wR<R<R<R<R<R<]RR<RR|@@@(0` $$$wwwwwwwwww%w%wR<R<R<R<ww9w9wR<R<R<R<R<R<RR<R<-RR~>9y̳x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<xߏDsVX}8[`"v(EJk0?_ @ i"zCpx홏!O lI`8ަȧ_ص|ǚ_`0Kfi/<Húl ,zL_\&feGDfg2GfڝRGF徺@ To/­x]+YH]_Eqb󁻁|3cXS.6[30uZR@3\E"ڳdKρqE8.>fIo EE(c*9w;p-ۓ̲o7 0GXdzFz8ʜoZS|IYPaǴ1b?Qa @TSb=لv*%qf@E<CUc0?1x8=;Ho@ pLɉm FkU$;#LL.1S0PF%ؖaiB'UF:NPD\7$+ ڰKbM<;b`Y`񶳱>68YNiFDU-s*?.Kbq=w p>0,y,JKz U1AiNRc瀔mSjFl Kt_)y [wP(ۼ+YXOu$&Z1:Mo\^{rjn)Ş҃E10C14gXHOFz ֫Zj'~4lU^Q*V6n شPLt?/7 +7-H$Ĥ+}#,m'&^`s&~xkYi^q1*&71+^IU9! o2 lzl'4v_&&or3Hp6%=lSyv8H{c\`&;t'vn:lj7!pMSŹaQs`;"$$jnJ[9Hbga?LqrNv2UV[ȿ)+#]J[q\!׾ XRڐoHOlrC!pRXuZ; (e6ޥz[Gpec}F|Iˀ+c! 0N6֙'L6=Mp{EU͔mhbo%4X/Hy([FzתHH{.O飯HNI]^c" c(+yiz 18>ս~/6FJ^nkQ3`S:\7|OR0'F?{ JHg 0jݖ=Q >G`?0߭6 [sEʑF [>Y.X፪l&܂etv̆o חlR^Q K]~kfc#n_[}olXmWƘ]Is3AJ5\JR%goƞXC=4?JH^2 (s|+sϫ+&? ;vEU Ns}eW}Q|y}P7#GzlgݣuRCU.y 섑%Jipe*;$ivՑFk(p4,O-x_x*YPF%] 9p_\Մؐj1d摮^HOb=/M0`@:gcu1K]KQˀG~ aȻ <(<lw s-9:XF:ʀRHŽunҴS7FTraamy%:4 (`ж]]l\coɁ9J:dO!ݾ}CN!]VHC |#p#*y;=9_9*9ae۽ѮJu@>@zc_@BYQ^l8֗p#i1~6W`"_#%,Us}?(@zsq6ظ\wDUv=#t0z p@cOv̳p %tKɝ ؽf+& ;5Ie_Fvd[L@TIb]U8Ё^&FSF&ʧd Izۭټ@:՞f&uR]6@CJ.96@̣dU_J";T6ge,:$֏S"`꿢 ϒ6\\xG&y[Pl~İVXqXM>Q4a%(3 7~d'd`وR숼wgHҋ<|[4*!u)IدwGV 4UIH#_Ǝ Ulg||=6OªJY%R4$Ovt1kf'/ahu{z"pu8M@)vL8dǠ49a.z>fd n\1p~RP"\WY;(4%|8B5=͓fAl7 q>R4p`(o8򦢻WFSJ XX '-HņȷJBGnxw%n_ް&Su*n0'I_>'{] \YqZ%%uvlHP:U"D;WH>s^@ףPvCyO%v<\RjglơtqpNO Gk{+U`P}ă_V*[-'і,ǎKzdKfg Z7ci]R+$Z _ly{ S1cMq)ŖKw~I6j4IZ=xϏuҸZ';qzlRD&anX/Kb>¼322aۑol`cR\C*Lkъd2.@],#Ii#Z':iwa*cy; }q2-jg (`w@f1r-sp$i?"T:@n;f(5{,/6J;.h4`줿k\~z_auҸCZ'K!W 8 8|Bk˸#ƽ9i=:<"6yd]d#McL׶vL6/y 侎cc`W8Z75:+N7řj V:i'`sl4N(SuS\ &Z4J*,d*PS\CdC:eB%r#M2O7W;J=+yo2ਘc95$< <,8nk ƚ29Y"Ol2!I EXkA;-%L*k`J\W9 eN7n(p66ݸ/ fz8gpo9wÜy$Ӷ7LH[6ѭ@ d@Yq'^F4AGL[$1tsq ;<#/ 5mc3)Egl8{ wxY>S܏4 0vZ$IP[\ll\(~'O £XC{U2"z4s[s3ܝWFw9+|{0u"I=w_-~1X)n ˑg 4MVq_5y{8YW:sJ\-ָr8ů[ݲ gIAqN$l/VR+@1#7`*X/ O3"5JC#w{.rMvwc]PXmY  O6 y|c{X'| 007ȕm y}ɒlȝTZq6G0AZ.fc&6W/7If@͢ƹUzw(+z-(j!R0 WkA.6"@>jb"Y 0F^%c&:)!xPA2A@6^STm;Jc *POYeXHs1$싕zf#811pH#@2}ƍq/2J|u W=.| )AKqK39Kńz3gy.QAV>WjG!ˑ県@f#7@4UD%8!kټrZYkK$Y>Pc^pdLc$ >Tf9r#*"2V RNY}3jpIlϛkș͵Rrdًo'u %5B>[fyy!5Hbd &8;XMWU{1oc:9`rix 6jgָk3,1}xSeq/U5Y<7c(m^x&@1^ sv%NƍR@- KYg+m*ap׃XlɰC~qL)rj[1ʙ2䫎8S3Q (u\ml`KqA`ƸۿxLhw:z;yHy a:+kCpߗcYŒAnC vlJu')YDgz/HC$`#eܗ;Muf/.o>F"QS4.|dFOjPlNjkde3: I vMGQm>'dk*o"[&iL]}]%p7a@# T,]}=(SC}M1"7N&W`&;LɅGqK(9IȗX#KLqܟq977͍.ovR疏}?Y#+]+;6G^( LƑȭ{rҴ2oFؽ*ʸW1Yg[֛:͠~|yx 3z;XPdٟԖ2E䓏oB_FU$ `t/qRHt]d]qFYѻ]oι ±3zG],E6f/f lcQ sPJ}sR 7"3K; $(վX}Xu/2ؽ..<}v[{9~c3S<kt))yNzwsx蝿z.ȻO@>B}Z >|>C (5~%_;l %fviEW9QMH^N$WJiWN=39KGO p;GOߖfPik !/c1nє QVaJyn0>_bNx?)hiW,FVEv-!7vU*pK`I3K;m. #] Ϳ _ (;͕ۖMvzwy똞 1Rlfs9gC;l1Cw@"S8g!=~6ȝTcz y{S O9qeӴw#'R0?.<'G-R(d91)t. ;((Q#zn<, r5X٤'d ZU[I Yԣ 8̱UQ`j]/C"N1Zpwq9X;-)6"MAIOYq%՝j-3rACY'YYn)j!+'cF 1 ~t0M)׃*#= m$ KA9}{#.T8;1Y;u1 g1Ґ?z݆K{ LunY \|sFe]bt Vs^i_ë2u&R;$[0쵥aǧOyDogg`ܪ>氤]i@>'5YwcT R0#`p+Z@/$a7k=UAs.'"+kx T ۂMqFJGJul8<p ˁ'ё|kՌ,(,ޑQ%tf(m0'^!4u @X #}bYN"}[q8,ŵ g!nlˡ`^yH_,# ˙`v a#Jr`=PO i20:/B Kx\FU&N@BeF@ -Γ@6QiS-ǓU)!h2`;RW8 Ic_s~rhBTEZOM#/90ȝNF: &U)6;h #=6tur4XD!ڪZ= F MMc{ w.v ? \Us>Ia/aW؁,u~Reח^Rp>rAC~Ť9kN=75cݙ Wamv}qځHD*/ hԦȫN$5yVTYg j6mXMG g0_s}QF L&]nw_dex9~؁.՟V"뱺,s< Zx k؜9夛*I(Ty'aU ę6,']y56řXya;}}ɛh_n l@DƯ>uVϯF`L] S {džN9!Gh{WE+QFNށ Fcӎ%?`FɕAXލZۊnU魍e?uG<,c;$X;g;y3e$q6@+V@%GŞO04sIb0 FXe-s@@;p$Ϩ$X(%6PZ0 Ht=.KסtVQ[wf47{pBNQ{b<𿅱FrM-^Ȋ*ke!)5+Zdb v"JÁm$[3/4.UAQSTEGZO-EFqq"$X߀;k$0jz_8ե7 M)pd-E1Ͻ 0ҵFruSrkL^$  x,Kz^*\l+9S{ˀ _eTI;غuiȲ' aTpMS IXO5ePLo> :e>8_hϑ-,|T79׾$~+5qOPJ@ےka ]5cI~_I~yz˗[Ӑ+<&Fu%i4Μ3 ukIn~K/7IJϳa * bWc9>y77ֻX̖򷒲UW9)2+]\0Nk3b1owgmk`>%Xuc} bVJ9c.cwt5M W) k֤W3I]NS&"MPI-9V?AR(b_Nt3ti  .CX)Zmj @A^Vu<*UM9,.EqAR֮j-kMB a4zR_gV_XY }r((+m(TL]Oq]QS:%_XSEr֎#&3 ^VGgb}Ғ7s{c)TӱdG>#it`"k%zycS۸4fO_C(hVq7aE_|"Ww$ʭk)Lgrl^*-$}4*\9|.ƭ{o"]QPV&ҩ$mVbǠH̐!lba yJvQ0+Ppށ=0ʷZ*1ye\vKyެ̺c:Hb8.pSc} +o#=.mC͊0!=8;*#89zͨ5W.V ΐEvnn% L-U)_VJ>^2=/o3ZYDvFWQ@`\Bi:X[ BxaMv6XZ:}Igc3YFʛź/O7* ZT gaǸ s(Ö agz"ߛ}ŜUl:#6Fzl{)OcRϯ. Lv].<+h*`')O:pER_\ib( xt(;4y<+3?P~߿$zu)OU HaN:bXӵkzٷF+0'bE>F@_=Yt+? )FYS;/sӓ}A O/&qORHb^?maŊžOWQ6(awF6OyŅZ> 1[16^ Z(&eW0TqSTYfCy8)}y%t@E$Xq4z x}FX\LH!Gu,, 7?A!_$~ Wo?MS,^: @{@{JںkOO Jt#+nDmp+Ke/X50/~zZ;W2;OIbm[[a5-ہﻨ__ h}[w^ ]Ua|tce8fu{vߙ~318K+$)BgMн"%|!PX* ß image/svg+xml mosquitto-1.6.9/logo/legacy/mosquitto-14x14.png0000664000175000017500000000100113626052637020352 0ustar rogerrogerPNG  IHDR*sRGBbKGD pHYs0 tIME ~5IDAT(ϵP3&Yq Te` .ڴhY˅Ap )\6|۸{t8|p0I@cx<өmۂ xt7jYrD"t:P("TU?vBl6[B1) 7` X,h4H$dY$i0$Inw]7Ns Zipn1Mzhx9?X,nE4 j(0RTTmq4,J"I>PJzn6ۍRl ˡh:z hZ,c!p>)d]W'/ pEIENDB`mosquitto-1.6.9/logo/legacy/mosquitto-16x16.png0000664000175000017500000000106613626052637020371 0ustar rogerrogerPNG  IHDRh6sRGBbKGDPPPƇ pHYs tIME :4IDAT(ϵ?P}$J h!XJ,,l? XWYYhaao/` DD%hPT޻Dz,X:3)f J)7LUh0 !r 7ZVTt:e2vK)EwHRH$r<~n81>~*n{β,x^<,d2zXg1!Xy>vFNS>7M3je#$Ir(fl?>??UU\.$qgFZ%0 s8t]NSEAV+v8 jD"1LfۍFBn_MS0  uCQeB޲,,{4E)tz8l6PJ5M4 {IKcBIENDB`mosquitto-1.6.9/logo/mosquitto-logo-min.svg0000664000175000017500000000712313626052637020074 0ustar rogerroger image/svg+xmlmosquitto-1.6.9/logo/mosquitto-logo-only.svg0000664000175000017500000001027313626052637020272 0ustar rogerroger image/svg+xmlmosquitto-1.6.9/logo/mosquitto-text-below.svg0000664000175000017500000002344013626052637020445 0ustar rogerroger image/svg+xmlmosquitto-1.6.9/logo/mosquitto-text-side.svg0000664000175000017500000002330113626052637020255 0ustar rogerroger image/svg+xmlmosquitto-1.6.9/Makefile0000664000175000017500000000630313626052637014267 0ustar rogerrogerinclude config.mk DIRS=lib client src DOCDIRS=man DISTDIRS=man DISTFILES= \ client/ \ examples/ \ installer/ \ lib/ \ logo/ \ man/ \ misc/ \ security/ \ service/ \ src/ \ test/ \ \ CMakeLists.txt \ CONTRIBUTING.md \ ChangeLog.txt \ LICENSE.txt \ Makefile \ about.html \ aclfile.example \ compiling.txt \ config.h \ config.mk \ edl-v10 \ epl-v10 \ libmosquitto.pc.in \ libmosquittopp.pc.in \ mosquitto.conf \ notice.html \ pskfile.example \ pwfile.example \ readme-windows.txt \ readme.md .PHONY : all mosquitto api docs binary check clean reallyclean test install uninstall dist sign copy localdocker all : $(MAKE_ALL) api : mkdir -p api p naturaldocs -o HTML api -i lib -p p rm -rf p docs : set -e; for d in ${DOCDIRS}; do $(MAKE) -C $${d}; done binary : mosquitto mosquitto : ifeq ($(UNAME),Darwin) $(error Please compile using CMake on Mac OS X) endif set -e; for d in ${DIRS}; do $(MAKE) -C $${d}; done clean : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} clean; done set -e; for d in ${DOCDIRS}; do $(MAKE) -C $${d} clean; done $(MAKE) -C test clean reallyclean : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} reallyclean; done set -e; for d in ${DOCDIRS}; do $(MAKE) -C $${d} reallyclean; done $(MAKE) -C test reallyclean -rm -f *.orig check : test test : mosquitto $(MAKE) -C test test ptest : mosquitto $(MAKE) -C test ptest utest : mosquitto $(MAKE) -C test utest install : mosquitto set -e; for d in ${DIRS}; do $(MAKE) -C $${d} install; done ifeq ($(WITH_DOCS),yes) set -e; for d in ${DOCDIRS}; do $(MAKE) -C $${d} install; done endif $(INSTALL) -d "${DESTDIR}/etc/mosquitto" $(INSTALL) -m 644 mosquitto.conf "${DESTDIR}/etc/mosquitto/mosquitto.conf.example" $(INSTALL) -m 644 aclfile.example "${DESTDIR}/etc/mosquitto/aclfile.example" $(INSTALL) -m 644 pwfile.example "${DESTDIR}/etc/mosquitto/pwfile.example" $(INSTALL) -m 644 pskfile.example "${DESTDIR}/etc/mosquitto/pskfile.example" uninstall : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} uninstall; done rm -f "${DESTDIR}/etc/mosquitto/mosquitto.conf.example" rm -f "${DESTDIR}/etc/mosquitto/aclfile.example" rm -f "${DESTDIR}/etc/mosquitto/pwfile.example" rm -f "${DESTDIR}/etc/mosquitto/pskfile.example" dist : reallyclean set -e; for d in ${DISTDIRS}; do $(MAKE) -C $${d} dist; done mkdir -p dist/mosquitto-${VERSION} cp -r ${DISTFILES} dist/mosquitto-${VERSION}/ cd dist; tar -zcf mosquitto-${VERSION}.tar.gz mosquitto-${VERSION}/ sign : dist cd dist; gpg --detach-sign -a mosquitto-${VERSION}.tar.gz copy : sign cd dist; scp mosquitto-${VERSION}.tar.gz mosquitto-${VERSION}.tar.gz.asc mosquitto:site/mosquitto.org/files/source/ cd dist; scp *.html mosquitto:site/mosquitto.org/man/ scp ChangeLog.txt mosquitto:site/mosquitto.org/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out localdocker : reallyclean set -e; for d in ${DISTDIRS}; do $(MAKE) -C $${d} dist; done rm -rf dockertmp/ mkdir -p dockertmp/mosquitto-${VERSION} cp -r ${DISTFILES} dockertmp/mosquitto-${VERSION}/ cd dockertmp/; tar -zcf mosq.tar.gz mosquitto-${VERSION}/ cp dockertmp/mosq.tar.gz docker/local rm -rf dockertmp/ cd docker/local && docker build . mosquitto-1.6.9/edl-v100000664000175000017500000000304113626052637013716 0ustar rogerrogerEclipse Distribution License - v 1.0 Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.